company-guard 0.4.6: custom rules, history and receipt recovery (#1173)

What changes:
- Custom rules: you can manage your own masking rules (aliases, checks for duplicates and limits, warnings before discarding edits) on their own subpage.
- History: rule-version and authorization history, up to 100 entries.
- Masking: tool schemas' enum, const, default and examples values are now masked.
- Receipts: a damaged receipt keeps the stages that are still valid.
- Dist check: `npm test` first checks that dist matches its source.

Version 0.4.3 to 0.4.6.

Run at 13ad10a8 on mica, which merges cleanly over 13a6f4c2:
- `bun test packages/company-guard`: 33 pass, 0 fail.
- `node --test`: 33 pass, 0 fail.
- `bun scripts/check.mjs company-guard`: ok.

What was read:
- The dist diff, line by line against src/protocols.js and src/session-authorization.js.
- The new rules.js fetch: it only calls the page's own receipt routes, the same as authorization.js.

Not run: `build.mjs --check`. esbuild isn't installed on the test box.

Co-authored-by: cyanask <44457432+cyanask@users.noreply.github.com>
This commit is contained in:
cyanask
2026-11-15 23:43:15 +08:00
committed by GitHub
parent fc0c5a882e
commit 8059af3148
21 changed files with 519 additions and 58 deletions
+19 -5
View File
@@ -2,9 +2,9 @@
Local company-name masking and reversible replies for Magpie, with session approvals and local receipts.
当前版本:**0.4.3**(macOS)。
当前版本:**0.4.6**(macOS)。
面向 Magpie 的公司名称保护插件:在模型请求发送前替换识别到的公司名称,在回复返回本机时还原;提供独立的“会话授权”和“脱敏回执”页面。
面向 Magpie 的公司名称保护插件:在模型请求发送前替换识别到的公司名称,在回复返回本机时还原;提供“会话授权”“脱敏规则”和“脱敏回执”三个页面。
## 功能与边界
@@ -56,15 +56,21 @@ magpie plugin add @magpie-community/middleware-company-guard
> 独立原名放行申请:按本会话编号和工作目录只读核对一次状态,如实最终答复并收尾,不等页面审批;原业务保留,续办按用户指令。
## 脱敏规则
“脱敏规则”下设“内置识别”和“自定义规则”两个子页面,默认打开自定义规则。内置识别说明公司全称、明确名称字段、材料中的简称定义及识别边界;自定义规则可新增、编辑或移除名称,为同一主体配置多个简称与别名。名称按文字匹配,不执行正则表达式;名称与别名合计最多512个。不同写法分别生成代号并按原写法还原,不提供自动主体归并。
切换子页面或主页面时,有未保存修改会先提示。自定义区域底部显示规则版本摘要,会话授权页另有授权变更记录,两者最多展示100条摘要,与最近25个请求的回执保留窗口分别计算。历史摘要不含原名、密钥或会话正文;旧摘要缺失不代表从未变更。并发修改会先核对版本,避免覆盖其他窗口的规则。
## 回执
在“脱敏回执”页面先选智能体,再选会话任务,查看替换数量和限时明细。任务列表随智能体选择变化,筛选范围仍是所有智能体合计保留的最近 25 个请求;某个智能体没有匹配回执时会显示空结果。处理结果保留在汇总和明细中。
在“脱敏回执”页面先选智能体,再选会话任务,查看替换数量和限时明细。任务列表随智能体选择变化,筛选范围仍是所有智能体合计保留的最近 25 个请求;某个智能体没有匹配回执时会显示空结果。处理结果按“已完成、待完成确认、需关注”三组汇总,具体原因保留在明细中。
页面可见时默认每 10 秒刷新,展开明细时暂停;关闭自动刷新后,页面保留最近一次结果。刚发起的请求在回复结束前可能暂时等待确认,这与处理失败分别记录。
同步检查和回复处理的确认会随回执保存,日志轮转不会抹去已保存的确认。同步检查、回复处理及正常流式结束事件均已确认时,可以据此确认完成;明细会区分流式确认与宿主确认。缺少必要检查、宿主明确报告失败或回复仍有本次代号残留时,不会标为完成。未命中不代表没有敏感名称。
桌面版默认读取 macOS 的 `~/Library/Logs/magpie/app.log` 来核对处理确认。使用 `magpie web` 或自行重定向日志时,可在插件选项 `appLog` 中指定实际日志文件的绝对路径。保存的阶段确认和当前日志共同用于核对。必要依据仍不齐全时保留“未确认”,不会仅因等待时间较长而标为成功。
桌面版默认读取 macOS 的 `~/Library/Logs/magpie/app.log` 来核对处理确认。使用 `magpie web` 或自行重定向日志时,可在插件选项 `appLog` 中指定实际日志文件的绝对路径。保存的阶段确认和当前日志共同用于核对。必要依据仍不齐全时保留未确认状态,不会仅因等待时间较长而标为成功。读取时会报告回执损坏或截断问题,并保留可恢复的有效阶段记录,不能把缺失记录当作已完成。
可从源码目录读取本机计数报告:
@@ -74,6 +80,14 @@ node receipt-report.mjs --json
本仓库不包含用户配置、授权名单、业务材料或本机验收记录。
## 授权容量与记录清理
授权表最多100条登记,普通已撤销记录在后续授权操作中清理,不再永久占位。有效授权不会因容量不足被自动删除;仍有旧独立授权的会话,保留必要的撤销标记,防止旧授权重新生效。授权变更摘要另行保留,不依赖当前授权表保存历史。
页面校验、授权规划和请求处理共用100条上限。授权表序列化长度最多3×1024×1024个字符,授权接口正文最多4 MiB;每份指定名单最多32个名称。待确认申请另按64条、24小时计算。归档Codex会话不会自动撤权,需要在插件中主动恢复脱敏后才能释放相应名额。
回归检查覆盖连续授权、撤销106个不同会话后再批准一个会话,已有64条撤销记录的恢复、满100条有效授权的请求处理、容量不足时保留有效授权、旧版撤销标记保护及大小限制。本次未进行30、50、100条记录的延迟压测,不提供未经测量的延迟承诺。
## 开发与测试
```sh
@@ -82,7 +96,7 @@ npm test
npm run build
```
开发和测试需要 Node.js 20 或更新版本。测试使用独立的临时配置和虚构名称,覆盖四种协议的往返处理、流式分段还原、工具参数、会话授权与撤销,以及首次初始化和密钥权限。同一套测试还验证已构建中间件与 Hook 的协作、日志轮转和回执淘汰后的快照核对,并检查失败通知和代号残留不会被提升为成功。
开发和测试需要 Node.js 20 或更新版本。测试使用独立的临时配置和虚构名称,覆盖四种协议的往返处理、流式分段还原、工具参数、会话授权与撤销,以及首次初始化和密钥权限。同一套测试还验证已构建中间件与 Hook 的协作、工具结构中的默认值和示例脱敏、规则校验及审计摘要、损坏回执恢复、日志轮转和回执淘汰后的快照核对,并检查失败通知和代号残留不会被提升为成功。构建检查要求已提交的中间件与源码一致。
`dist/` 已提交,可直接从 Git 安装,无需安装时构建。运行时使用 Magpie 自带的 Bun,无额外 npm 运行时依赖;esbuild 仅用于开发构建。社区版本由本仓库的分发流程提供;上述社区安装命令在 PR 合并并完成分发后可用。合并前,可从仓库根目录运行 `magpie plugin add ./packages/company-guard` 进行本地验证。
+12 -3
View File
@@ -814,13 +814,21 @@ function inspectRequest(body, protocol) {
if (typeof body.system === "string") add(body, "system", { source: "instruction", index: -1 });
else blocks(body.system, { source: "instruction", index: -1 });
if (body.systemInstruction) blocks(body.systemInstruction.parts, { source: "instruction", index: -1 });
const schemaValue = (owner, key, depth) => {
if (++nodes > 5e4 || depth > 48) throw new Error("input_structure_limit");
const value = owner[key];
if (typeof value === "string") add(owner, key, { source: "schema", index: -1 });
else if (value && typeof value === "object") for (const k of Object.keys(value)) schemaValue(value, k, depth + 1);
};
const schema = (v, depth = 0) => {
if (!v || typeof v !== "object") return;
if (++nodes > 5e4 || depth > 48) throw new Error("input_structure_limit");
for (const k of Object.keys(v)) {
if (["description", "title"].includes(k)) add(v, k, { source: "schema", index: -1 });
else if (k === "enum" && Array.isArray(v[k])) for (let i = 0; i < v[k].length; i++) add(v[k], i, { source: "schema", index: -1 });
else if (typeof v[k] === "object") schema(v[k], depth + 1);
else if (["enum", "const", "default", "examples"].includes(k)) schemaValue(v, k, depth + 1);
else if (["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"].includes(k) && v[k] && typeof v[k] === "object") {
for (const child of Object.values(v[k])) schema(child, depth + 1);
} else if (typeof v[k] === "object") schema(v[k], depth + 1);
}
};
schema(body.tools);
@@ -853,6 +861,7 @@ function safeInput(body, protocol) {
// src/session-authorization.js
var PREFIX = "nero.session.authorization.v1\0";
var validId = (value) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{1,127}$/.test(value);
var AUTHORIZATION_ENTRY_LIMIT = 100;
function sessionIdentity(body, ctx) {
if (ctx?.agent !== "codex" || ctx.origin && !["local", "magpie-key"].includes(ctx.origin)) return null;
let meta = body?.client_metadata?.["x-codex-turn-metadata"] || body?.client_metadata;
@@ -901,7 +910,7 @@ function resolveAuthorization(body, ctx) {
const id = sessionIdentity(body, ctx);
if (!id) return { record: null, reason: "request_identity_unavailable", managed: false };
const entries = ctx.options?.sessionAuthorizations;
if (!Array.isArray(entries) || entries.length > 64) return { record: null, managed: false };
if (!Array.isArray(entries) || entries.length > AUTHORIZATION_ENTRY_LIMIT) return { record: null, managed: false };
const matching = entries.filter((e) => e?.session === id.session);
if (!matching.length) return { record: null, managed: false };
if (matching.length !== 1) return { record: null, managed: true, reason: "authorization_invalid" };
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@magpie-community/middleware-company-guard",
"version": "0.4.1",
"version": "0.4.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@magpie-community/middleware-company-guard",
"version": "0.4.1",
"version": "0.4.6",
"license": "MIT",
"devDependencies": {
"esbuild": "0.25.12"
+4 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/middleware-company-guard",
"version": "0.4.3",
"version": "0.4.6",
"type": "module",
"license": "MIT",
"description": "Local company-name masking, reversible replies and session approvals for Magpie",
@@ -55,8 +55,9 @@
"codex"
],
"scripts": {
"build": "esbuild src/company-guard.js --bundle --format=esm --target=es2020 --outfile=dist/company-guard.middleware.js",
"test": "node --test test/*.test.mjs"
"build": "node scripts/build.mjs",
"check:dist": "node scripts/build.mjs --check",
"test": "npm run check:dist && node --test test/*.test.mjs"
},
"devDependencies": {
"esbuild": "0.25.12"
+13 -3
View File
@@ -5,7 +5,10 @@ const count = value => value ?? '—';
const label = status => status==='已替换,回复处理完成'?'已替换 · 回复完成':status;
const statusOf = r => r.statusLabel || r.status;
const agentsOf = r => r.agentIds?.length ? r.agentIds : [r.agent || 'unknown'];
let report=null,busy=false,pageVisible=true,base,readKey,expanded=null,expiryTimer;
let report=null,busy=false,pageVisible=true,base,readKey,expanded=null,expiryTimer,selectedCategory='';
const category=r=>r.status==='处理失败'?'attention':['已替换,回复处理完成','授权放行','未命中'].includes(r.status)?'completed':r.statusCode==='awaiting_completion'?'waiting':'attention';
const categories=[['','全部请求'],['completed','已完成'],['waiting','待完成确认'],['attention','需关注']];
const categoryHelp={'':'当前日期、智能体和任务筛选下保留的请求。',completed:'已取得完成确认,包括已脱敏、授权放行和未命中。',waiting:'尚未取得完整完成确认,不代表请求仍在运行。',attention:'确认缺失、调用未完成或处理失败;请打开明细查看原因。'};
function el(tag,text,cls) {const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;}
function agentRows() {const selected=$('agent').value;return (report?.rows || []).filter(r=>!selected || agentsOf(r).includes(selected));}
function updateTasks() {
@@ -48,6 +51,11 @@ async function showDetail(r,tr,button) {
cell.append(el('div','替换内容','detail-title'),content);content.append(el('p','正在读取本机明细…','detail-message'));
for(const [k,v] of [['智能体',r.agentLabel || '来源未记录'],['处理结果',label(statusOf(r))],['同步检查',r.requestChecked?'已确认':'缺少确认'],['回复处理',r.replyProcessingOK===true?'成功':r.replyProcessingOK===false?'未成功':'缺少确认'],['完成确认',r.completionSource==='stream'?'流式回复已正常结束':r.hostCompletionObserved===true?'宿主已完成':r.hostCompletionObserved===false?'调用未完成':'尚未取得']])meta.append(el('span',k+':'+v));
for(const [key,s] of Object.entries(r.scopes || {}))meta.append(el('span',`${scopeNames[key] || key} ${s.replacements} 处 / 检查 ${s.checkedTexts} 段`));
const reasonNames={session_all_active:'全部名称授权有效',session_names_active:'指定名单授权有效',task_not_active:'授权已失效',task_request_too_large:'请求超出授权检查容量',grant_state_unavailable:'授权记录暂不可用',request_identity_unavailable:'无法核验授权身份',authorization_invalid:'授权校验未通过',session_revoked:'此会话已恢复脱敏',task_identity_mismatch:'会话或工作目录不匹配',session_active:'会话授权有效',session_task_active:'会话授权有效',turn_grant_active:'本轮授权有效',no_matching_grant:'没有匹配授权'};
meta.append(el('span','保护方式:'+({original:'按授权放行',public_lookup:'公开查询范围放行',masked:'默认脱敏'}[r.authorization]||'未记录')),el('span','授权范围:'+({all:'全部名称',names:'指定名单',none:'无'}[r.authorizationCoverage]||'未记录')),el('span','放行处数:'+(r.authorization==='original'&&r.authorizationCoverage==='all'?'全部名称授权,不逐项统计':count(r.allowedOccurrences))),el('span','授权核对:'+(reasonNames[r.authorizationReason]||'详见当前授权范围')));
meta.append(el('span','采用自动简称:'+count(r.taskAliases)),el('span','简称冲突:'+count(r.aliasConflicts)));
if(r.aliasLimitReached||r.aliasConflicts)cell.append(el('p','部分自动简称未采用:'+(r.aliasLimitReached?'超过本次识别数量上限。':'存在指向不同主体的冲突。')+'请核对材料,必要时补充自定义规则。','detail-message'));
if(r.rulesRevision)meta.append(el('span','规则版本:'+r.rulesRevision.slice(0,12)));
cell.append(meta);if(r.statusReason)cell.append(el('p',r.statusReason,'detail-message'));
cell.append(el('div',`任务 ${r.taskTitle ? r.taskTitle+' · ' : ''}${r.task || r.thread || '未知'} · 请求 ${r.id} · 插件 ${r.version || '未知'}`,'identity mono'));row.append(cell);tr.after(row);
try {
@@ -62,9 +70,11 @@ async function showDetail(r,tr,button) {
}
function render() {
closeDetail();const selected=$('task').value;
const rows=agentRows().filter(r=>!selected || (r.task || r.thread || '')===selected);
const matching=agentRows().filter(r=>!selected || (r.task || r.thread || '')===selected),rows=matching.filter(r=>!selectedCategory||category(r)===selectedCategory);
$('totals').replaceChildren();
for(const [n,name] of [[rows.length,'请求'],[rows.filter(r=>r.status==='已替换,回复处理完成').length,'替换与回复完成'],[rows.filter(r=>r.status==='未确认' && statusOf(r)!=='调用未完成').length,'证据待齐'],[rows.filter(r=>statusOf(r)==='调用未完成').length,'调用未完成'],[rows.filter(r=>r.status==='处理失败').length,'失败']]){const v=el('span');v.append(el('b',n),document.createTextNode(name));$('totals').append(v);}
for(const [id,name] of categories){const n=id?matching.filter(r=>category(r)===id).length:matching.length,button=el('button');button.type='button';button.className='summary-filter';button.title=categoryHelp[id];button.setAttribute('aria-label',`${n} ${name}。${categoryHelp[id]}`);button.setAttribute('aria-pressed',String(id===selectedCategory));button.append(el('b',n),document.createTextNode(' '+name));button.addEventListener('click',()=>{selectedCategory=id;render();});$('totals').append(button);}
const health=report?.health;$('receipt-health').textContent=health?.available===false?'尚未取得回执保存状态,请刷新核对。':health?.writeFailed?'回执保存异常:下方记录可能不是最新。请保留本机日志并检查存储。':health?.recoveredFiles?'已隔离损坏回执并保留原件,后续保存已恢复。':'';$('receipt-health').hidden=!$('receipt-health').textContent;
if(health?.lastSuccessfulWrite)$('receipt-health').title='最近保存成功:'+new Date(health.lastSuccessfulWrite).toLocaleString('zh-CN');
const diagnosticCount=report?.diagnostics?.observed || 0;$('diagnostics').hidden=!diagnosticCount;
$('diagnostics').textContent=diagnosticCount?`当日跨任务记录到 ${diagnosticCount} 次插件处理超时或异常;日志没有请求编号,无法归到某一条回执。`:'';
$('rows').replaceChildren();
@@ -1,10 +1,10 @@
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>会话授权</title><script src="bridge.js"></script><link rel="stylesheet" href="style.css"><script src="authorization.js" defer></script></head>
<body class="authorization-page"><main><nav class="tabs" aria-label="公司名称保护"><a href="session-authorization.html" aria-current="page">会话授权</a><a href="./">脱敏回执</a></nav>
<body class="authorization-page"><main><header class="page-topbar"><h1 class="sr-only">会话授权</h1><nav class="tabs" aria-label="公司名称保护"><a href="session-authorization.html" aria-current="page">会话授权</a><a href="rules.html">脱敏规则</a><a href="./">脱敏回执</a></nav><p class="page-description">默认脱敏,仅对你确认的会话和范围放行原名。</p></header>
<section id="authorization-panel" aria-label="会话原名授权">
<div class="authorization-heading"><div><h1>会话授权</h1><p>默认脱敏,仅对你确认的会话和范围放行原名。</p></div><button id="authorization-refresh" type="button">刷新授权</button></div>
<p id="authorization-notice" role="status" aria-live="polite">正在读取授权…</p>
<div class="authorization-heading"><p id="authorization-notice" role="status" aria-live="polite">正在读取授权…</p><button id="authorization-refresh" type="button">刷新授权</button></div>
<p class="authorization-boundary">目前仅支持 Codex 会话申请原名授权。授权按会话与工作目录生效,持续到主动恢复脱敏。</p>
<div class="authorization-guide"><span>申请放行</span><p>在目标会话单独发送 <code>申请本会话原名放行</code>,再到这里确认范围。</p><details><summary>使用说明</summary><p>待确认申请保留24小时,申请本身不会启用授权或暂停任务。任务名称只用于识别,授权以会话编号和工作目录为准。其他会话、分叉和子任务不会自动取得授权。</p></details></div>
<section id="authorization-pending-section" aria-labelledby="pending-title" hidden><h2 id="pending-title">待确认申请</h2><div id="authorization-pending" class="authorization-list"></div></section>
<section id="authorization-editor" class="authorization-editor" aria-labelledby="editor-title" hidden>
@@ -20,4 +20,4 @@
<p class="authorization-footnote">授权持续到你主动恢复脱敏。恢复仅影响后续请求,已发送原文不能撤回;图片不做文字识别。</p>
</section>
</main></body></html>
<details class="audit-history"><summary><svg class="history-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="8.5"/><path d="M12 7v5l3 2"/></svg><span class="history-heading"><span class="history-title">授权变更记录</span><span class="history-description">查看批准放行与恢复脱敏的历史</span></span><span class="history-action"><span class="history-open">查看记录</span><span class="history-close">收起记录</span><span aria-hidden="true">↗</span></span></summary><p>这里展示最近最多100条授权变更摘要,不含原名、密钥或会话正文。脱敏回执另按最近25个请求保留。旧摘要缺失不代表从未变更。</p><div id="authorization-history" role="status">展开后读取</div></details></main></body></html>
+16 -3
View File
@@ -18,8 +18,12 @@ async function authorizationPost(route,body){
function sessionCard(row,kind){
const card=el('article',undefined,'authorization-card'),text=el('div',undefined,'authorization-task'),scope=el('div',undefined,'authorization-scope');
const title=el('h3',row.taskTitle || '会话 '+short(row.session));title.title=row.taskTitle || row.session;
const identity=el('p',undefined,'authorization-identity');identity.append(el('span',row.agentLabel || '来源未记录','agent-source'),el('span',row.session,'mono'),el('span',row.workspace,'authorization-workspace'));
text.append(title,identity);
const heading=el('div',undefined,'authorization-title'),agent=el('span',undefined,'authorization-agent');
agent.append(el('span','智能体','authorization-agent-label'),el('strong',row.agentLabel || '来源未记录'));
heading.append(agent,title);
const identity=el('p',undefined,'authorization-identity');identity.append(el('span',row.session,'mono'),el('span',row.workspace,'authorization-workspace'));
text.append(heading,identity);
if(kind!=='pending'){const details=el('details',undefined,'authorization-range');details.append(el('summary','查看授权范围'));if(row.coverage==='all')details.append(el('p','此会话内全部公司名称,包括后续历史和工具文字。'));else{const list=el('ul');for(const name of row.names||[])list.append(el('li',name));details.append(list,el('p','仅上述写法放行;简称与别名不会自动随全称放行。'));}text.append(details);}
scope.append(el('span',kind==='pending'?'等待确认':row.coverage==='all'?'全部公司名称':`${Number(row.nameCount).toLocaleString('zh-CN')} 个名称`,'authorization-scope-label'));
if(kind!=='pending'&&row.coverage!=='all')scope.append(el('span',row.legacy?'已有名单授权':'指定名单','detail-message'));
const at=kind==='pending'?row.requestedAt:row.created;
@@ -53,7 +57,7 @@ function openAuthorization(row){
function closeAuthorization(){$('authorization-editor').hidden=true;editingRequest=null;$('authorization-name-list').value='';$('authorization-file').value='';}
function updateAuthorizationScope(){
const all=$('authorization-form').elements.coverage.value==='all';$('authorization-names').hidden=all;
$('authorization-scope-note').textContent=all?'此会话后续发送的历史和工具文字也会保留公司原名。其他会话、分叉和子任务照常脱敏。':'名单外名称继续脱敏。其他会话、分叉和子任务不会自动取得授权。';
$('authorization-scope-note').textContent=all?'此会话后续发送的历史和工具文字也会保留公司原名。其他会话、分叉和子任务照常脱敏。':'按填写的具体名称放行,简称和别名需逐项填写,不会随全称自动放行。名单外名称继续脱敏;其他会话、分叉和子任务不会自动取得授权。';
}
function openRevocation(row,card){
document.querySelector('.revocation-confirm')?.remove();revocationOpen=true;const confirm=el('div',undefined,'revocation-confirm');
@@ -100,3 +104,12 @@ $('authorization-approve').addEventListener('click',event=>{if(!event.isTrusted|
async function start(){try{await magpie.ready;const options=await magpie.options.get();readKey=options.receiptReadKey;authorizationKey=options.authorizationKey;if(!/^[a-f0-9]{64}$/.test(readKey||"")||!/^[a-f0-9]{64}$/.test(authorizationKey||""))throw new Error("授权服务尚未配置,请联系维护。");base=new URL(".",location.href).href;await refreshAuthorizations();magpie.onVisibility?.(visible=>{if(visible&&!editingRequest&&!authorizationBusy&&!revocationOpen)refreshAuthorizations();});setInterval(()=>{if(magpie.visible&&!editingRequest&&!authorizationBusy&&!revocationOpen)refreshAuthorizations();},10000);}catch(error){authorizationNotice(error.message||"授权服务暂不可用,请重新打开此页。",true);}}
start();
$('authorization-history').parentElement.addEventListener('toggle',async()=>{
if(!$('authorization-history').parentElement.open)return;
try{const data=await api('audit');$('authorization-history').replaceChildren();
for(const row of data.authorizations){const line=el('p',undefined,'history-row'),time=el('time',new Date(row.at).toLocaleString('zh-CN'));time.dateTime=row.at;
line.append(time,el('span',(row.action==='approve'?'批准放行':'恢复脱敏')+' · 会话 '+row.session.slice(0,8)+' · '+(row.action==='revoke'?'恢复默认脱敏':row.coverage==='all'?'全部名称':row.nameCount+' 个名称')));$('authorization-history').append(line);}
if(!data.authorizations.length)$('authorization-history').textContent='暂无可用记录。';
}catch{$('authorization-history').textContent='记录暂时无法读取,请重新展开重试。';}
});
+4 -4
View File
@@ -1,8 +1,7 @@
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>脱敏回执</title><script src="bridge.js"></script><link rel="stylesheet" href="style.css"><script src="app.js" defer></script></head>
<body><main><nav class="tabs" aria-label="公司名称保护"><a href="session-authorization.html">会话授权</a><a href="./" aria-current="page">脱敏回执</a></nav>
<h1 class="page-title">脱敏回执</h1>
<body><main><header class="page-topbar"><h1 class="sr-only">脱敏回执</h1><nav class="tabs" aria-label="公司名称保护"><a href="session-authorization.html">会话授权</a><a href="rules.html">脱敏规则</a><a href="./" aria-current="page">脱敏回执</a></nav><p class="page-description">查看最近25个请求的脱敏与还原结果。</p></header>
<section id="receipts-panel" aria-label="脱敏回执">
<form id="filters" class="filters">
<label>日期(UTC)<input id="date" type="date" required></label>
@@ -11,14 +10,15 @@
<button id="refresh" type="button">刷新</button><label class="auto"><input id="auto" type="checkbox" checked>自动刷新</label>
</form>
<div class="summary-line"><div id="totals" aria-label="当前筛选汇总"></div><span id="notice" role="status" aria-live="polite">正在读取…</span></div>
<p id="receipt-health" class="detail-message" role="status" hidden></p>
<p id="diagnostics" class="detail-message" role="status" hidden></p>
<section aria-label="逐请求回执">
<div class="table-wrap" tabindex="0" aria-label="回执表格,可横向滚动">
<table class="requests"><thead><tr><th>时间(北京)</th><th>智能体</th><th>任务 / 请求</th><th class="number">名称 / 替换处数</th><th class="number">还原名称</th><th class="number">用时</th><th>明细</th></tr></thead><tbody id="rows"></tbody></table>
</div>
<p id="empty" hidden>最近保留的 25 个请求中没有匹配的回执,不能据此判断请求已受保护。</p>
<p id="empty" hidden>当前筛选没有匹配回执(仅保留最近25个请求),不能据此判断请求已受保护。</p>
</section>
<details class="explanation"><summary>记录说明 · 仅本机查看</summary><p>回执列表与替换明细按所有任务合计保留最近 25 个请求,超过后自动清理最早记录。清理不影响正在处理的请求还原。明细另有 30 分钟期限,只存内存,重启插件后清空;旧明细不能补出原名。自动刷新间隔为 10 秒,展开明细时暂停。</p><p>处理结果见汇总和明细。回复已通过流式处理并正常结束时,可通过流式记录确认完成;缺少独立完成通知会在明细中说明。等待完成通知不证明请求仍在运行;调用未完成可能由取消、上游失败或采集超限造成。未命中不代表没有敏感名称;回复未使用代号时,还原数可以为 0。</p><p>日期按 UTC 归档,时间按北京显示。日期和任务筛选只作用于保留的最近 25 个请求。已取得的处理确认随回执保存;复核报告另外保留固定样本的确认快照。智能体来源取自请求及本机索引,旧记录无法核实时显示“来源未记录”。</p></details>
<details class="explanation"><summary>记录说明 · 仅本机查看</summary><p>回执列表与替换明细按所有任务合计保留最近 25 个请求,超过后自动清理最早记录。清理不影响正在处理的请求还原。明细最多保留30分钟,也可能因内存容量上限提前淘汰,只存内存,重启插件后清空;旧明细不能补出原名。自动刷新间隔为 10 秒,展开明细时暂停。</p><p>汇总按已完成、待完成确认、需关注三组展示。已完成包含已脱敏、授权放行和未命中;需关注包含确认缺失、调用未完成和处理失败,具体原因见明细。回复已通过流式处理并正常结束时,可通过流式记录确认完成;缺少独立完成通知会在明细中说明。等待完成通知不证明请求仍在运行;调用未完成可能由取消、上游失败或采集超限造成。未命中不代表没有敏感名称;回复未使用代号时,还原数可以为 0。</p><p>日期按 UTC 归档,时间按北京显示。日期和任务筛选只作用于保留的最近 25 个请求。已取得的处理确认随回执保存;复核报告另外保留固定样本的确认快照。智能体来源取自请求及本机索引,旧记录无法核实时显示“来源未记录”。</p></details>
</section>
</main></body></html>
+21
View File
@@ -0,0 +1,21 @@
.rules-page main{max-width:1160px;padding-bottom:28px}
.builtin-status{border:1px solid color-mix(in srgb,var(--magpie-accent,#a292ff) 35%,var(--magpie-line,#35353d));border-radius:20px;padding:4px 10px;font-size:11px;white-space:nowrap}.builtin-intro{font-size:12px;line-height:1.75;margin:16px 0;color:var(--magpie-muted,#aaaab5);max-width:960px}.recognition-rules{display:grid;gap:12px;margin:0}.recognition-rules>div{display:grid;grid-template-columns:190px minmax(0,1fr);gap:20px;padding:18px;border:1px solid var(--magpie-line,#35353d);border-radius:8px;background:var(--magpie-bg,#19191d)}.recognition-rules dt{display:flex;align-items:flex-start;gap:10px;font-size:14px;font-weight:650;line-height:1.55}.recognition-rules dt small{display:block;margin-top:5px;font-size:11px;font-weight:400;color:var(--magpie-muted,#aaaab5)}.recognition-icon{display:flex;align-items:center;justify-content:center;width:32px;height:32px;flex:none;border-radius:7px;background:color-mix(in srgb,var(--magpie-accent,#a292ff) 9%,var(--magpie-bg,#19191d));color:var(--magpie-accent,#a292ff)}.recognition-icon svg{width:21px;height:21px}.recognition-rules dd{margin:0;font-size:13px;line-height:1.8}.recognition-rules dd p{margin:0 0 8px}.recognition-rules dd p:last-child{margin:0}.recognition-boundaries{margin-top:18px;padding:16px 18px;border-left:3px solid color-mix(in srgb,var(--magpie-accent,#a292ff) 55%,var(--magpie-line,#35353d));background:color-mix(in srgb,var(--magpie-bg,#19191d),var(--magpie-fg,#ededf0) 3%);border-radius:0 7px 7px 0}.recognition-boundaries h3{margin:0 0 9px;font-size:13px}.recognition-boundaries ul{margin:0;padding-left:18px;font-size:12px;line-height:1.75}.recognition-boundaries li+li{margin-top:7px}
.rule-help{font-size:13px!important;color:var(--magpie-fg,#ededf0)!important}.recognition-rules dd,.recognition-boundaries ul{font-size:13px!important}.rule-actions{position:sticky;bottom:0;background:var(--magpie-bg,#19191d);padding:9px 0}.rule-actions p{color:var(--magpie-fg,#ededf0)}
.rules-summary,.rules-toolbar,.editor-heading,.builtin-heading{display:flex;align-items:center;justify-content:space-between;gap:12px}
.rules-page h2{font-size:14px;font-weight:600;margin:0}.rules-summary{align-items:baseline;flex-wrap:wrap;margin:12px 0 18px;color:var(--magpie-muted,#aaaab5);font-size:12px}
#rule-count{color:var(--magpie-fg,#ededf0)}#rule-notice.error,#editor-message.error{color:var(--magpie-error,light-dark(#b42318,#ffb4ab))}
.rules-toolbar{justify-content:flex-start;margin:18px 0 12px}.rule-search{width:360px;max-width:60%}.rule-search input{width:100%}
.rules-table{table-layout:fixed;min-width:600px}.rules-table th:first-child{width:40%}.rules-table th:nth-child(2){width:auto}.rules-table th:last-child{width:132px}.rules-table th,.rules-table td{padding:12px 14px;vertical-align:top}.rules-table td:first-child{font-weight:550;overflow-wrap:anywhere}.rules-table td:nth-child(2){overflow-wrap:anywhere}.rules-table tbody tr:last-child td{border-bottom:0}
.rule-operations{text-align:right;white-space:nowrap}.rule-operations button{height:30px;padding:4px 9px;font-size:12px}.rule-operations button:last-child{background:transparent;border-color:transparent;color:var(--magpie-muted,#aaaab5)}.rule-operations button+button{margin-left:6px}.rule-alias{display:inline-block;max-width:100%;box-sizing:border-box;padding:2px 7px;border:1px solid var(--magpie-line,#414147);border-radius:6px;background:color-mix(in srgb,var(--magpie-accent,#a292ff) 5%,var(--magpie-bg,#19191d));margin:0 5px 5px 0;font-size:12px;overflow-wrap:anywhere}.no-alias{color:var(--magpie-muted,#aaaab5);font-size:12px}
#rule-empty{padding:25px 16px;margin:0;text-align:center;color:var(--magpie-muted,#aaaab5)}.rules-footnote{font-size:12px;line-height:1.65;color:var(--magpie-muted,#aaaab5);margin:10px 0 0}
.rule-confirm{border:1px solid var(--magpie-line,#414147);border-radius:7px;margin:0 0 20px;padding:16px;background:color-mix(in srgb,var(--magpie-bg,#19191d),var(--magpie-fg,#ededf0) 2%)}
.editor-heading{margin:0 0 14px}.editor-heading #draft-state{font-size:12px;color:var(--magpie-muted,#aaaab5)}#rule-form label{font-size:13px;color:var(--magpie-fg,#ededf0);position:relative}#rule-name{width:100%;height:34px;margin-top:3px}
.alias-editor{border:0;padding:16px 0 0;border-top:1px solid var(--magpie-line,#35353d);margin:18px 0 0;min-width:0}.alias-editor legend{width:100%;box-sizing:border-box;padding:0;display:flex;gap:10px;align-items:baseline;font-size:13px;font-weight:550}.alias-editor legend span{font-weight:400;font-size:12px;color:var(--magpie-muted,#aaaab5)}#rule-aliases{display:grid;gap:8px;max-height:240px;overflow:auto;padding:3px;margin:8px -3px}.alias-input-row{display:grid;grid-template-columns:116px minmax(0,1fr) auto;align-items:center;gap:10px}.alias-input-row input{width:100%;height:34px}.alias-input-row button{min-width:52px}.alias-toolbar{display:flex;align-items:center;gap:12px;margin-top:8px}.alias-toolbar span{font-size:12px;color:var(--magpie-muted,#aaaab5)}
.rule-help{color:var(--magpie-muted,#aaaab5);font-size:12px;line-height:1.65;margin:5px 0 13px}.rule-actions{display:flex;justify-content:flex-end;align-items:center;flex-wrap:wrap;gap:8px}.rule-actions p{flex:1;margin:0;font-size:12px}.rule-actions .primary{border-color:var(--magpie-accent,#a292ff);font-weight:600}#remove-name{font-weight:600;overflow-wrap:anywhere;margin:9px 0}
.custom-rules,.builtin-rules{padding:22px;border:1px solid var(--magpie-line,#35353d);border-radius:12px;background:color-mix(in srgb,var(--magpie-bg,#19191d),var(--magpie-fg,#ededf0) 2%)}.custom-rules .primary{border-color:var(--magpie-accent,#a292ff);background:color-mix(in srgb,var(--magpie-accent,#a292ff) 12%,var(--magpie-bg,#19191d));font-weight:600}.custom-heading button{height:34px;padding:6px 12px}.custom-rules .table-wrap{background:var(--magpie-bg,#19191d)}.rule-editor{border:1px solid color-mix(in srgb,var(--magpie-accent,#a292ff) 40%,var(--magpie-line,#35353d));border-radius:10px;margin:0 0 18px;padding:20px;background:var(--magpie-bg,#19191d)}.editor-heading{padding-bottom:14px;border-bottom:1px solid var(--magpie-line,#35353d);align-items:flex-start}.rules-page .editor-heading h2{font-size:16px}.editor-heading p{font-size:12px;color:var(--magpie-muted,#aaaab5);margin:4px 0 0}.editor-heading #draft-state{padding:3px 8px;border-radius:5px;background:color-mix(in srgb,var(--magpie-fg,#ededf0) 5%,var(--magpie-bg,#19191d));white-space:nowrap}.name-editor{max-width:680px}.field-title{font-weight:600}.field-title small{font-size:11px;font-weight:400;color:var(--magpie-muted,#aaaab5);margin-left:6px}#rule-name{height:38px}.alias-input-row{padding:8px 10px;border-radius:6px;background:color-mix(in srgb,var(--magpie-fg,#ededf0) 3%,var(--magpie-bg,#19191d))}.alias-toolbar button{border-style:dashed;background:transparent}.rule-editor .rule-actions{margin-top:16px;padding:14px 0 0;border-top:1px solid var(--magpie-line,#35353d)}.rule-editor .rule-actions button{min-width:80px;height:34px}
.custom-heading,.builtin-heading{display:flex;align-items:center;justify-content:flex-start;gap:14px}.custom-heading>div,.builtin-heading>div{flex:1;min-width:0}.custom-icon,.builtin-icon{width:32px;height:32px;flex:none;color:var(--magpie-accent,#a292ff)}.rules-page .custom-heading h2,.rules-page .builtin-heading h2{font-size:18px}.custom-heading p,.builtin-heading p{margin:3px 0 0;color:var(--magpie-muted,#aaaab5);font-size:12px}.custom-rules>.audit-history{margin-top:20px;border-radius:8px;background:var(--magpie-bg,#19191d)}.custom-rules>.audit-history>summary{padding:14px 16px}.custom-rules .history-title{font-size:13px}
.rule-subnav{display:inline-flex;gap:4px;padding:4px;margin:0 0 18px;border:1px solid var(--magpie-line,#35353d);border-radius:8px;background:color-mix(in srgb,var(--magpie-bg,#19191d),var(--magpie-fg,#ededf0) 3%)}.rule-subnav button{height:32px;padding:5px 16px;border:1px solid transparent;background:transparent;color:var(--magpie-muted,#aaaab5);border-radius:5px}.rule-subnav button[aria-selected="true"]{color:var(--magpie-fg,#ededf0);font-weight:650;border-color:var(--magpie-line,#35353d);background:var(--magpie-card,#242429);box-shadow:0 1px 3px #0000000d}
+39
View File
@@ -0,0 +1,39 @@
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>脱敏规则</title><script src="bridge.js"></script><link rel="stylesheet" href="style.css"><link rel="stylesheet" href="rules.css"><script src="rules.js" defer></script></head>
<body class="rules-page"><main>
<header class="page-topbar"><h1 class="sr-only">脱敏规则</h1><nav class="tabs" aria-label="公司名称保护"><a href="session-authorization.html">会话授权</a><a href="rules.html" aria-current="page">脱敏规则</a><a href="./">脱敏回执</a></nav><p class="page-description">管理本机使用的公司名称、简称和别名。</p></header>
<div class="rule-subnav" role="tablist" aria-label="规则类型"><button id="builtin-tab" type="button" role="tab" aria-selected="false" aria-controls="builtin-view" tabindex="-1">内置识别</button><button id="custom-tab" type="button" role="tab" aria-selected="true" aria-controls="custom-view">自定义规则</button></div>
<section id="remove-panel" class="rule-confirm" aria-labelledby="remove-title" hidden><h2 id="remove-title">移除这条自定义规则?</h2><p id="remove-name"></p><p class="rule-help">移除后,这条规则的名称和别名不再作为自定义词匹配;内置识别仍继续生效。</p><div class="rule-actions"><button id="cancel-remove" type="button">取消</button><button id="confirm-remove" type="button">确认移除</button></div></section>
<section id="leave-panel" class="rule-confirm" aria-label="未保存的修改" hidden><p>当前修改尚未保存。离开会丢弃这些修改。</p><div class="rule-actions"><button id="stay-edit" type="button">继续编辑</button><button id="discard-edit" type="button">放弃修改</button></div></section>
<section id="custom-view" role="tabpanel" aria-labelledby="custom-tab" class="custom-rules">
<div class="custom-heading"><svg class="custom-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 4h16v16H4zM8 8h8M8 12h5M8 16h3"/></svg><div><h2 id="custom-title">自定义规则</h2><p>补充自动识别之外的名称,并集中管理它的简称与别名。</p></div><button id="add-rule" class="primary" type="button" disabled><span aria-hidden="true">+</span> 新增规则</button></div>
<div class="rules-summary"><p id="rule-count">正在读取规则…</p><p id="rule-notice" role="status" aria-live="polite"></p></div>
<div class="rules-toolbar"><label class="rule-search" for="rule-search"><span class="sr-only">搜索名称或别名</span><input id="rule-search" type="search" placeholder="搜索名称或别名" autocomplete="off"></label><button id="refresh-rules" type="button">刷新</button></div>
<section class="rule-editor" id="rule-editor" aria-labelledby="editor-title" hidden>
<div class="editor-heading"><div><h2 id="editor-title">编辑规则</h2><p>一条规则管理一个主体,简称与别名可以添加多个。</p></div><span id="draft-state">尚未保存</span></div>
<form id="rule-form">
<div class="name-editor"><label for="rule-name"><span class="field-title">公司名称或脱敏词 <small>必填</small></span><input id="rule-name" type="text" maxlength="120" autocomplete="off" spellcheck="false" required aria-describedby="name-help"></label>
<p id="name-help" class="rule-help">填写需要完整匹配的名称。收入、成本等业务字段及金额不在这里设置。</p></div>
<fieldset class="alias-editor"><legend>同一主体的简称、别名<span>选填,可添加多个</span></legend><div id="rule-aliases"></div><div class="alias-toolbar"><button id="add-alias" type="button"><span aria-hidden="true">+</span> 添加简称或别名</button><span id="alias-count" aria-live="polite"></span></div></fieldset>
<p id="alias-help" class="rule-help">每个输入框填写一个;也可粘贴每行一个的多行名单。空白行不会保存。各别名独立匹配并按原写法还原,不要把不同主体合并到一条规则。所有规则的名称和别名合计最多512个。</p>
<div class="rule-actions"><p id="editor-message" role="status" aria-live="polite"></p><button id="cancel-edit" type="button">取消</button><button id="save-rule" class="primary" type="button">保存规则</button></div>
</form>
</section>
<div class="table-wrap" tabindex="0" aria-label="自定义脱敏规则表"><table class="rules-table"><thead><tr><th scope="col">公司名称 / 脱敏词</th><th scope="col">简称与别名</th><th scope="col" class="rule-operations">操作</th></tr></thead><tbody id="rule-rows"></tbody></table><p id="rule-empty" hidden></p></div>
<p class="rules-footnote">保存后对后续经过 Magpie 的请求生效。已批准的会话原名授权仍适用,已发送的内容不会撤回。</p>
<details class="audit-history"><summary><svg class="history-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="8.5"/><path d="M12 7v5l3 2"/></svg><span class="history-heading"><span class="history-title">规则版本记录</span><span class="history-description">追溯自定义规则的版本与名称数量</span></span><span class="history-action"><span class="history-open">查看记录</span><span class="history-close">收起记录</span><span aria-hidden="true">↗</span></span></summary><p>这里展示最近最多100条规则版本摘要,不含原名、密钥或会话正文。脱敏回执另按最近25个请求保留。旧摘要缺失不代表从未变更。</p><div id="rule-history" role="status">展开后读取</div></details>
</section>
<section id="builtin-view" role="tabpanel" class="builtin-rules" aria-labelledby="builtin-tab" hidden>
<div class="builtin-heading"><svg class="builtin-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m12 3 8 3v6c0 5-8 9-8 9s-8-4-8-9V6l8-3Z"/><path d="m8 12 3 3 5-6"/></svg><div><h2 id="builtin-title">内置识别规则</h2><p>三种识别方式共同保护经过 Magpie 的文字</p></div><span class="builtin-status">自动生效</span></div>
<p class="builtin-intro">检查经过 Magpie 的文字输入、历史消息、工具返回文字、工具参数和工具说明。以下识别方式共同生效,自定义规则用于补充名称和别名。</p>
<dl class="recognition-rules">
<div><dt><span class="recognition-icon"><svg class="" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 21V7l8-4v18M12 10h8v11M2 21h20M7 9h2M7 13h2M7 17h2M15 14h2M15 18h2"/></svg></span><span>公司全称<small>按名称结构识别</small></span></dt><dd><p><strong>中文:</strong>识别以“股份有限公司、有限责任公司、有限公司、股份公司、集团公司”结尾的名称;仅以“公司”或“集团”结尾,不会单凭后缀自动认定。</p><p><strong>英文:</strong>首词以大写英文字母开头,并带 Inc.、Ltd.、LLC 等常见后缀。支持的后缀还包括 Corporation、Corp.、Incorporated、Limited、L.L.C.、PLC、GmbH;常见的 Co. 与 Ltd. 组合形式也可识别。普通文字中的小写 limited 不按公司后缀识别。</p></dd></div>
<div><dt><span class="recognition-icon"><svg class="" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 10h18M9 10v10M13 14h4M13 17h3"/></svg></span><span>明确名称字段<small>按字段含义识别</small></span></dt><dd><p>“公司名称、客户名称、供应商名称、交易对手名称”等字段中的值,可识别不带上述后缀的名称。会跳过明显泛称、说明句和空值占位文字。</p><p>通用 company、customer、supplier、counterparty 字段里的小写下划线标识,不会单凭该字段认定为公司名;明确名称字段和自定义规则仍可声明这类写法。</p></dd></div>
<div><dt><span class="recognition-icon"><svg class="" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m10 13 4-2M9 16H7a4 4 0 0 1 0-8h3M14 8h3a4 4 0 0 1 0 8h-3"/></svg></span><span>材料中的简称关系<small>按明确关系识别</small></span></dt><dd><p>从用户文字和工具返回文字中识别紧接公司全称、带引号的“以下简称”“简称为”等定义;代码块、示例或虚构定义不采用。同一简称对应多个全称时,跳过该自动简称。</p><p>一处定义最多读取4个简称;本次请求的自动简称关系超过128个时,不采用这批自动简称。自定义规则不受这两项自动识别限制,但受全局512名称上限约束。</p></dd></div>
</dl>
<div class="recognition-boundaries"><h3>补充方式与识别边界</h3><ul><li>未被自动识别的名称或简称,可以切换到“自定义规则”补充。自定义词按文字匹配,不按正则表达式执行;重叠时优先较长名称,英文字母匹配不区分大小写。</li><li>识别依赖文字形式和明确关系,不会自动查询工商资料、推断品牌归属或保证所有名称都能识别。没有明确简称关系时,应自行补充。</li><li>图片、音频及文件中的二进制内容不做文字识别;工具自行联网、上传文件或绕过 Magpie 的请求不在本插件范围内。</li><li>本页不提供金额脱敏。收入、成本、期间、币种、单位和含税口径应保留;移除自定义规则不等于关闭内置识别。</li></ul></div>
</section>
</main></body></html>
+141
View File
@@ -0,0 +1,141 @@
const $=id=>document.getElementById(id);
const errors={invalid_rules:'规则格式不正确,请检查名称和别名。',invalid_names:'名称须为2至120个字符,包含中文或字母,不能使用纯数字或脱敏代号。',too_many_names:'名称和别名合计最多512个,请缩小范围。',duplicate_names:'名称或别名重复,请保留一处。',rules_changed:'规则刚被其他窗口修改。请先刷新,再重新编辑。',rules_unavailable:'本机规则服务暂不可用,请稍后刷新。'};
let base,readKey,writeKey,nonce,revision,rules=[],baseline='',editing=null,formBaseline='',removing=null,busy=false,loaded=false,leaveAction=null;
const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(key=>[key,canonical(value[key])])):value;
const json=value=>JSON.stringify(canonical(value));
const terms=row=>typeof row==='string'?{name:row,aliases:[]}:{name:row.name,aliases:row.aliases||[]};
function el(tag,text,cls){const node=document.createElement(tag);if(text!==undefined)node.textContent=text;if(cls)node.className=cls;return node;}
function notice(text,error=false){$('rule-notice').textContent=text;$('rule-notice').className=error?'error':'';}
function editorNotice(text,error=false){$('editor-message').textContent=text;$('editor-message').className=error?'error':'';}
const aliasInputs=()=>[...$('rule-aliases').querySelectorAll('input')];
function draft(){return {name:$('rule-name').value,aliases:aliasInputs().map(input=>input.value)};}
function markDraft(){$('draft-state').textContent=dirty()?'有未保存的修改':'当前生效内容';editorNotice('');}
function numberAliases(){
[...$('rule-aliases').children].forEach((row,index)=>{
row.querySelector('label').textContent=`简称或别名 ${index+1}`;
row.querySelector('button').setAttribute('aria-label',`移除简称或别名 ${index+1}`);
});
$('alias-count').textContent=`${aliasInputs().filter(input=>input.value.trim()).length} 个已填写`;
}
let aliasSerial=0;
function addAlias(value='',focus=true,after=null){
if(aliasInputs().length>=511){editorNotice('名称和别名合计最多512个,请减少条目。',true);return null;}
const row=el('div',undefined,'alias-input-row'),label=el('label'),input=el('input'),remove=el('button','移除');
input.type='text';input.id='alias-'+(++aliasSerial);input.maxLength=120;input.autocomplete='off';input.spellcheck=false;input.value=value;input.setAttribute('aria-describedby','alias-help');label.htmlFor=input.id;remove.type='button';
remove.addEventListener('click',()=>{if(busy)return;row.remove();if(!$('rule-aliases').children.length)addAlias('',false);numberAliases();markDraft();});
input.addEventListener('input',numberAliases);
input.addEventListener('keydown',event=>{if(event.key==='Enter'&&!event.isComposing){event.preventDefault();if(input.value.trim()&&addAlias('',true,row))markDraft();}});
input.addEventListener('paste',event=>{
const values=event.clipboardData?.getData('text/plain').split(/\r\n|\r|\n/).map(text=>text.trim()).filter(Boolean)||[];
if(values.length<2)return;event.preventDefault();if(aliasInputs().length+values.length-1>511){editorNotice('名称和别名合计最多512个,请减少条目。',true);return;}input.value=values[0];let previous=row;
for(const text of values.slice(1))previous=addAlias(text,false,previous);
numberAliases();markDraft();
});
row.append(label,input,remove);if(after)after.after(row);else $('rule-aliases').append(row);numberAliases();if(focus)input.focus();return row;
}
function dirty(){return editing!==null&&json(draft())!==formBaseline;}
function setBusy(value){busy=value;document.querySelectorAll('main button,main input,main textarea').forEach(node=>node.disabled=value||(!loaded&&node.getAttribute('role')!=='tab'));}
async function api(route,body,timeout=8000){
const response=await fetch(new URL(route,base),{method:body===undefined?'GET':'POST',headers:body===undefined?{'X-Receipt-Key':readKey}:{'X-Receipt-Key':readKey,'X-Authorization-Key':writeKey,'X-Authorization-Nonce':nonce,'Content-Type':'application/json'},body:body===undefined?undefined:json(body),cache:'no-store',signal:AbortSignal.timeout(timeout)});
const result=await response.json();if(!response.ok){let message=errors[result.error]||'读取或保存未完成,请刷新核对。';if(result.error==='duplicate_names'&&Array.isArray(result.conflicts))message+=' 冲突位置:'+result.conflicts.map(v=>'第'+v.rule+'条规则的'+(v.field?'别名'+v.field:'名称')).join('、');throw new Error(message);}return result;
}
function render(){
const query=$('rule-search').value.trim().toLowerCase();
const rows=rules.map((rule,index)=>({rule,index})).filter(({rule})=>{const row=terms(rule);return [row.name,...row.aliases].some(value=>value.toLowerCase().includes(query));});
$('rule-count').textContent=`${rules.length} 条自定义规则 · ${rules.reduce((sum,row)=>sum+terms(row).aliases.length+1,0)} 个名称及别名`;
$('rule-rows').replaceChildren(...rows.map(({rule,index})=>{
const row=terms(rule),tr=el('tr'),name=el('td',row.name),aliases=el('td'),actions=el('td',undefined,'rule-operations');
if(row.aliases.length)row.aliases.forEach(value=>aliases.append(el('span',value,'rule-alias')));else aliases.append(el('span','未设置别名','no-alias'));
for(const [label,action]of [['编辑',()=>openEditor(index)],['移除',()=>openRemove(index)]]){
const button=el('button',label);button.type='button';button.setAttribute('aria-label',label+'规则 '+row.name);button.addEventListener('click',event=>{if(event.isTrusted&&!busy)guard(action);});actions.append(button);
}
tr.append(name,aliases,actions);return tr;
}));
$('rule-empty').hidden=rows.length>0;$('rule-empty').textContent=rules.length?'没有匹配的名称或别名。':'尚未设置自定义规则,内置识别仍在生效。';
}
async function load(){
if(busy)return;setBusy(true);
try{
const options=await magpie.options.get(),current=options.companies||[];
readKey=options.receiptReadKey;writeKey=options.authorizationKey;
if(!/^[a-f0-9]{64}$/.test(readKey||'')||!/^[a-f0-9]{64}$/.test(writeKey||''))throw new Error('本机规则服务尚未就绪,请重新打开插件。');
const state=await api('rules');nonce=state.nonce;
const checked=await api('rules/validate',{revision:state.revision,companies:current});
if(checked.revision!==state.revision)throw new Error('配置已保存,本机服务尚未同步。请稍后刷新。');
rules=structuredClone(current);baseline=json(current);revision=state.revision;loaded=true;closeEditor();render();notice('已读取当前生效规则。');
}catch(error){notice(error.message||'无法读取规则,请重新打开插件。',true);}
finally{setBusy(false);$('refresh-rules').disabled=false;}
}
function closeEditor(){editing=null;removing=null;leaveAction=null;$('rule-editor').hidden=true;$('remove-panel').hidden=true;$('leave-panel').hidden=true;editorNotice('');}
function openEditor(index){
closeEditor();editing=index;const row=index===-1?{name:'',aliases:[]}:terms(rules[index]);
$('editor-title').textContent=index===-1?'新增规则':'编辑规则';$('rule-name').value=row.name;$('rule-aliases').replaceChildren();for(const alias of row.aliases.length?row.aliases:[''])addAlias(alias,false);formBaseline=json(draft());
$('draft-state').textContent=index===-1?'填写后保存生效':'当前生效内容';$('rule-editor').hidden=false;$('rule-name').focus();
}
function openRemove(index){closeEditor();removing=index;$('remove-name').textContent=terms(rules[index]).name;$('remove-panel').hidden=false;$('cancel-remove').focus();}
function guard(action){if(busy){notice('正在保存,请稍候。');return;}if(!dirty()){action();return;}leaveAction=action;$('leave-panel').hidden=false;$('stay-edit').focus();}
async function waitForReload(expected){
const deadline=Date.now()+15000;
while(Date.now()<deadline){try{const state=await api('rules',undefined,1000);if(state.revision===expected){nonce=state.nonce;return;}}catch{}await new Promise(resolve=>setTimeout(resolve,250));}
throw new Error('规则已提交,尚未确认服务生效。请刷新核对,不要重复保存。');
}
async function save(next){
if(busy)return;setBusy(true);editorNotice('正在校验并保存…');notice('正在保存…');let submitted=false;
try{
const before=await magpie.options.get();if(json(before.companies||[])!==baseline)throw new Error(errors.rules_changed);
const state=await api('rules');nonce=state.nonce;if(state.revision!==revision)throw new Error(errors.rules_changed);
const checked=await api('rules/validate',{revision,companies:next});
const latest=await magpie.options.get();if(json(latest.companies||[])!==baseline)throw new Error(errors.rules_changed);
if(json(next)===baseline){closeEditor();notice('内容与当前规则一致,无需保存。');return;}
try{await magpie.options.set({...latest,companies:next});submitted=true;}
catch(error){const saved=await magpie.options.get();if(json(saved.companies||[])!==json(next))throw error;submitted=true;}
await waitForReload(checked.revision);
const saved=await magpie.options.get();if(json(saved.companies||[])!==json(next))throw new Error('保存后规则再次发生变化,请刷新核对。');
rules=structuredClone(next);baseline=json(next);revision=checked.revision;closeEditor();render();notice('已保存并生效,后续请求使用新规则。');
}catch(error){const message=error.message||'保存未完成,请刷新核对。';notice(message,true);editorNotice(message,true);if(submitted)$('draft-state').textContent='已提交,待核对';}
finally{setBusy(false);}
}
function saveEditor(){
if(editing===null||!$('rule-form').reportValidity())return;
const name=$('rule-name').value.trim(),aliases=aliasInputs().map(input=>input.value.trim()).filter(Boolean);
const next=structuredClone(rules),prior=editing===-1?null:next[editing];
const value=prior&&typeof prior==='object'?{...prior,name,aliases}:{name,aliases};
if(editing===-1)next.push(value);else next[editing]=value;save(next);
}
function showRuleView(view){
closeEditor();
for(const kind of ['builtin','custom']){const selected=kind===view;$(kind+'-view').hidden=!selected;$(kind+'-tab').setAttribute('aria-selected',String(selected));$(kind+'-tab').tabIndex=selected?0:-1;}
$(view+'-tab').focus();
}
for(const kind of ['builtin','custom']){
$(kind+'-tab').addEventListener('click',()=>{if($(kind+'-tab').getAttribute('aria-selected')!=='true')guard(()=>showRuleView(kind));});
$(kind+'-tab').addEventListener('keydown',event=>{
const next=event.key==='Home'?'builtin':event.key==='End'?'custom':['ArrowLeft','ArrowRight'].includes(event.key)?(kind==='builtin'?'custom':'builtin'):null;
if(next){event.preventDefault();if(next!==kind)guard(()=>showRuleView(next));}
});
}
$('add-rule').addEventListener('click',event=>{if(event.isTrusted)guard(()=>openEditor(-1));});
$('refresh-rules').addEventListener('click',()=>guard(load));
$('rule-search').addEventListener('input',render);
$('rule-form').addEventListener('submit',event=>event.preventDefault());
$('rule-form').addEventListener('input',markDraft);
$('add-alias').addEventListener('click',event=>{if(event.isTrusted&&!busy&&addAlias())markDraft();});
$('save-rule').addEventListener('click',event=>{if(event.isTrusted)saveEditor();});
$('cancel-edit').addEventListener('click',()=>guard(closeEditor));
$('cancel-remove').addEventListener('click',closeEditor);
$('confirm-remove').addEventListener('click',event=>{if(event.isTrusted&&removing!==null)save(rules.filter((_,index)=>index!==removing));});
$('stay-edit').addEventListener('click',()=>{$('leave-panel').hidden=true;leaveAction=null;$('rule-name').focus();});
$('discard-edit').addEventListener('click',()=>{const action=leaveAction;closeEditor();action?.();});
document.querySelectorAll('.tabs a').forEach(link=>link.addEventListener('click',event=>{event.preventDefault();guard(()=>{location.href=link.href;});}));
window.addEventListener('beforeunload',event=>{if(dirty()||busy){event.preventDefault();event.returnValue='';}});
async function start(){try{await magpie.ready;base=new URL('.',location.href).href;await load();magpie.onVisibility?.(visible=>{if(visible&&!dirty()&&editing===null&&removing===null&&!busy)load();});}catch{notice('无法连接插件配置,请重新打开此页。',true);$('refresh-rules').disabled=false;}}
start();
$('rule-history').parentElement.addEventListener('toggle',async()=>{
if(!$('rule-history').parentElement.open)return;
try{const data=await api('audit');$('rule-history').replaceChildren();
for(const row of data.rules){const line=el('p',undefined,'history-row'),time=el('time',new Date(row.at).toLocaleString('zh-CN'));time.dateTime=row.at;
line.append(time,el('span',row.ruleCount+' 条规则 · '+row.nameCount+' 个名称 · 版本 '+row.revision.slice(0,12)));$('rule-history').append(line);}
if(!data.rules.length)$('rule-history').textContent='暂无可用记录。';
}catch{$('rule-history').textContent='记录暂时无法读取,请重新展开重试。';}
});
+8 -4
View File
@@ -1,4 +1,6 @@
:root {color-scheme:light dark}
.audit-history{margin-top:24px;border:1px solid var(--magpie-line,#35353d);border-radius:10px;background:color-mix(in srgb,var(--magpie-bg,#19191d),var(--magpie-fg,#ededf0) 3%);overflow:hidden}.audit-history>summary{display:flex;align-items:center;gap:14px;list-style:none;cursor:pointer;padding:17px 20px}.audit-history>summary::-webkit-details-marker{display:none}.audit-history>summary:hover .history-action{border-color:var(--magpie-accent,#a292ff)}.history-icon{width:26px;height:26px;flex:none;color:var(--magpie-muted,#aaaab5)}.history-heading{display:grid;gap:3px;flex:1;min-width:0}.history-title{font-size:14px;font-weight:650}.history-description{font-size:12px;color:var(--magpie-muted,#aaaab5)}.history-action{display:inline-flex;align-items:center;gap:10px;flex:none;border:1px solid var(--magpie-line,#414147);border-radius:6px;padding:7px 12px;font-size:12px;background:var(--magpie-bg,#19191d)}.history-close,.audit-history[open] .history-open{display:none}.audit-history[open] .history-close{display:inline}.audit-history[open] .history-action>span:last-child{transform:rotate(180deg)}.audit-history>p{margin:0;padding:14px 20px 8px;border-top:1px solid var(--magpie-line,#35353d);font-size:12px;line-height:1.7;color:var(--magpie-muted,#aaaab5)}.audit-history>div{padding:0 20px 16px;max-height:320px;overflow:auto}.history-row{display:grid;grid-template-columns:170px minmax(0,1fr);gap:8px 20px;padding:10px 0;margin:0;border-bottom:1px solid var(--magpie-line,#35353d);font-size:12px;line-height:1.6}.history-row:last-child{border:0}.history-row time{color:var(--magpie-muted,#aaaab5);font-variant-numeric:tabular-nums}.history-row>span{overflow-wrap:anywhere}
.authorization-boundary,.authorization-range{font-size:13px;line-height:1.65}.authorization-range{margin-top:8px}.authorization-range summary{cursor:pointer}.authorization-range ul{padding-left:20px}.authorization-range p{font-size:12px}.authorization-guide p,.authorization-footnote{color:var(--magpie-fg,#ededf0)!important;font-size:12px!important}.summary-filter{height:auto;min-height:31px;font-size:12px;background:transparent}.summary-filter[aria-pressed="true"]{border-color:var(--magpie-accent,#a292ff);background:color-mix(in srgb,var(--magpie-accent,#a292ff) 10%,var(--magpie-bg,#19191d))}#totals{display:flex;flex-wrap:wrap;gap:6px!important}.requests thead th{position:sticky;top:0;z-index:1;background:var(--magpie-card,#242429)}.table-wrap:has(.requests){max-height:65vh;overflow:auto}#receipt-health{border-left:3px solid var(--magpie-accent,#a292ff);padding:8px 12px;color:var(--magpie-fg,#ededf0)}
body {margin:0;background:var(--magpie-bg,#19191d);color:var(--magpie-fg,#ededf0);font:13px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
main {padding:14px 20px 24px}p {margin:5px 0}
button,input,select {font:inherit;box-sizing:border-box;border-radius:5px;border:1px solid var(--magpie-line,#414147);padding:5px 8px;background:var(--magpie-card,#242429);color:inherit;height:31px}
@@ -9,16 +11,15 @@ button {cursor:pointer;white-space:nowrap}button:hover:not(:disabled) {border-co
#agent {min-width:130px;max-width:220px}.agent-source {white-space:nowrap}.view {border:0;background:transparent;color:var(--magpie-accent,#a292ff);padding:2px 0;height:24px}
.detail-row>td {padding:12px 14px;background:var(--magpie-card,#222227)}.detail-title {font-size:13px;font-weight:600;margin-bottom:6px}.detail-meta {display:flex;flex-wrap:wrap;gap:4px 16px;color:var(--magpie-muted,#aaaab5);font-size:12px;margin-top:8px}.identity {font-size:11px;margin-top:6px;color:var(--magpie-muted,#aaaab5);overflow-wrap:anywhere}.pairs {max-width:1100px;min-width:580px}.pairs th,.pairs td {padding:5px 8px}.pairs th:first-child {width:45%}.pairs td {vertical-align:top}.pairs th {font-size:11px}.detail-message {color:var(--magpie-muted,#aaaab5);font-size:12px}.detail-pairs {overflow:auto}
.explanation {border-top:1px solid var(--magpie-line,#35353d);padding-top:10px;color:var(--magpie-muted,#aaaab5);font-size:12px}summary {cursor:pointer}#empty {padding:20px 0;text-align:center;color:var(--magpie-muted,#aaaab5)}
.tabs{display:flex;gap:6px;border-bottom:1px solid var(--magpie-line,#35353d);padding-bottom:10px;margin-bottom:16px}
.page-topbar{display:flex;align-items:center;gap:22px;border-bottom:1px solid var(--magpie-line,#35353d);padding-bottom:12px;margin-bottom:20px}.tabs{display:flex;flex:none;gap:6px}.page-description{margin:0;padding-left:22px;border-left:1px solid var(--magpie-line,#35353d);font-size:12px;line-height:1.65;color:var(--magpie-muted,#aaaab5)}
[hidden]{display:none!important}
.tabs a{display:inline-block;text-decoration:none;color:inherit;border:1px solid var(--magpie-line,#414147);border-radius:5px;padding:5px 10px}
.tabs a[aria-current="page"]{font-weight:650;background:color-mix(in srgb,var(--magpie-bg,#19191d),var(--magpie-fg,#ededf0) 8%);border-color:var(--magpie-accent,#a292ff)}
.tabs a:focus-visible{outline:2px solid var(--magpie-accent,#a292ff);outline-offset:2px}.page-title{font-size:21px;margin:0 0 18px}
.tabs a:focus-visible{outline:2px solid var(--magpie-accent,#a292ff);outline-offset:2px}
.task-name{display:block;max-width:290px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;font-weight:550;margin-bottom:2px}
.authorization-page main{max-width:1160px;padding-bottom:20px}
.authorization-page .tabs{margin-bottom:14px}
.authorization-heading{display:flex;align-items:center;justify-content:space-between;gap:16px}
.authorization-heading h1{font-size:19px;line-height:1.3;margin:0 0 4px}.authorization-heading p{font-size:12px;line-height:1.5;color:var(--magpie-muted,#aaaab5);margin:0}
.authorization-heading p{font-size:12px;line-height:1.5;color:var(--magpie-muted,#aaaab5);margin:0}
#authorization-notice{font-size:12px;color:var(--magpie-muted,#aaaab5);margin:8px 0 12px;min-height:18px}
.authorization-guide{display:flex;align-items:baseline;flex-wrap:wrap;gap:6px 12px;padding:10px 12px;border:1px solid var(--magpie-line,#35353d);border-radius:6px;font-size:12px}
.authorization-guide>span{font-weight:600;white-space:nowrap}.authorization-guide>p{flex:1;margin:0;color:var(--magpie-muted,#aaaab5)}
@@ -27,6 +28,7 @@ button {cursor:pointer;white-space:nowrap}button:hover:not(:disabled) {border-co
#authorization-panel h2{font-size:13px;font-weight:600;margin:16px 0 8px}.authorization-list{display:grid;gap:8px}
.authorization-card{display:grid;grid-template-columns:minmax(0,1fr) minmax(155px,auto) auto;align-items:center;gap:20px;border:1px solid var(--magpie-line,#35353d);border-radius:7px;padding:12px 14px}
.authorization-task{min-width:0}.authorization-card h3{font-size:14px;font-weight:600;line-height:1.45;overflow-wrap:anywhere;margin:0 0 5px}.authorization-card p{margin:0}
.authorization-title{display:flex;align-items:center;flex-wrap:wrap;gap:8px 10px;margin-bottom:6px}.authorization-title h3{margin:0}.authorization-agent{display:inline-flex;align-items:baseline;gap:6px;max-width:100%;overflow-wrap:anywhere;padding:3px 8px;border:1px solid color-mix(in srgb,var(--magpie-accent,#a292ff) 45%,var(--magpie-line,#35353d));border-radius:4px;background:color-mix(in srgb,var(--magpie-accent,#a292ff) 10%,var(--magpie-bg,#19191d));color:var(--magpie-fg,#ededf0);font-size:12px;line-height:1.5}.authorization-agent-label{font-size:11px}.authorization-agent strong{font-weight:650}
.authorization-identity{display:flex;flex-wrap:wrap;gap:2px 12px;color:var(--magpie-muted,#aaaab5);font-size:11px;line-height:1.6}.authorization-workspace{overflow-wrap:anywhere}
.authorization-scope{display:grid;grid-template-columns:auto auto;align-items:baseline;gap:1px 8px;font-size:12px}.authorization-scope-label{font-weight:550;white-space:nowrap}.authorization-scope .detail-message{font-size:11px}.authorization-time{grid-column:1/-1;font-size:11px;color:var(--magpie-muted,#aaaab5);white-space:nowrap}
.authorization-card>button{height:29px;padding:4px 10px}.authorization-footnote{margin:9px 0 0;color:var(--magpie-muted,#aaaab5);font-size:11px;line-height:1.6}
@@ -41,3 +43,5 @@ button {cursor:pointer;white-space:nowrap}button:hover:not(:disabled) {border-co
.revocation-confirm{grid-column:1/-1;padding-top:10px;border-top:1px solid var(--magpie-line,#35353d)}.revocation-confirm button{margin:8px 8px 0 0}
#authorization-scope-note{margin:4px 0 0;font-size:12px;line-height:1.6}#authorization-panel button,#authorization-panel textarea{background:color-mix(in srgb,var(--magpie-bg,#19191d),var(--magpie-fg,#ededf0) 5%);color:var(--magpie-fg,#ededf0)}
#authorization-notice.error{color:var(--magpie-error,light-dark(#b42318,#ffb4ab))}
.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
+30 -11
View File
@@ -1,4 +1,5 @@
import fs from "node:fs/promises";
import {recordRuleRevision,readAuditHistory} from "./src/rule-history.mjs";
import {constants} from "node:fs";
import {createServer} from "node:http";
import {timingSafeEqual, randomBytes, randomUUID} from "node:crypto";
@@ -10,8 +11,8 @@ import {readDetails} from "./src/receipt-details.mjs";
import {stateRoot, secureDir, listAuthorizationRequests, closeAuthorizationRequest, legacyTaskGrants, revokeGrant} from "./src/grant-store.mjs";
import {retainReceipts, readTail, receiptAgent} from "./src/receipts.mjs";
import {validName,namePattern} from "./src/policy.js";
import {readAuthorization, signAuthorization} from "./src/session-authorization.js";
import {initializeOptions} from "./src/local-options.mjs";
import {readAuthorization, planAuthorizationEntries, AUTHORIZATION_ENTRY_LIMIT} from "./src/session-authorization.js";
import {initializeOptions,validateCompanyRules,companyRulesRevision} from "./src/local-options.mjs";
const services = new Map();
const agentNames={codex:"Codex",claude:"Claude Code","claude-code":"Claude Code",pi:"Pi",opencode:"OpenCode","deepseek-harness":"DeepSeek Harness",deepseek:"DeepSeek",hermes:"Hermes","nero-banker":"NERO Banker"};
@@ -92,13 +93,27 @@ export const ReceiptPage = async (_input, options = {}) => {
console.warn("company_guard_receipt_page_not_configured"); return {};
}
const root = stateRoot(options.stateDir);
try{await recordRuleRevision(root,options.companies);}catch{console.warn("company_guard_rule_history_failed");}
try { await retainReceipts(root, undefined, options.appLog); } catch { console.warn("company_guard_receipt_retention_failed"); }
const assets = new Map();
for (const [route,file,type] of [["/","page/dashboard.html","text/html"],["/session-authorization.html","page/authorization.html","text/html"],["/authorization.js","page/authorization.js","text/javascript"],["/app.js","page/app.js","text/javascript"],["/style.css","page/style.css","text/css"],["/bridge.js","vendor/magpie-pagebridge.js","text/javascript"]]) {
for (const [route,file,type] of [["/","page/dashboard.html","text/html"],["/session-authorization.html","page/authorization.html","text/html"],["/rules.html","page/rules.html","text/html"],["/rules.js","page/rules.js","text/javascript"],["/rules.css","page/rules.css","text/css"],["/authorization.js","page/authorization.js","text/javascript"],["/app.js","page/app.js","text/javascript"],["/style.css","page/style.css","text/css"],["/bridge.js","vendor/magpie-pagebridge.js","text/javascript"]]) {
assets.set(route, {body:await fs.readFile(new URL(file,import.meta.url)),type});
}
if (services.has(port)) return {};
const nonce=randomBytes(32).toString("hex");
const canWrite=req=>{
const writeKey=req.headers["x-authorization-key"];
return req.headers.origin==="null"&&req.headers["x-authorization-nonce"]===nonce&&req.headers["content-type"]==="application/json"&&/^[a-f0-9]{64}$/.test(options.authorizationKey||"")&&typeof writeKey==="string"&&/^[a-f0-9]{64}$/.test(writeKey)&&timingSafeEqual(Buffer.from(writeKey),Buffer.from(options.authorizationKey));
};
const rules=async(req,res,url,send)=>{
if(req.method==="GET"&&url.pathname==="/rules")return send(200,{nonce,revision:companyRulesRevision(options.companies),ruleCount:(options.companies||[]).length});
if(req.method!=="POST"||url.pathname!=="/rules/validate")return send(405,{error:"method_not_allowed"});
if(!canWrite(req))return send(403,{error:"forbidden"});
let raw="";for await(const chunk of req){raw+=chunk;if(Buffer.byteLength(raw)>384*1024)return send(413,{error:"too_many_names"});}
let body;try{body=JSON.parse(raw);}catch{return send(400,{error:"invalid_json"});}
if(!body||body.revision!==companyRulesRevision(options.companies))return send(409,{error:"rules_changed"});
try{return send(200,validateCompanyRules(body.companies));}catch(error){return send(400,{error:error.message,conflicts:error.conflicts});}
};
const operationFile=id=>path.join(root,"authorization-operations",id+".json");
const readOperation=async id=>{
if(!/^[a-f0-9-]{36}$/.test(id))throw new Error("invalid_operation");
@@ -108,13 +123,12 @@ export const ReceiptPage = async (_input, options = {}) => {
};
const authorization=async(req,res,url,send)=>{
if(req.method==="GET"){
const pending=await listAuthorizationRequests(root),legacy=(await legacyTaskGrants(root)).map(g=>({session:g.session,workspace:g.workspace,coverage:"names",nameCount:g.names.length,created:g.created,legacy:true}));
const pending=await listAuthorizationRequests(root),legacy=(await legacyTaskGrants(root)).map(g=>({session:g.session,workspace:g.workspace,coverage:"names",nameCount:g.names.length,names:g.names,created:g.created,legacy:true}));
const rows=await withTaskTitles([...pending,...legacy]);
return send(200,{nonce,revision:options.sessionAuthorizationRevision,pending:rows.slice(0,pending.length),legacy:rows.slice(pending.length)});
}
if(req.method!=="POST")return send(405,{error:"method_not_allowed"});
const writeKey=req.headers["x-authorization-key"];
if(req.headers.origin!=="null"||req.headers["x-authorization-nonce"]!==nonce||req.headers["content-type"]!=="application/json"||!/^[a-f0-9]{64}$/.test(options.authorizationKey||"")||typeof writeKey!=="string"||!/^[a-f0-9]{64}$/.test(writeKey)||!timingSafeEqual(Buffer.from(writeKey),Buffer.from(options.authorizationKey)))return send(403,{error:"forbidden"});
if(!canWrite(req))return send(403,{error:"forbidden"});
let raw="";for await(const chunk of req){raw+=chunk;if(Buffer.byteLength(raw)>4*1024*1024)return send(413,{error:"authorization_too_large"});}
let body;try{body=JSON.parse(raw);}catch{return send(400,{error:"invalid_json"});}
if(["/authorization/commit","/authorization/cancel"].includes(url.pathname)){
@@ -131,9 +145,9 @@ export const ReceiptPage = async (_input, options = {}) => {
await fs.rm(path.join(root,"authorization-operations","lock.json"),{force:true});
return send(200,{ok:true});
}
if(!Array.isArray(body.entries)||body.entries.length>64||body.entries.some(e=>!readAuthorization(e,options.authKey)))return send(400,{error:"invalid_registry"});
if(!Array.isArray(body.entries)||body.entries.length>AUTHORIZATION_ENTRY_LIMIT||body.entries.some(e=>!readAuthorization(e,options.authKey)))return send(400,{error:"invalid_registry"});
const ids=new Set(body.entries.map(e=>e.session));if(ids.size!==body.entries.length)return send(400,{error:"invalid_registry"});
if(url.pathname==="/authorization/state")return send(200,{active:await withTaskTitles(body.entries.map(e=>readAuthorization(e,options.authKey)).filter(r=>r.state==="active").map(r=>({session:r.session,workspace:r.workspace,coverage:r.coverage,nameCount:r.names.length,created:r.created,requestId:r.requestId})))});
if(url.pathname==="/authorization/state")return send(200,{active:await withTaskTitles(body.entries.map(e=>readAuthorization(e,options.authKey)).filter(r=>r.state==="active").map(r=>({session:r.session,workspace:r.workspace,coverage:r.coverage,nameCount:r.names.length,names:r.names,created:r.created,requestId:r.requestId})))});
if(url.pathname!=="/authorization/plan")return send(404,{error:"not_found"});
let request, prior;
const legacy=await legacyTaskGrants(root);
@@ -150,9 +164,10 @@ export const ReceiptPage = async (_input, options = {}) => {
if(coverage==="names"&&(!names.length||names.length>32||names.some(n=>!validName(n))))return send(400,{error:"invalid_names"});
const target=request||prior;
const record={v:1,session:target.session,workspace:target.workspace,requestId:request?.id,coverage,names,pattern:coverage==="names"?namePattern(names):"",state:body.action==="revoke"?"revoked":"active",created:Date.now()};
const legacySessions=new Set(legacy.map(r=>r.session));
const entry=signAuthorization(record,options.authKey),entries=body.entries.filter(e=>e.session!==record.session&&(readAuthorization(e,options.authKey).state==="active"||legacySessions.has(e.session))).concat(entry);
if(entries.length>64||JSON.stringify(entries).length>3*1024*1024)return send(413,{error:"authorization_too_large"});
let plan;
try{plan=planAuthorizationEntries(body.entries,record,options.authKey,new Set(legacy.map(r=>r.session)));}
catch(error){if(error.message==="authorization_too_large")return send(413,{error:"authorization_too_large"});throw error;}
const {entry,entries}=plan;
const op={id:randomUUID(),action:body.action,session:record.session,requestId:request?.id,entryMac:entry.mac,coverage:record.coverage,nameCount:names.length,created:Date.now()};
const dir=path.dirname(operationFile(op.id));await secureDir(root,true);await secureDir(dir,true);
const lock=path.join(dir,"lock.json");
@@ -184,10 +199,14 @@ export const ReceiptPage = async (_input, options = {}) => {
}
const supplied = req.headers["x-receipt-key"];
if (typeof supplied !== "string" || !/^[a-f0-9]{64}$/.test(supplied) || !timingSafeEqual(Buffer.from(supplied), Buffer.from(key))) return send(401, {error:"unauthorized"});
if(url.pathname==="/rules"||url.pathname.startsWith("/rules/")){
try{return await rules(req,res,url,send);}catch{console.warn("company_guard_rules_unavailable");return send(400,{error:"rules_unavailable"});}
}
if(url.pathname==="/authorization"||url.pathname.startsWith("/authorization/")){
try{return await authorization(req,res,url,send);}catch{console.warn("company_guard_authorization_unavailable");return send(400,{error:"authorization_unavailable"});}
}
if (req.method !== "GET") return send(405, {error:"read_only"});
if(url.pathname==="/audit"){try{return send(200,await readAuditHistory(root));}catch{return send(500,{error:"audit_unavailable"});}}
if (url.pathname === "/details") {
const id=url.searchParams.get("id") || "";
if (!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(id)) return send(400,{error:"invalid_id"});
+9
View File
@@ -0,0 +1,9 @@
import {build} from 'esbuild';
import fs from 'node:fs/promises';
import {fileURLToPath} from 'node:url';
const root=fileURLToPath(new URL('../',import.meta.url));
const result=await build({absWorkingDir:root,entryPoints:['src/company-guard.js'],bundle:true,format:'esm',platform:'neutral',target:'es2020',write:false,legalComments:'none'});
const file=new URL('../dist/company-guard.middleware.js',import.meta.url),output=result.outputFiles[0].text;
if(process.argv.includes('--check')){
if(await fs.readFile(file,'utf8')!==output)throw Error('发布中间件与源码不一致,请先运行 npm run build');
}else await fs.writeFile(file,output);
+19 -3
View File
@@ -2,9 +2,10 @@ import fs from "node:fs/promises";
import {constants} from "node:fs";
import path from "node:path";
import {fileURLToPath} from "node:url";
import {randomBytes, randomUUID} from "node:crypto";
import {randomBytes, randomUUID, createHash} from "node:crypto";
import {secureDir, stateRoot, configRoot} from "./grant-store.mjs";
import {validKey} from "./crypto.js";
import {configuredNames} from "./policy.js";
const fields = ["authKey", "receiptReadKey", "authorizationKey"];
const pluginRoot = fileURLToPath(new URL("..", import.meta.url)).replace(/\/$/, "");
@@ -29,8 +30,7 @@ async function writeTemporary(file, text) {
}
function owns(spec) {
return spec === pluginRoot || /^@magpie-community\/middleware-company-guard(?:@[^/\s]+)?$/.test(spec || "") ||
/^(?:github:cyanask\/magpie-company-guard|(?:git\+)?https:\/\/github\.com\/cyanask\/magpie-company-guard(?:\.git)?)(?:#.*)?$/.test(spec || "");
return spec === pluginRoot || /^@magpie-community\/middleware-company-guard(?:@[^/\s]+)?$/.test(spec || "") || /^(?:github:cyanask\/magpie-company-guard|(?:git\+)?https:\/\/github\.com\/cyanask\/magpie-company-guard(?:\.git)?)(?:#.*)?$/.test(spec || "");
}
// The Bun hooks, page bridge and synchronous middleware must share the same
@@ -87,3 +87,19 @@ export async function initializeOptions(options = {}) {
Object.assign(options, keys);
return options;
}
export function validateCompanyRules(companies) {
if(!Array.isArray(companies)||companies.some(c=>typeof c!=="string"&&(!c||typeof c!=="object"||Array.isArray(c)||typeof c.name!=="string"||(c.aliases!==undefined&&!Array.isArray(c.aliases)))))throw new Error("invalid_rules");
const names=companies.flatMap(c=>typeof c==="string"?[c]:[c.name,...(c.aliases||[])]);
if(names.length>512)throw new Error("too_many_names");
try{configuredNames({companies});}catch{throw new Error("invalid_names");}
const seen=new Map();
for(let rule=0;rule<companies.length;rule++){const row=companies[rule],values=typeof row==='string'?[row]:[row.name,...row.aliases||[]];for(let field=0;field<values.length;field++){const key=values[field].toLowerCase();if(seen.has(key)){const error=new Error('duplicate_names');error.conflicts=[seen.get(key),{rule:rule+1,field}];throw error;}seen.set(key,{rule:rule+1,field});}}
return {ruleCount:companies.length,nameCount:names.length,revision:companyRulesRevision(companies)};
}
export function companyRulesRevision(companies) {
// The host serializes option objects with a different key order. Compare
// their content while retaining the order of rules and aliases.
const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==="object"?Object.fromEntries(Object.keys(value).sort().map(key=>[key,canonical(value[key])])):value;
return createHash("sha256").update(JSON.stringify(canonical(companies||[]))).digest("hex");
}
+10 -1
View File
@@ -68,12 +68,21 @@ export function inspectRequest(body, protocol) {
add(body, "instructions", {source: "instruction", index: -1});
if (typeof body.system === "string") add(body, "system", {source: "instruction", index: -1}); else blocks(body.system, {source: "instruction", index: -1});
if (body.systemInstruction) blocks(body.systemInstruction.parts, {source: "instruction", index: -1});
const schemaValue = (owner, key, depth) => {
if (++nodes > 50000 || depth > 48) throw new Error("input_structure_limit");
const value = owner[key];
if (typeof value === "string") add(owner, key, {source:"schema", index:-1});
else if (value && typeof value === "object") for (const k of Object.keys(value)) schemaValue(value, k, depth + 1);
};
const schema = (v, depth = 0) => {
if (!v || typeof v !== "object") return;
if (++nodes > 50000 || depth > 48) throw new Error("input_structure_limit");
for (const k of Object.keys(v)) {
if (["description", "title"].includes(k)) add(v, k, {source: "schema", index: -1});
else if (k === "enum" && Array.isArray(v[k])) for (let i = 0; i < v[k].length; i++) add(v[k], i, {source: "schema", index: -1});
else if (["enum", "const", "default", "examples"].includes(k)) schemaValue(v, k, depth + 1);
else if (["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"].includes(k) && v[k] && typeof v[k] === "object") {
for (const child of Object.values(v[k])) schema(child, depth + 1);
}
else if (typeof v[k] === "object") schema(v[k], depth + 1);
}
};
@@ -2,7 +2,7 @@ import path from "node:path";
import os from "node:os";
import {fileURLToPath} from "node:url";
import {stateRoot} from "./grant-store.mjs";
import {readTail, readReceiptConfirmations, receiptCheckpoint, receiptAgent} from "./receipts.mjs";
import {readTail, readReceiptConfirmations, receiptCheckpoint, receiptAgent, receiptHealth} from "./receipts.mjs";
export async function getReceiptReport({day = new Date().toISOString().slice(0,10), root = stateRoot(), task, appLog, records = []} = {}) {
if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) throw new Error("invalid_date");
@@ -55,7 +55,7 @@ export async function getReceiptReport({day = new Date().toISOString().slice(0,1
} else {
statusCode = "awaiting_completion"; statusLabel = "等待完成通知"; statusReason = g.reply_processed?.ok ? "插件已确认回复处理,尚未取得宿主完整完成通知。" : "输入已检查,尚未取得完整的回复处理及宿主完成通知;这不证明请求仍在运行。";
}
return {id, task:p?.task || reply?.task, thread:p?.thread || reply?.thread, agent:receiptAgent(p?.agent || reply?.agent), at:p?.startedAt || reply?.startedAt, version:p?.version || reply?.version, status, statusCode, statusLabel, statusReason, completionSource, preparedStatus:p?.status || "not_observed", authorization:p?.authorization || "unknown", authorizationCoverage:p?.authorizationCoverage || "none", authorizationReason:p?.authorizationReason || "unknown", allowedOccurrences:p?.allowedOccurrences ?? null, matchedNames:p?.matchedNames ?? null, replacedNames:p?.replacedNames ?? null, replacements:p?.replacements ?? null, scopes:p?.scopes || {}, processingMs:p?.processingMs ?? null, requestChecked:!!g.request_checked?.ok, replyProcessingObserved:!!g.reply_processed, replyProcessingOK:g.reply_processed?.ok ?? null, replyProcessingReason:["processed","upstream_incomplete","restoration_incomplete"].includes(g.reply_processed?.reason) ? g.reply_processed.reason : null, replyEventType:["response.completed","response.failed","response.incomplete","message_stop","chat.completed","gemini.completed","error"].includes(g.reply_processed?.eventType) ? g.reply_processed.eventType : null, requestCheckpoint:receiptCheckpoint(g.request_checked), replyCheckpoint:receiptCheckpoint(g.reply_processed), restoredNames:g.reply_processed?.restoredNames ?? null, hostCompletionObserved:reply?.hostCompletionObserved ?? null, replyCaptured:reply?.replyCaptured ?? null, remainingCurrentPlaceholders:reply?.remainingCurrentPlaceholders ?? (streamComplete ? 0 : null)};
return {rulesRevision:p?.rulesRevision||null,taskAliases:p?.taskAliases??null,aliasConflicts:p?.aliasConflicts??null,aliasLimitReached:p?.aliasLimitReached===true,id, task:p?.task || reply?.task, thread:p?.thread || reply?.thread, agent:receiptAgent(p?.agent || reply?.agent), at:p?.startedAt || reply?.startedAt, version:p?.version || reply?.version, status, statusCode, statusLabel, statusReason, completionSource, preparedStatus:p?.status || "not_observed", authorization:p?.authorization || "unknown", authorizationCoverage:p?.authorizationCoverage || "none", authorizationReason:p?.authorizationReason || "unknown", allowedOccurrences:p?.allowedOccurrences ?? null, matchedNames:p?.matchedNames ?? null, replacedNames:p?.replacedNames ?? null, replacements:p?.replacements ?? null, scopes:p?.scopes || {}, processingMs:p?.processingMs ?? null, requestChecked:!!g.request_checked?.ok, replyProcessingObserved:!!g.reply_processed, replyProcessingOK:g.reply_processed?.ok ?? null, replyProcessingReason:["processed","upstream_incomplete","restoration_incomplete"].includes(g.reply_processed?.reason) ? g.reply_processed.reason : null, replyEventType:["response.completed","response.failed","response.incomplete","message_stop","chat.completed","gemini.completed","error"].includes(g.reply_processed?.eventType) ? g.reply_processed.eventType : null, requestCheckpoint:receiptCheckpoint(g.request_checked), replyCheckpoint:receiptCheckpoint(g.reply_processed), restoredNames:g.reply_processed?.restoredNames ?? null, hostCompletionObserved:reply?.hostCompletionObserved ?? null, replyCaptured:reply?.replyCaptured ?? null, remainingCurrentPlaceholders:reply?.remainingCurrentPlaceholders ?? (streamComplete ? 0 : null)};
}).sort((a,b)=>(b.at||"").localeCompare(a.at||""));
return {date:day,rows,diagnostics:{events:errors.slice(-25), observed:errors.length, omitted:Math.max(0,errors.length-25), requestAttribution:"unavailable"},limits:["未命中不代表没有敏感名称", "无回执或宿主回调、日志缺失均不能视为已保护", "本地检查和还原记录不证明所有名称均被识别", "status保留兼容分组;statusCode、statusLabel和statusReason说明当前分类及证据缺口", "回调错误日志没有请求编号,不能据此归因到某一条回执", "本工具读取每日回执末尾8MiB及应用日志末尾4MiB;日志轮转或宿主限流可能造成确认缺失"]};
return {health:await receiptHealth(root),date:day,rows,diagnostics:{events:errors.slice(-25), observed:errors.length, omitted:Math.max(0,errors.length-25), requestAttribution:"unavailable"},limits:["未命中不代表没有敏感名称", "无回执或宿主回调、日志缺失均不能视为已保护", "本地检查和还原记录不证明所有名称均被识别", "status保留兼容分组;statusCode、statusLabel和statusReason说明当前分类及证据缺口", "回调错误日志没有请求编号,不能据此归因到某一条回执", "本工具读取每日回执末尾8MiB及应用日志末尾4MiB;日志轮转或宿主限流可能造成确认缺失"]};
}
+30 -5
View File
@@ -5,8 +5,9 @@ import os from "node:os";
import {createHash, randomUUID} from "node:crypto";
import {retainDetails} from "./receipt-details.mjs";
import {secureDir, stateRoot} from "./grant-store.mjs";
import {companyRulesRevision} from "./local-options.mjs";
export const RECEIPT_VERSION = "0.4.3";
export const RECEIPT_VERSION = "0.4.6";
const writes = new Map();
export const RECEIPT_LIMIT = 25;
@@ -33,17 +34,31 @@ export async function readReceiptConfirmations(ids, appLog, text) {
// and replace complete files so readers never observe a partial JSON line.
export function retainReceipts(root, incoming, appLog) {
const prior = writes.get(root) || Promise.resolve();
const next = prior.catch(() => {}).then(() => retain(root, incoming, appLog));
const next = prior.catch(() => {}).then(() => retain(root, incoming, appLog)).catch(async error => {
try { await saveReceiptHealth(root, {writeFailed:true}); } catch {}
throw error;
});
writes.set(root, next);
next.finally(() => { if (writes.get(root) === next) writes.delete(root); }).catch(() => {});
return next;
}
async function saveReceiptHealth(root, update) {
const file=path.join(root,"receipt-health.json");
let prior={};try{prior=JSON.parse(await readTail(file,8192));}catch{}
const value={lastSuccessfulWrite:prior.lastSuccessfulWrite||null,recoveredFiles:prior.recoveredFiles||0,...update};
const temp=file+"."+randomUUID()+".tmp";
try {const fd=await fs.open(temp,"wx",0o600);try{await fd.writeFile(JSON.stringify(value));await fd.sync();}finally{await fd.close();}await fs.rename(temp,file);}finally{await fs.rm(temp,{force:true});}
}
export async function receiptHealth(root) {
try {const value=JSON.parse(await readTail(path.join(root,"receipt-health.json"),8192));return {available:true,writeFailed:value.writeFailed===true,lastSuccessfulWrite:value.lastSuccessfulWrite||null,recoveredFiles:Number.isSafeInteger(value.recoveredFiles)?value.recoveredFiles:0};}catch{return {available:false,writeFailed:false,lastSuccessfulWrite:null,recoveredFiles:0};}
}
async function retain(root, incoming, appLog) {
const dir = path.join(root, "receipts");
await secureDir(root, true); await secureDir(dir, true);
const files = (await fs.readdir(dir)).filter(n => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(n)).sort();
const originals = new Map(), groups = new Map();
const originals = new Map(), groups = new Map();let recoveredFiles=0;
const add = row => {
if (!/^[a-f0-9-]{36}$/i.test(row.id || "") || !["prepared", "response_observed", "request_checked", "reply_processed"].includes(row.phase) || !/^\d{4}-\d{2}-\d{2}T/.test(row.startedAt || "")) throw new Error("invalid_receipt_record");
if (["request_checked", "reply_processed"].includes(row.phase)) {
@@ -60,7 +75,15 @@ async function retain(root, incoming, appLog) {
const stat = await fd.stat();
if (!stat.isFile() || stat.uid !== process.getuid() || (stat.mode & 0o077) || stat.size > 64*1024*1024) throw new Error("unsafe_receipt_file");
const text = await fd.readFile("utf8"); originals.set(name,text);
for (const line of text.split("\n")) if (line.trim()) add(JSON.parse(line));
let damaged=false;
for (const line of text.split("\n")) if (line.trim()) {try{add(JSON.parse(line));}catch{damaged=true;}}
if(damaged){
const recovery=path.join(root,"receipt-recovery");await secureDir(recovery,true);
// Preserve the entire source before replacing it with readable records.
const backup=path.join(recovery,name+"."+randomUUID()+".bak"),saved=await fs.open(backup,"wx",0o600);
try{await saved.writeFile(text);await saved.sync();}finally{await saved.close();}
recoveredFiles++;
}
} finally { await fd.close(); }
}
if (incoming) add(incoming);
@@ -84,6 +107,8 @@ async function retain(root, incoming, appLog) {
}
for (const name of originals.keys()) if (!output.has(name)) await fs.unlink(path.join(dir,name));
retainDetails(root,new Set(kept.map(([id])=>id)));
const health=await receiptHealth(root);
await saveReceiptHealth(root,{writeFailed:false,lastSuccessfulWrite:new Date().toISOString(),recoveredFiles:health.recoveredFiles+recoveredFiles});
return {retained:kept.length,removed:groups.size-kept.length};
}
const opaqueId = value => {
@@ -100,7 +125,7 @@ export const receiptAgent = value => typeof value === "string" && /^[a-z0-9][a-z
export async function appendReceipt(ctx, base, phase, details = {}) {
try {
const count = n => Number.isSafeInteger(n) && n >= 0 ? n : 0;
const row = {...base, phase, at: new Date().toISOString()};
const row = {...base, phase, at: new Date().toISOString(),rulesRevision:companyRulesRevision(ctx.options?.companies)};
if (phase === "prepared") {
row.status = ["replaced", "no_match", "authorized", "failed"].includes(details.status) ? details.status : "failed";
row.errorCode = details.error ? "preparation_failed" : null;
@@ -0,0 +1,20 @@
import fs from 'node:fs/promises';
import {constants} from 'node:fs';
import path from 'node:path';
import {secureDir} from './grant-store.mjs';
import {companyRulesRevision,validateCompanyRules} from './local-options.mjs';
async function tail(file){
let fd;try{fd=await fs.open(file,constants.O_RDONLY|constants.O_NOFOLLOW);const stat=await fd.stat();if(!stat.isFile()||stat.uid!==process.getuid()||(stat.mode&0o077))throw Error('unsafe_history');const start=Math.max(0,stat.size-128*1024),buffer=Buffer.alloc(stat.size-start);const {bytesRead}=await fd.read(buffer,0,buffer.length,start);return buffer.subarray(0,bytesRead).toString('utf8').split('\n').flatMap(line=>{try{return [JSON.parse(line)];}catch{return [];}});}catch(error){if(error.code==='ENOENT')return [];throw error;}finally{await fd?.close();}
}
export async function recordRuleRevision(root,companies){
await secureDir(root,true);const file=path.join(root,'rule-events.jsonl'),revision=companyRulesRevision(companies),existing=await tail(file);
if(existing.at(-1)?.revision===revision)return;
const checked=validateCompanyRules(companies||[]),fd=await fs.open(file,constants.O_WRONLY|constants.O_APPEND|constants.O_CREAT|constants.O_NOFOLLOW,0o600);
try{const stat=await fd.stat();if(!stat.isFile()||stat.uid!==process.getuid()||(stat.mode&0o077))throw Error('unsafe_history');await fd.writeFile(JSON.stringify({at:new Date().toISOString(),revision,ruleCount:checked.ruleCount,nameCount:checked.nameCount})+'\n');await fd.sync();}finally{await fd.close();}
}
export async function readAuditHistory(root){
const rules=(await tail(path.join(root,'rule-events.jsonl'))).filter(r=>r&&/^[a-f0-9]{64}$/.test(r.revision||'')).slice(-100).reverse().map(r=>({at:r.at,revision:r.revision,ruleCount:r.ruleCount,nameCount:r.nameCount}));
const authorizations=(await tail(path.join(root,'authorization-events.jsonl'))).filter(r=>r&&['approve','revoke'].includes(r.action)).slice(-100).reverse().map(r=>({at:r.at,session:r.session,action:r.action,coverage:r.coverage,nameCount:r.nameCount}));
return {rules,authorizations};
}
@@ -3,6 +3,7 @@ import {sign, same, validKey, digest} from "./crypto.js";
const PREFIX = "nero.session.authorization.v1\0";
const validId = value => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{1,127}$/.test(value);
export const AUTHORIZATION_REQUEST = "申请本会话原名放行";
export const AUTHORIZATION_ENTRY_LIMIT = 100;
export function sessionIdentity(body, ctx) {
if (ctx?.agent !== "codex" || (ctx.origin && !["local", "magpie-key"].includes(ctx.origin))) return null;
@@ -51,11 +52,23 @@ export function readAuthorization(envelope, key, verifyContents=true) {
return record;
}
export function planAuthorizationEntries(entries, record, key, legacySessions = new Set()) {
const retained = entries.filter(envelope => {
const prior = readAuthorization(envelope, key);
if (!prior) throw new Error("invalid_registry");
// Keep a revocation while an independent legacy grant could still revive it.
return envelope.session !== record.session && (prior.state === "active" || legacySessions.has(envelope.session));
});
const entry = signAuthorization(record, key), next = retained.concat(entry);
if (next.length > AUTHORIZATION_ENTRY_LIMIT || JSON.stringify(next).length > 3 * 1024 * 1024) throw new Error("authorization_too_large");
return {entry, entries:next};
}
export function resolveAuthorization(body, ctx) {
const id = sessionIdentity(body,ctx);
if (!id) return {record:null, reason:"request_identity_unavailable", managed:false};
const entries = ctx.options?.sessionAuthorizations;
if (!Array.isArray(entries) || entries.length > 64) return {record:null, managed:false};
if (!Array.isArray(entries) || entries.length > AUTHORIZATION_ENTRY_LIMIT) return {record:null, managed:false};
const matching = entries.filter(e => e?.session === id.session);
if (!matching.length) return {record:null, managed:false};
if (matching.length !== 1) return {record:null, managed:true, reason:"authorization_invalid"};
@@ -10,8 +10,10 @@ import {onRequest as hookRequest, onResponse as hookResponse} from "../company-g
import {retainReceipts} from "../src/receipts.mjs";
import {getReceiptReport} from "../src/receipt-report.mjs";
import {onRequest as middlewareRequest, onResponse as middlewareResponse, onEvent as middlewareEvent} from "../dist/company-guard.middleware.js";
import {initializeOptions} from "../src/local-options.mjs";
import {signAuthorization} from "../src/session-authorization.js";
import {initializeOptions,validateCompanyRules,companyRulesRevision} from "../src/local-options.mjs";
import {signAuthorization,readAuthorization,planAuthorizationEntries,AUTHORIZATION_ENTRY_LIMIT} from "../src/session-authorization.js";
import * as pageEntry from "../receipt-page.mjs";
import {recordRuleRevision,readAuditHistory} from '../src/rule-history.mjs';
// Synthetic fixtures only: no user credentials, companies, grants or history.
const NAME = ["单元", "测试", "科技", "有限", "公司"].join("");
@@ -20,6 +22,24 @@ const TURN = "22222222-2222-4222-8222-222222222222";
const ROOT = fileURLToPath(new URL("..", import.meta.url)).replace(/\/$/, "");
const keyFields = ["authKey", "receiptReadKey", "authorizationKey"];
const newKeys = () => Object.fromEntries(keyFields.map(field => [field, randomBytes(32).toString("hex")]));
test("plugin entry exposes only the host factory",()=>assert.deepEqual(Object.keys(pageEntry),["ReceiptPage"]));
test("rule editing validates the same names as the request processor without mutating options",()=>{
const companies=[{name:NAME,aliases:[NAME.slice(0,4),NAME.slice(0,2)]}],before=JSON.stringify(companies);
const result=validateCompanyRules(companies);
assert.equal(result.ruleCount,1);assert.equal(result.nameCount,3);
assert.equal(result.revision,companyRulesRevision(companies));
assert.equal(result.revision,companyRulesRevision([{aliases:companies[0].aliases,name:NAME}]));
assert.equal(JSON.stringify(companies),before);
assert.notEqual(result.revision,companyRulesRevision([NAME]));
assert.deepEqual(validateCompanyRules([]),{ruleCount:0,nameCount:0,revision:companyRulesRevision([])});
});
test("rule editing rejects malformed, numeric, repeated and oversized lists",()=>{
for(const value of [null,{},[null],[{name:NAME,aliases:NAME}]])assert.throws(()=>validateCompanyRules(value),/invalid_rules/);
for(const value of [[SESSION],[NAME+'\n'],[{name:NAME,aliases:[null]}]])assert.throws(()=>validateCompanyRules(value),/invalid_names/);
assert.throws(()=>validateCompanyRules([NAME,NAME]),/duplicate_names/);
assert.throws(()=>validateCompanyRules([{name:NAME,aliases:[NAME]}]),/duplicate_names/);
assert.throws(()=>validateCompanyRules(Array(513).fill(NAME)),/too_many_names/);
});
function context(protocol, options = {}) {
return {protocol, origin:"local", agent:"codex", session:SESSION, cwd:"/tmp/company-guard-fixture", state:{},
options:{...newKeys(), companies:[NAME], ...options}, reject(status, message) { throw new Error(status + ": " + message); }};
@@ -45,6 +65,28 @@ function prepare(protocol, options) {
return {ctx, body, token};
}
test("multiple aliases each match and restore their original spelling",()=>{
const aliases=[NAME.slice(0,4),NAME.slice(0,2)],original=[NAME,...aliases].join("\n");
const ctx=context("responses",{companies:[{name:NAME,aliases}]}),body=request("responses",original);
prepareRequest(body,ctx);
assert.equal(ctx.state.guard.metrics.replacedNames,3);
assert.deepEqual(new Set(Object.values(ctx.state.guard.reverse)),new Set([NAME,...aliases]));
const response={output:[{type:"message",content:[{type:"output_text",text:body.input[0].content[0].text}]}]};
onResponse(response,ctx);assert.equal(response.output[0].content[0].text,original);
});
test("schema value fields are protected by source and released middleware without changing structural keys",()=>{
for(const prepare of [prepareRequest,middlewareRequest]){
const ctx=context('responses'),body=request('responses');
body.tools=[{type:'function',name:'lookup',parameters:{type:'object',properties:{default:{type:'string',const:NAME,default:NAME,examples:[NAME,{company:NAME}]}},required:['default']}}];
prepare(body,ctx);
const schema=body.tools[0].parameters;
assert.equal(body.tools[0].name,'lookup');assert.equal(schema.properties.default.type,'string');assert.deepEqual(schema.required,['default']);
assert(!JSON.stringify(schema).includes(NAME));
assert(Object.values(ctx.state.guard.reverse).includes(NAME));
}
});
for (const protocol of ["responses", "chat", "anthropic", "gemini"]) {
test(protocol + ": request masking and reply restoration", () => {
const {ctx, token} = prepare(protocol);
@@ -119,6 +161,42 @@ for (const coverage of ["names", "all"]) {
assert.equal(ctx.state.guard.metrics.authorizationReason, "session_revoked");
});
}
test("revoked sessions do not exhaust authorization slots; active and legacy limits remain enforced", () => {
const ctx=context("responses"),key=ctx.options.authKey;
const record=(session,state="active")=>({v:1,session,workspace:ctx.cwd,state,coverage:"all",names:[],created:Date.now()});
let entries=[];
for(let index=0;index<AUTHORIZATION_ENTRY_LIMIT+6;index++){
const session=SESSION+"_"+index;
entries=planAuthorizationEntries(entries,record(session),key).entries;
entries=planAuthorizationEntries(entries,record(session,"revoked"),key).entries;
assert.equal(entries.length,1);
assert.equal(readAuthorization(entries[0],key).state,"revoked");
}
entries=planAuthorizationEntries(entries,record(SESSION),key).entries;
assert.equal(entries.length,1);
ctx.options.sessionAuthorizations=entries;
const approved=request("responses");prepareRequest(approved,ctx);
assert(JSON.stringify(approved).includes(NAME));
const fullRevoked=Array.from({length:64},(_,index)=>signAuthorization(record(SESSION+"_"+index,"revoked"),key));
assert.equal(planAuthorizationEntries(fullRevoked,record(SESSION),key).entries.length,1,"existing 64 revoked records must recover without hand-editing options");
const fullActive=Array.from({length:AUTHORIZATION_ENTRY_LIMIT},(_,index)=>signAuthorization(record(SESSION+"_"+index),key));
ctx.options.sessionAuthorizations=fullActive;ctx.session=fullActive.at(-1).session;
const last=request("responses");last.client_metadata.thread_id=ctx.session;
prepareRequest(last,ctx);assert(JSON.stringify(last).includes(NAME),"the request runtime must honor the last grant in a full table");
const before=JSON.stringify(fullActive);
assert.throws(()=>planAuthorizationEntries(fullActive,record(SESSION),key),/authorization_too_large/);
assert.equal(JSON.stringify(fullActive),before,"capacity rejection cannot evict active grants");
const revoked=planAuthorizationEntries(fullActive,record(SESSION+"_0","revoked"),key).entries;
assert.equal(planAuthorizationEntries(revoked,record(SESSION),key).entries.length,AUTHORIZATION_ENTRY_LIMIT,"revoking a full table frees a slot for the next approval");
const legacySession=SESSION+"_legacy",marker=signAuthorization(record(legacySession,"revoked"),key);
const protectedPlan=planAuthorizationEntries([marker],record(SESSION),key,new Set([legacySession]));
assert(protectedPlan.entries.some(e=>e.session===legacySession),"legacy-backed revocation cannot be discarded");
assert(!planAuthorizationEntries(protectedPlan.entries,record(TURN),key).entries.some(e=>e.session===legacySession),"marker can be removed once the independent grant is gone");
const large=Array.from({length:63},(_,index)=>signAuthorization({...record(SESSION+"_"+index),workspace:"/"+"x".repeat(50000)},key));
assert.throws(()=>planAuthorizationEntries(large,{...record(SESSION),workspace:"/"+"x".repeat(50000)},key),/authorization_too_large/,"the size limit remains in force");
});
test("authorization cannot cross sessions or workspaces; altered seals do not authorize", () => {
const ctx = context("responses"), approved = authorization(ctx);
ctx.options.sessionAuthorizations = [approved];
@@ -152,6 +230,11 @@ test("fresh install generates three private persistent keys and preserves unrela
const saved = JSON.parse(await fs.readFile(setup.configFile));
assert.deepEqual(saved.plugins[1], setup.config.plugins[1]); assert.deepEqual(saved.prefer, setup.config.prefer);
const again = await initializeOptions({...saved.plugins[0].options});
const auditRoot=path.dirname(setup.keyFile);
await recordRuleRevision(auditRoot,options.companies);await recordRuleRevision(auditRoot,options.companies);
const history=await readAuditHistory(auditRoot);
assert.equal(history.rules.length,1);assert.equal(history.rules[0].revision,companyRulesRevision(options.companies));
assert(!JSON.stringify(history).includes(NAME));
for (const field of keyFields) assert.equal(again[field], options[field]);
assert.equal((await fs.stat(setup.configFile)).mode & 0o777, 0o600);
});
@@ -163,7 +246,7 @@ test("a pinned GitHub installation initializes without a local-path registration
const saved = JSON.parse(await fs.readFile(setup.configFile));
for (const field of keyFields) assert.equal(saved.plugins[0].options[field], options[field]);
});
for (const spec of ["@magpie-community/middleware-company-guard", "@magpie-community/middleware-company-guard@0.4.3"]) {
for (const spec of ["@magpie-community/middleware-company-guard", "@magpie-community/middleware-company-guard@0.4.6"]) {
test("community installation initializes: " + spec, async t => {
const setup = await installation(t);
setup.config.plugins[0].spec = spec;
@@ -257,6 +340,21 @@ test("fresh hook preparation and native middleware share keys and remove the pri
assert.equal((await report()).agent,"codex");
await fs.writeFile(appLog,"");
assert.equal((await report()).statusCode,"completed","persisted confirmations survive log rotation");
const original=await fs.readFile(file,'utf8'),damaged=original+JSON.stringify(records[0]).slice(0,-1);
await fs.writeFile(file,damaged);
await retainReceipts(root,undefined,appLog);
assert.equal((await report()).statusCode,'completed');
const backups=await fs.readdir(path.join(root,'receipt-recovery'));
assert.equal(backups.length,1);
assert.equal(await fs.readFile(path.join(root,'receipt-recovery',backups[0]),'utf8'),damaged);
assert.equal((await getReceiptReport({day,root,appLog})).health.recoveredFiles,1);
await retainReceipts(root,records[0],appLog);
assert.equal((await getReceiptReport({day,root,appLog})).health.writeFailed,false);
await fs.chmod(file,0o644);
await assert.rejects(retainReceipts(root,undefined,appLog),/unsafe_receipt_file/);
assert.equal((await getReceiptReport({day,root,appLog})).health.writeFailed,true);
await fs.chmod(file,0o600);await retainReceipts(root,undefined,appLog);
assert.equal((await getReceiptReport({day,root,appLog})).health.writeFailed,false);
await fs.unlink(file);
assert.equal((await report(records)).statusCode,"completed","fixed snapshots survive recent-window eviction");
assert.equal((await report(records.filter(r=>r.phase!=="request_checked"))).statusCode,"request_confirmation_missing");