From 001a1f9fbfb1db4922ea3624539afaff0e1b2a15 Mon Sep 17 00:00:00 2001 From: cyanask <44457432+cyanask@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:18:13 +0800 Subject: [PATCH] company-guard 0.4.3: reversible company-name masking middleware (#903) New middleware package @magpie-community/middleware-company-guard 0.4.3 (ported by @cyanask from cyanask/magpie-company-guard): masks company names in requests with stable per-session aliases, restores them in replies (Responses, Chat Completions, Anthropic Messages, Gemini; streaming and tool arguments), keeps local receipts, and lets a Codex session be approved explicitly. macOS only ("os": ["darwin"]). The receipt page listens on 127.0.0.1:3469 only; nothing goes to an outside host. Review fixes since 07587b9: default port 3478 (atomcode's) -> 3469, unused in the repo; the three local keys are generated on first run into /magpie/company-guard/keys.json (0600, O_NOFOLLOW, owner-checked) and written into this plugin's own plugins.json entry, so install works with no setup; 27 tests. Run at 7a147166 on mica: node --test 27 pass, bun test 27 pass; esbuild 0.25.12 rebuild of dist/company-guard.middleware.js is byte-identical (sha256 b2faf535...); merged with origin/main, scripts/check.mjs ok, bun test scripts 24 pass. Broken by hand: onEvent returning the event unrestored -> the four split-chunk tests red; initializeOptions without publishKeys -> five install tests red. Not tried: a real magpie install end to end. The package is not on npm yet, so it is served from the dist branch until its first npm publish. --- README.md | 1 + packages/company-guard/.gitignore | 17 + packages/company-guard/LICENSE | 21 + packages/company-guard/README.md | 93 ++ packages/company-guard/THIRD_PARTY_NOTICES.md | 7 + .../company-guard/company-guard.hooks.mjs | 92 ++ .../dist/company-guard.middleware.js | 1313 +++++++++++++++++ packages/company-guard/package-lock.json | 507 +++++++ packages/company-guard/package.json | 71 + packages/company-guard/page/app.js | 96 ++ .../company-guard/page/authorization.html | 23 + packages/company-guard/page/authorization.js | 102 ++ packages/company-guard/page/dashboard.html | 24 + packages/company-guard/page/index-0.3.3.html | 2 + packages/company-guard/page/open.js | 11 + packages/company-guard/page/style.css | 43 + packages/company-guard/receipt-page.mjs | 227 +++ packages/company-guard/receipt-report.mjs | 14 + packages/company-guard/src/company-guard.js | 336 +++++ packages/company-guard/src/crypto.js | 41 + packages/company-guard/src/grant-store.mjs | 111 ++ packages/company-guard/src/local-options.mjs | 89 ++ packages/company-guard/src/policy.js | 245 +++ packages/company-guard/src/protocols.js | 109 ++ .../company-guard/src/receipt-details.mjs | 32 + packages/company-guard/src/receipt-report.mjs | 61 + packages/company-guard/src/receipts.mjs | 148 ++ .../src/session-authorization.js | 67 + .../company-guard/test/company-guard.test.mjs | 267 ++++ packages/company-guard/vendor/LICENSE.magpie | 21 + .../company-guard/vendor/LICENSE.noble-hashes | 21 + .../company-guard/vendor/LICENSE.word-guard | 21 + packages/company-guard/vendor/hashes.js | 462 ++++++ .../company-guard/vendor/magpie-pagebridge.js | 190 +++ registry.json | 2 + 35 files changed, 4887 insertions(+) create mode 100644 packages/company-guard/.gitignore create mode 100644 packages/company-guard/LICENSE create mode 100644 packages/company-guard/README.md create mode 100644 packages/company-guard/THIRD_PARTY_NOTICES.md create mode 100644 packages/company-guard/company-guard.hooks.mjs create mode 100644 packages/company-guard/dist/company-guard.middleware.js create mode 100644 packages/company-guard/package-lock.json create mode 100644 packages/company-guard/package.json create mode 100644 packages/company-guard/page/app.js create mode 100644 packages/company-guard/page/authorization.html create mode 100644 packages/company-guard/page/authorization.js create mode 100644 packages/company-guard/page/dashboard.html create mode 100644 packages/company-guard/page/index-0.3.3.html create mode 100644 packages/company-guard/page/open.js create mode 100644 packages/company-guard/page/style.css create mode 100644 packages/company-guard/receipt-page.mjs create mode 100644 packages/company-guard/receipt-report.mjs create mode 100644 packages/company-guard/src/company-guard.js create mode 100644 packages/company-guard/src/crypto.js create mode 100644 packages/company-guard/src/grant-store.mjs create mode 100644 packages/company-guard/src/local-options.mjs create mode 100644 packages/company-guard/src/policy.js create mode 100644 packages/company-guard/src/protocols.js create mode 100644 packages/company-guard/src/receipt-details.mjs create mode 100644 packages/company-guard/src/receipt-report.mjs create mode 100644 packages/company-guard/src/receipts.mjs create mode 100644 packages/company-guard/src/session-authorization.js create mode 100644 packages/company-guard/test/company-guard.test.mjs create mode 100644 packages/company-guard/vendor/LICENSE.magpie create mode 100644 packages/company-guard/vendor/LICENSE.noble-hashes create mode 100644 packages/company-guard/vendor/LICENSE.word-guard create mode 100644 packages/company-guard/vendor/hashes.js create mode 100644 packages/company-guard/vendor/magpie-pagebridge.js diff --git a/README.md b/README.md index 9567197..68866f3 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ These packages aren't OpenCode plugins. magpie runs them in its gateway, on the | [system-prompt](packages/system-prompt) | Your own system prompt on every request, or on some agents' or models', in each API's own place | | [output-strategy](packages/output-strategy) | Seven composable output styles with a selection panel; off by default, cache-stable, and Codex `instructions` stay untouched | | [word-guard](packages/word-guard) | New API's 敏感词过滤: turn away or mask words and patterns in what users send, and in replies | +| [company-guard](packages/company-guard) | Recognize company names, mask them with stable session aliases and restore replies, with local receipts and explicit Codex session approvals; complements Word Guard's configured-word filter | | [think-tags](packages/think-tags) | Take a leading ``, `` or `` block out of a reply's text, or put a Chat reply's `reasoning_content` into it (`thinking_to_content`) | | [empty-reply](packages/empty-reply) | Drop the end of a reply that has reasoning but no text, so Claude Code and Codex retry instead of stopping | | [antigravity-cloak](packages/antigravity-cloak) | Claude Code and Claude Desktop on Antigravity: break the words Antigravity turns their system prompt away for, in what Antigravity alone is sent | diff --git a/packages/company-guard/.gitignore b/packages/company-guard/.gitignore new file mode 100644 index 0000000..8f2aa91 --- /dev/null +++ b/packages/company-guard/.gitignore @@ -0,0 +1,17 @@ +node_modules/ +.runtime/ +.cache/ +*.tgz +*.log +.env +.env.* +.DS_Store +verification/ +release/ +receipts/ +authorization-requests/ +authorization-operations/ +grants/ +plugins.json +auth.json +keys.json diff --git a/packages/company-guard/LICENSE b/packages/company-guard/LICENSE new file mode 100644 index 0000000..9a8a95b --- /dev/null +++ b/packages/company-guard/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 NERO + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/company-guard/README.md b/packages/company-guard/README.md new file mode 100644 index 0000000..63c40e5 --- /dev/null +++ b/packages/company-guard/README.md @@ -0,0 +1,93 @@ +# Magpie Company Guard + +Local company-name masking and reversible replies for Magpie, with session approvals and local receipts. + +当前版本:**0.4.3**(macOS)。 + +面向 Magpie 的公司名称保护插件:在模型请求发送前替换识别到的公司名称,在回复返回本机时还原;提供独立的“会话授权”和“脱敏回执”页面。 + +## 功能与边界 + +- 检查请求中的用户文字、历史、工具结果、工具参数和工具说明,支持 Responses、Chat Completions、Anthropic Messages、Gemini 协议。 +- 根据企业名称规则、明确的名称字段、简称定义及用户配置识别名称,同一会话内使用稳定代号。 +- 支持 Codex 单会话原名放行,可选指定名单或全部公司名称;其他会话、分叉和子任务不自动继承。 +- 保留最近 25 份回执;名称对应明细仅在插件宿主内存中限时保留,最长 30 分钟。磁盘回执不保存原名、代号或消息全文。 + +这是规则识别工具,不能保证发现所有公司名称,也不能作为完整的数据防泄漏边界。图片、音频、文件二进制内容及绕过 Magpie 的连接不在检查范围内。宿主超时、回调缺失或请求被跳过时,不能视为已完成保护。 + +本版仅支持 macOS,安装包已声明此限制;Windows 和 Linux 不在本版支持范围内。会话授权依赖 Codex 的会话元数据,其他客户端默认执行名称脱敏。插件不修改源文件或业务数据库,Magpie 自带的其他隐私保护继续按原配置运行。 + +## 安装与首次运行 + +支持 macOS,需要 Magpie 0.1.3841 或更新版本。运行时使用 Magpie 自带的 Bun,无需另外安装 Node.js 或 npm。只启用一份本插件,避免两份安装同时处理请求。 + +在终端执行: + +```sh +magpie plugin add @magpie-community/middleware-company-guard +``` + +如果标准 App 已安装,但终端找不到 `magpie` 命令,可使用: + +```sh +/Applications/magpie.app/Contents/MacOS/magpie plugin add @magpie-community/middleware-company-guard +``` + +安装后打开 Magpie → 公司名称保护。首次加载时,插件自动生成三个随机密钥,保存在本机状态目录的 `keys.json` 中,文件权限为 `0600`,目录权限为 `0700`。插件会把缺失的密钥同步到自身的 Magpie 选项,使中间件、请求 Hook 和页面使用同一套凭据;不需要手动运行配置脚本。 + +已有有效密钥、会话授权、自定义端口和其他选项继续沿用。重启不会重新生成密钥。若已有文件权限不安全、密钥损坏或两处配置冲突,初始化会停止并保留原配置,请先排查重复安装或配置变动,不要通过删除密钥文件尝试恢复。 + +默认页面端口为 `3469`,已核对本次社区插件源码未使用此端口。它只监听 `127.0.0.1`;可通过插件选项 `receiptPort` 调整。升级时已有端口设置不变,原来显式配置的 `3478` 仍会继续使用;如果同时安装 AtomCode 等使用该端口的插件,应为本插件另设端口。 + +默认状态目录为 `~/.config/magpie/company-guard`;设置了绝对路径 `XDG_CONFIG_HOME` 时,使用该目录下的 `magpie/company-guard`。显式配置的 `stateDir` 优先。密钥、授权目录和含密钥的插件选项只留在本机,不要提交或发送给他人。 + +## 会话授权 + +1. 在目标 Codex 会话单独发送“申请取消脱敏”“取消脱敏”或“原名放行”。加粗、行内代码等常见格式也可识别。 +2. 打开“公司名称保护 → 会话授权”,核对会话和工作目录,选择范围并确认。申请本身不启用授权,待确认项保留 24 小时。 +3. 名单模式最多 32 个完整名称,别名须单独列入;全部名称模式也覆盖该会话后续请求携带的历史和工具文字。 +4. 在对应卡片点击“恢复脱敏”并确认,后续请求恢复默认处理。已经发送的原文不能撤回。 + +授权只在本机保存,持续到用户主动撤销。普通回答结束、追问或中断后继续,不会自动撤销授权。页面批准、撤销使用独立凭据,回执读取凭据不能批准授权。 + +## Codex 申请轮收尾 + +可将以下规则加入你自己的 Codex 指导文件;安装本插件不会自动修改它。 + +> 独立原名放行申请:按本会话编号和工作目录只读核对一次状态,如实最终答复并收尾,不等页面审批;原业务保留,续办按用户指令。 + +## 回执 + +在“脱敏回执”页面先选智能体,再选会话任务,查看替换数量和限时明细。任务列表随智能体选择变化,筛选范围仍是所有智能体合计保留的最近 25 个请求;某个智能体没有匹配回执时会显示空结果。处理结果保留在汇总和明细中。 + +页面可见时默认每 10 秒刷新,展开明细时暂停;关闭自动刷新后,页面保留最近一次结果。刚发起的请求在回复结束前可能暂时等待确认,这与处理失败分别记录。 + +同步检查和回复处理的确认会随回执保存,日志轮转不会抹去已保存的确认。同步检查、回复处理及正常流式结束事件均已确认时,可以据此确认完成;明细会区分流式确认与宿主确认。缺少必要检查、宿主明确报告失败或回复仍有本次代号残留时,不会标为完成。未命中不代表没有敏感名称。 + +桌面版默认读取 macOS 的 `~/Library/Logs/magpie/app.log` 来核对处理确认。使用 `magpie web` 或自行重定向日志时,可在插件选项 `appLog` 中指定实际日志文件的绝对路径。保存的阶段确认和当前日志共同用于核对。必要依据仍不齐全时保留“未确认”,不会仅因等待时间较长而标为成功。 + +可从源码目录读取本机计数报告: + +```sh +node receipt-report.mjs --json +``` + +本仓库不包含用户配置、授权名单、业务材料或本机验收记录。 + +## 开发与测试 + +```sh +npm ci +npm test +npm run build +``` + +开发和测试需要 Node.js 20 或更新版本。测试使用独立的临时配置和虚构名称,覆盖四种协议的往返处理、流式分段还原、工具参数、会话授权与撤销,以及首次初始化和密钥权限。同一套测试还验证已构建中间件与 Hook 的协作、日志轮转和回执淘汰后的快照核对,并检查失败通知和代号残留不会被提升为成功。 + +`dist/` 已提交,可直接从 Git 安装,无需安装时构建。运行时使用 Magpie 自带的 Bun,无额外 npm 运行时依赖;esbuild 仅用于开发构建。社区版本由本仓库的分发流程提供;上述社区安装命令在 PR 合并并完成分发后可用。合并前,可从仓库根目录运行 `magpie plugin add ./packages/company-guard` 进行本地验证。 + +插件接口见 [Magpie 官方文档](https://usemagpie.ai/docs/plugins)。提交问题时,请使用不含真实名称、凭据和会话内容的必要诊断信息。 + +## 许可证 + +MIT。第三方组件及其许可见 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) 和 `vendor/LICENSE.*`。 diff --git a/packages/company-guard/THIRD_PARTY_NOTICES.md b/packages/company-guard/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..124c64c --- /dev/null +++ b/packages/company-guard/THIRD_PARTY_NOTICES.md @@ -0,0 +1,7 @@ +# Third-party sources + +- Word Guard, `@magpie-community/middleware-word-guard` 0.1.1, MIT. The protocol layout and hook contract were used as a reference. Its existing `cases.json` and `scripts/middleware.mjs` were reused for verification. Source: https://github.com/magpie-community/plugins/tree/main/packages/word-guard . License: `vendor/LICENSE.word-guard`. +- `@noble/hashes` 2.4.0, MIT. Only HMAC and SHA-256 are bundled in `vendor/hashes.js` and the generated middleware. Source: https://github.com/paulmillr/noble-hashes . License: `vendor/LICENSE.noble-hashes`. +- esbuild 0.25.12, MIT, used only to create the local JavaScript bundle. It is not required in the installed plugin and is not a global installation. Source: https://github.com/evanw/esbuild . + +Magpie is the unmodified host application. The official page bridge is bundled unchanged in `vendor/magpie-pagebridge.js` for the plugin-hosted receipt page. Its MIT license is retained in `vendor/LICENSE.magpie`. Reference revision: `c42522e2414dfb6bf48c0a33a0b7de088d050f26`, official application version 0.1.3113. diff --git a/packages/company-guard/company-guard.hooks.mjs b/packages/company-guard/company-guard.hooks.mjs new file mode 100644 index 0000000..00a9c8c --- /dev/null +++ b/packages/company-guard/company-guard.hooks.mjs @@ -0,0 +1,92 @@ +import { createHmac } from "node:crypto"; +import { validKey } from "./src/crypto.js"; +import { PROOF, identity, taskSession, validName, TASK_NAME_LIMIT } from "./src/policy.js"; +import { inspectRequest } from "./src/protocols.js"; +import { readGrant, stateRoot, observeAuthorizationRequest } from "./src/grant-store.mjs"; +import {resolveAuthorization} from "./src/session-authorization.js"; + +async function attachGrant(body, ctx) { + // Never accept a proof supplied by a caller, a tool result or an older request. + delete body[PROOF]; + const managed = resolveAuthorization(body,ctx); + if (managed.managed) {ctx.state.grantStatus=managed.reason;return body;} + const o = ctx.options || {}, session = taskSession(body, ctx); + ctx.state.grantStatus = "no_matching_grant"; + if (!validKey(o.authKey) || !session) { + ctx.state.grantStatus = "request_identity_unavailable"; return body; + } + try { + const record = await readGrant(stateRoot(o.stateDir), session), now = Date.now(); + if (record.v === 2 && record.scope === "session_task") { + if (!session || record.session !== session || record.mode !== "original" || + (ctx.cwd && record.workspace !== ctx.cwd) || !Number.isFinite(record.created) || record.created > now) { + ctx.state.grantStatus = "task_identity_mismatch"; return body; + } + if (record.state !== "active") { ctx.state.grantStatus = "task_not_active"; return body; } + // Human authorization belongs to this registered session task. + const names = record.names; + if (!Array.isArray(names) || !names.length || names.length > TASK_NAME_LIMIT || names.some(n => !validName(n))) throw new Error("invalid_task_names"); + const payload = JSON.stringify({v:2, scope:"session_task", thread:session, expires:now+10000, mode:"original", names}); + if (payload.length > 2 * 1024 * 1024) { ctx.state.grantStatus = "task_request_too_large"; return body; } + body[PROOF] = {payload, mac:createHmac("sha256", Buffer.from(o.authKey,"hex")).update(payload).digest("hex")}; + ctx.state.grantStatus = "session_task_active"; + return body; + } + } catch (e) { + ctx.state.grantStatus = e.code === "ENOENT" ? "no_matching_grant" : "grant_state_unavailable"; + if (e.code !== "ENOENT") ctx.report?.("company_guard_grant_unavailable", 0); + } + return body; +} + +import { rememberDetails } from "./src/receipt-details.mjs"; +import { newReceipt, appendReceipt } from "./src/receipts.mjs"; +import {initializeOptions} from "./src/local-options.mjs"; +import { prepareRequest, PREPARED } from "./src/company-guard.js"; +export async function onRequest(body, ctx) { + ctx.options ||= {}; + if (!["authKey", "receiptReadKey", "authorizationKey"].every(field => validKey(ctx.options[field]))) + await initializeOptions(ctx.options); + const started = Date.now(), receipt = newReceipt(ctx, identity(body)); + ctx.state ||= {}; ctx.state.receipt = receipt; + delete body[PREPARED]; delete body[PROOF]; + const key = ctx.options?.authKey; + if (!validKey(key)) { + await appendReceipt(ctx, receipt, "prepared", {status: "failed", error: true, processingMs: Date.now()-started}); + return body; + } + const sign = (key, value) => createHmac("sha256", Buffer.from(key, "hex")).update(value).digest("hex"); + const originalTools = body.tools === undefined ? undefined : structuredClone(body.tools); + let error, schema = []; + const local = {...ctx, state: {}, sign, reject: (_status, message) => {error = message;}}; + try { + // A request only creates a pending item. This path cannot approve it. + try { await observeAuthorizationRequest(body,ctx); } catch { ctx.report?.("unavailable",0); } + await attachGrant(body, ctx); local.grantStatus = ctx.state.grantStatus; prepareRequest(body, local); + const originalSlots = inspectRequest({tools: originalTools}, ctx.protocol).slots; + schema = inspectRequest({tools: body.tools}, ctx.protocol).slots.flatMap((s, i) => s.owner[s.key] === originalSlots[i]?.owner[originalSlots[i].key] ? [] : [[i, s.owner[s.key]]]); + } catch { error = "本地脱敏处理失败"; } + if (originalTools !== undefined) body.tools = originalTools; + const state = local.state.guard; + ctx.state.receiptTokens = Object.keys(state?.reverse || {}); + const payload = JSON.stringify({v: 1, receiptId: receipt.id, thread: identity(body)?.thread || "", session: ctx.session || "", protocol: ctx.protocol, expires: Date.now() + 20000, reverse: state?.reverse || {}, schema, error}); + body[PREPARED] = {payload, mac: sign(key, payload)}; + const status = error || !state?.ready ? "failed" : state.metrics?.replacements ? "replaced" : state.metrics?.allowedOccurrences || state.metrics?.authorizationCoverage === "all" ? "authorized" : "no_match"; + if (status !== "failed") rememberDetails(stateRoot(ctx.options?.stateDir), receipt, state?.reverse); + await appendReceipt(ctx, receipt, "prepared", {status, error: status === "failed", metrics: state?.metrics, processingMs: Date.now()-started}); + return body; +} + +export async function onResponse(reply, ctx) { + const receipt = ctx.state?.receipt; + if (!receipt) return; + let remaining = 0; + try { + const tokens = new Set(ctx.state.receiptTokens || []); + const text = JSON.stringify(reply); + for (const token of text?.match(/\[\[NERO_ORG_[a-f0-9]{24}\]\]/g) || []) if (tokens.has(token)) remaining++; + await appendReceipt(ctx, receipt, "response_observed", {success: ctx.success, replyCaptured: !!reply, remaining}); + } catch { + await appendReceipt(ctx, receipt, "response_observed", {success: false, replyCaptured: false}); + } +} diff --git a/packages/company-guard/dist/company-guard.middleware.js b/packages/company-guard/dist/company-guard.middleware.js new file mode 100644 index 0000000..730ece3 --- /dev/null +++ b/packages/company-guard/dist/company-guard.middleware.js @@ -0,0 +1,1313 @@ +// vendor/hashes.js +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); +function isBytes(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; +} +var atitle = (title) => title ? `"${title}" ` : ""; +function anumber(n, title = "") { + if (typeof n !== "number") + throw new TypeError(atitle(title) + "expected number, got " + typeof n); + if (!Number.isSafeInteger(n) || n < 0) + throw new RangeError(atitle(title) + "expected integer >= 0, got " + n); + return n; +} +function abytes(value, length, title = "") { + if (isBytes(value) && (length === void 0 || value.length === length)) + return value; + if (length !== void 0) + anumber(length, "length"); + const bytes = isBytes(value); + const ofLen = length !== void 0 ? ` of length ${length}` : ""; + const got = bytes ? `length=${value.length}` : `type=${typeof value}`; + const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got; + if (!bytes) + throw new TypeError(message); + throw new RangeError(message); +} +function ahash(h) { + if (typeof h !== "function" || typeof h.create !== "function") + throw new TypeError("expected hash wrapped by utils.createHasher"); + anumber(h.outputLen); + anumber(h.blockLen); + if (h.outputLen < 1 || h.blockLen < 1) + throw new Error("hash blockLen / outputLen must be >= 1"); +} +var aobject = (value, label) => { + if (value === null || typeof value !== "object" || Array.isArray(value)) + throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value); +}; +var aopts = (value, label) => { + aobject(value, label); + const proto = Object.getPrototypeOf(value); + if (proto !== Object.prototype && proto !== null) + throw new TypeError(`"${label}" expected plain object`); + if (Object.hasOwn(value, "__proto__")) + throw new TypeError(`"${label}.__proto__" is not allowed`); +}; +function aexists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("hash was destroyed"); + if (checkFinished && instance.finished) + throw new Error("digest() was already called"); +} +function aoutput(out, instance) { + abytes(out, void 0, "output"); + const min = instance.outputLen; + if (!(out.length >= min)) { + throw new RangeError('"output" expected length >= ' + min); + } +} +function clean(...arrays) { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } +} +function createView(arr) { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +} +function rotr(word, shift) { + return word << 32 - shift | word >>> shift; +} +function checkOpts(defaults, opts, title = "opts") { + aopts(defaults, "defaults"); + if (opts !== void 0) + aopts(opts, title); + const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts); + return merged; +} +function createHasher(hashCons, info = {}) { + if (typeof hashCons !== "function") + throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons); + info = checkOpts({}, info, "info"); + const hashC = (msg, opts) => hashCons(opts).update(msg).digest(); + const tmp = hashCons(void 0); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.canXOF = tmp.canXOF; + hashC.create = (opts) => hashCons(opts); + Object.assign(hashC, info); + return Object.freeze(hashC); +} +var oidNist = (suffix) => ({ + // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet. + // Larger suffix values would need base-128 OID encoding and a different length byte. + oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix]) +}); +var _HMAC = class { + constructor(hash, key) { + __publicField(this, "oHash"); + __publicField(this, "iHash"); + __publicField(this, "blockLen"); + __publicField(this, "outputLen"); + __publicField(this, "canXOF", false); + __publicField(this, "finished", false); + __publicField(this, "destroyed", false); + ahash(hash); + abytes(key, void 0, "key"); + this.iHash = hash.create(); + if (typeof this.iHash.update !== "function") + throw new Error("expected Hash instance"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 54; + this.iHash.update(pad); + this.oHash = hash.create(); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 54 ^ 92; + this.oHash.update(pad); + clean(pad); + } + update(buf) { + aexists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const buf = out.subarray(0, this.outputLen); + this.iHash.digestInto(buf); + this.oHash.update(buf); + this.oHash.digestInto(buf); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.canXOF = canXOF; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + clone() { + return this._cloneInto(); + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +}; +var hmac = /* @__PURE__ */ (() => { + const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest()); + hmac_.create = (hash, key) => new _HMAC(hash, key); + return hmac_; +})(); +var fromNumH = (n) => n / 2 ** 32 | 0; +var fromNumL = (n) => n >>> 0; +function setU64FromNum(view, byteOffset, n, isLE) { + const h = fromNumH(n); + const l = fromNumL(n); + view.setUint32(byteOffset, isLE ? l : h, isLE); + view.setUint32(byteOffset + 4, isLE ? h : l, isLE); +} +function Chi(a, b, c) { + return a & b ^ ~a & c; +} +function Maj(a, b, c) { + return a & b ^ a & c ^ b & c; +} +var HashMD = class { + constructor(blockLen, outputLen, padOffset, isLE) { + __publicField(this, "blockLen"); + __publicField(this, "outputLen"); + __publicField(this, "canXOF", false); + __publicField(this, "padOffset"); + __publicField(this, "isLE"); + __publicField(this, "buffer"); + __publicField(this, "view"); + __publicField(this, "finished", false); + __publicField(this, "length", 0); + __publicField(this, "pos", 0); + __publicField(this, "destroyed", false); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + aexists(this); + abytes(data); + const { view, buffer, blockLen } = this; + const len = data.length; + let processed = false; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + processed = true; + continue; + } + buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + processed = true; + } + } + this.length += data.length; + if (processed) + this.roundClean(); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + buffer[pos++] = 128; + buffer.fill(0, pos); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + buffer.fill(0); + } + setU64FromNum(view, blockLen - 8, this.length * 8, isLE); + this.process(view, 0); + this.roundClean(); + const oview = out === buffer ? view : createView(out); + const len = this.outputLen; + const outLen = len / 4; + const state = this.get(); + if (len % 4 || outLen > state.length) + throw new Error("invalid outputLen"); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneIntoMeta(to) { + const { buffer, length, finished, destroyed, pos } = this; + to.destroyed = destroyed; + to.finished = finished; + to.length = length; + to.pos = pos; + if (pos) + to.buffer.set(buffer); + return to; + } + clone() { + return this._cloneInto(); + } +}; +var SHA256_IV = /* @__PURE__ */ Uint32Array.from([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]); +var SHA256_K = /* @__PURE__ */ Uint32Array.from([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]); +var SHA256_W = /* @__PURE__ */ new Uint32Array(64); +var SHA2_32B = class extends HashMD { + constructor(outputLen, IV) { + super(64, outputLen, 8, false); + __publicField(this, "A", 0); + __publicField(this, "B", 0); + __publicField(this, "C", 0); + __publicField(this, "D", 0); + __publicField(this, "E", 0); + __publicField(this, "F", 0); + __publicField(this, "G", 0); + __publicField(this, "H", 0); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + _cloneInto(to) { + (to || (to = new this.constructor())).set(...this.get()); + return this._cloneIntoMeta(to); + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; + SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; + } + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = sigma0 + Maj(A, B, C) | 0; + H = G; + G = F; + F = E; + E = D + T1 | 0; + D = C; + C = B; + B = A; + A = T1 + T2 | 0; + } + A = A + this.A | 0; + B = B + this.B | 0; + C = C + this.C | 0; + D = D + this.D | 0; + E = E + this.E | 0; + F = F + this.F | 0; + G = G + this.G | 0; + H = H + this.H | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + clean(SHA256_W); + } + destroy() { + this.destroyed = true; + this.set(0, 0, 0, 0, 0, 0, 0, 0); + clean(this.buffer); + } +}; +var _SHA256 = class extends SHA2_32B { + constructor() { + super(32, SHA256_IV); + } +}; +var sha256 = /* @__PURE__ */ createHasher( + () => new _SHA256(), + /* @__PURE__ */ oidNist(1) +); + +// src/crypto.js +function utf8(text) { + const out = []; + for (let i = 0; i < text.length; i++) { + let cp = text.charCodeAt(i); + if (cp >= 55296 && cp <= 56319) { + const lo = text.charCodeAt(i + 1); + if (lo >= 56320 && lo <= 57343) { + cp = 65536 + (cp - 55296 << 10) + lo - 56320; + i++; + } else cp = 65533; + } else if (cp >= 56320 && cp <= 57343) cp = 65533; + if (cp < 128) out.push(cp); + else if (cp < 2048) out.push(192 | cp >> 6, 128 | cp & 63); + else if (cp < 65536) out.push(224 | cp >> 12, 128 | cp >> 6 & 63, 128 | cp & 63); + else out.push(240 | cp >> 18, 128 | cp >> 12 & 63, 128 | cp >> 6 & 63, 128 | cp & 63); + } + return new Uint8Array(out); +} +function hex(bytes) { + let out = ""; + for (const n of bytes) out += n.toString(16).padStart(2, "0"); + return out; +} +function validKey(key) { + return typeof key === "string" && /^[0-9a-f]{64}$/.test(key); +} +function keyBytes(key) { + if (!validKey(key)) throw new Error("guard_key_missing"); + const bytes = new Uint8Array(32); + for (let i = 0; i < 32; i++) bytes[i] = parseInt(key.slice(i * 2, i * 2 + 2), 16); + return bytes; +} +function sign(key, text) { + return hex(hmac(sha256, keyBytes(key), utf8(text))); +} +function scopedSigner(key, prefix) { + const base = hmac.create(sha256, keyBytes(key)).update(utf8(prefix)); + return (text) => hex(base.clone().update(utf8(text)).digest()); +} +function digest(text) { + return hex(sha256(utf8(text))); +} +function same(a, b) { + if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) return false; + let d = 0; + for (let i = 0; i < a.length; i++) d |= a.charCodeAt(i) ^ b.charCodeAt(i); + return d === 0; +} + +// src/policy.js +var PROOF = "__nero_company_guard"; +var TASK_NAME_LIMIT = 65536; +var TOKEN_PREFIX = "[[NERO_ORG_"; +function normalPrompt(s) { + return typeof s === "string" ? s.replace(/\r\n/g, "\n").trim() : ""; +} +function directive(prompt) { + const first = normalPrompt(prompt).split("\n", 1)[0]; + if (first.length > 600) return null; + const m = /^(本轮允许原名|本次允许原名|本轮不脱敏|本次不脱敏|允许原名|不脱敏|联网核查|互联网核查|互联核查)\s*[::]\s*(.+)$/.exec(first); + if (!m) return null; + const names = m[2].replace(/[。.]$/, "").split(/[;;、]/).map((s) => s.trim()); + if (!names.length || names.length > 32 || names.some((s) => !validName(s) || /^(所有|全部|任何|all|\*)$/i.test(s) || /[\n<>??!!]/.test(s))) return null; + return { mode: /核查$/.test(m[1]) ? "public_lookup" : "original", names: [...new Set(names)] }; +} +function identity(body) { + const c = body && body.client_metadata; + if (!c || typeof c !== "object") return null; + let m = c["x-codex-turn-metadata"] || c; + if (typeof m === "string") { + try { + m = JSON.parse(m); + } catch { + return null; + } + } + const ok = (x) => typeof x === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{1,127}$/.test(x); + if (!m || !ok(m.thread_id) || !ok(m.turn_id) || m.thread_source !== "user") return null; + return { thread: m.thread_id, turn: m.turn_id }; +} +function taskSession(body, ctx) { + if (!["local", "magpie-key"].includes(ctx?.origin) || ctx?.agent !== "codex" || !/^[A-Za-z0-9][A-Za-z0-9_-]{1,127}$/.test(ctx?.session || "")) return null; + const c = body?.client_metadata; + let m = c?.["x-codex-turn-metadata"] || c; + if (typeof m === "string") { + try { + m = JSON.parse(m); + } catch { + return null; + } + } + if (m && typeof m !== "object") return null; + if (m?.thread_source && !["user", "agent_created_thread"].includes(m.thread_source)) return null; + if (m?.thread_id && m.thread_id !== ctx.session) return null; + return ctx.session; +} +function readProof(proof, body, key, ctx) { + if (!proof || typeof proof.payload !== "string" || proof.payload.length > 2 * 1024 * 1024 || !same((ctx?.sign || sign)(key, proof.payload), proof.mac)) return null; + let p; + try { + p = JSON.parse(proof.payload); + } catch { + return null; + } + if (p.v === 1 && proof.payload.length > 12e3) return null; + const id = identity(body), now = Date.now(); + if (!Number.isFinite(p.expires) || p.expires <= now || p.expires > now + 15e3) return null; + const session = taskSession(body, ctx); + const task = p.v === 2 && p.scope === "session_task" && !!session && p.thread === session; + if (!task && (!id || p.v !== 1 || p.thread !== id.thread || p.turn !== id.turn)) return null; + if (!["original", "public_lookup"].includes(p.mode) || !Array.isArray(p.names) || p.names.length > (task ? TASK_NAME_LIMIT : 32) || p.names.some((n) => !validName(n))) return null; + return p; +} +function validName(s) { + return typeof s === "string" && s.length >= 2 && s.length <= 120 && !/^\s|\s$/.test(s) && /[A-Za-z\u00c0-\u024f\u3400-\u9fff]/.test(s) && !/[\x00-\x1f]/.test(s) && !s.includes(TOKEN_PREFIX); +} +function configuredNames(options) { + const out = []; + for (const c of options.companies || []) { + if (typeof c === "string") out.push(c); + else if (c && typeof c === "object") { + out.push(c.name); + if (Array.isArray(c.aliases)) out.push(...c.aliases); + } + } + if (out.length > 512 || out.some((n) => !validName(n))) throw new Error("invalid_company_options"); + return [...new Set(out)]; +} +function expandAllowed(names, options) { + const out = new Set(names); + for (const c of options.companies || []) { + if (!c || typeof c !== "object") continue; + const group = [c.name, ...Array.isArray(c.aliases) ? c.aliases : []]; + if (group.some((n) => out.has(n))) { + for (const n of group) if (validName(n)) out.add(n); + } + } + return out; +} +function environmentText(s) { + const t = s.trim(); + return t.startsWith("") || t.startsWith("") || t.startsWith("# AGENTS.md instructions for "); +} +function webTool(name) { + return ["web.run", "web__run", "functions.web__run", "mcp__codex_apps__search_service__web_search", "mcp__codex_apps__search_service__search", "mcp__codex_apps__search_service__browse"].includes(name); +} +var LEGAL_NAME = /[\u3400-\u9fffA-Za-z0-9((][\u3400-\u9fffA-Za-z0-9()()·&..\-]{1,79}?(?:股份有限公司|有限责任公司|有限公司|股份公司|集团公司)/; +var ENGLISH_KIND = /(?:Co\.,?[ \t]+Ltd\.?|Corporation|Corp\.?|Incorporated|Inc\.?|Limited|Ltd\.?|LLC|L\.L\.C\.|PLC|GmbH)/.source.replace(/\\.|Limited|[A-Za-z]/g, (value) => value === "Limited" ? "L[Ii][Mm][Ii][Tt][Ee][Dd]" : value.length === 1 ? `[${value.toUpperCase()}${value.toLowerCase()}]` : value); +var KIND_SUFFIX = /(?:股份有限公司|有限责任公司|有限公司|股份公司|集团公司|集团|公司)$/; +var GENERIC_PARTS = /(?:非上市|拟上市|非公众|供应商|交易对手|发行人|保荐人|可比|其他|任何|所有|全部|上述|相关|目标|项目|主体|企业|真实|实际|一般|普通|外部|内部|境内|境外|国内|国外|上市|公众|有限|股份|母子|集团|关联|同控|控股|参股|全资|被投|投资|持股|合作|客户|这家|那家|本|贵|该|各|某|母|子|孙)/g; +var FIELD_DESCRIPTION = /的(?:公司|集团)$|避免|当作|当成|没有|并非|不是|是否|能否|不能|不应|不要|只对|仅对|包含|保留|保护|替换|脱敏|识别|显示|看到|查看|核实|确认|表示|说明|继续|启动|存在|属于|涉及|上传|下载|配置|插件|页面|功能|工具|规则|名称|原名|本轮|本次|字段|提示词|样本|包括|以及|而非|等非|某个|某家|一家|一个|哪些|这些|这种|这类|用于|构成|均以|通过|提供的/; +var cleanName = (name) => name.replace(/^.*(?:映射最初包含|另查到|单独归入)/, "").replace(/^(?:(?:请帮我|帮我|请|查询|核查|分析|关于|公司名为|客户为|供应商为|交易对手为|以及|来自))+/, ""); +var genericName = (name) => name.replace(KIND_SUFFIX, "").replace(GENERIC_PARTS, "") === ""; +function nameFieldValue(text, field = "") { + if (typeof text !== "string") return null; + const name = text.trim(); + if (!validName(name) || genericName(name)) return null; + if (/^(?:unknown|none|null|n\/a|string|number|boolean|object|array)$/i.test(name)) return null; + const full = LEGAL_NAME.exec(name); + if (full && full[0] === name) return name; + if (/^(?:company|customer|supplier|counterparty)$/i.test(field) && /^(?:[A-Za-z_][A-Za-z0-9_]*\.)*[a-z][a-z0-9]*(?:_[a-z0-9]+)+$/.test(name)) return null; + return FIELD_DESCRIPTION.test(name) ? null : name; +} +function recognitionText(text, quotes = false) { + return text.replace(/\\+(r\\+n|[nrt"])?/g, (raw, escaped) => !escaped ? raw : escaped === '"' ? quotes ? '"' : raw : "\n"); +} +var LEGAL_HINT = /有限公司|有限责任公司|股份公司|集团公司/; +var ENGLISH_HINT = new RegExp("[ ,](?:" + ENGLISH_KIND + ")\\b"); +var FIELD_HINT = /company|customer|supplier|counterparty|entity_name|公司名称|客户名称|供应商名称|交易对手名称/i; +function scanLegalNames(text, visit) { + const suffixes = ["\u80A1\u4EFD\u6709\u9650\u516C\u53F8", "\u6709\u9650\u8D23\u4EFB\u516C\u53F8", "\u6709\u9650\u516C\u53F8", "\u80A1\u4EFD\u516C\u53F8", "\u96C6\u56E2\u516C\u53F8"]; + const next = suffixes.map((s) => text.indexOf(s)); + const legal = new RegExp(LEGAL_NAME.source, "g"); + let after = 0; + for (; ; ) { + let k = -1; + for (let i = 0; i < next.length; i++) if (next[i] >= 0 && (k < 0 || next[i] < next[k])) k = i; + if (k < 0) return; + const at = next[k], end = at + suffixes[k].length; + next[k] = text.indexOf(suffixes[k], at + 1); + if (at < after) continue; + const from = Math.max(after, at - 80); + legal.lastIndex = 0; + const m = legal.exec(text.slice(from, end)); + if (!m) continue; + m.index += from; + after = m.index + m[0].length; + for (let i = 0; i < next.length; i++) if (next[i] >= 0 && next[i] < after) next[i] = text.indexOf(suffixes[i], after); + visit(m); + } +} +function detectNames(text) { + const out = []; + const add = (s) => { + if (validName(s)) out.push(s); + }; + const legalHint = LEGAL_HINT.test(text), englishHint = ENGLISH_HINT.test(text), fieldHint = FIELD_HINT.test(text); + if (!legalHint && !englishHint && !fieldHint) return out; + text = recognitionText(text); + if (legalHint) scanLegalNames(text, (m) => { + let name = cleanName(m[0]); + if (name.startsWith("\u4E0E") && /(?:用户|您|你|贵方)[”"」』]?[))]$/.test(text.slice(Math.max(0, m.index - 24), m.index).trimEnd().replace(/\\+(?=")/g, ""))) name = name.slice(1); + if (!genericName(name)) add(name); + }); + const en = new RegExp(/\b[A-Z][A-Za-z0-9&.'’-]*(?:[ \t]+[A-Za-z0-9&.'’-]+){0,7}[ ,]+/.source + ENGLISH_KIND + /\b\.?/.source, "g"); + for (const m of englishHint ? text.matchAll(en) : []) { + if (!/\bBUT\s+NOT\s+LIMITED\.?$/i.test(m[0])) add(m[0]); + } + const fields = /(?:"(company(?:_name)?|customer(?:_name)?|supplier(?:_name)?|counterparty(?:_name)?|entity_name|公司名称|客户名称|供应商名称|交易对手名称)"\s*:\s*"((?:[^"\\]|\\.)*)"|(?:公司名称|客户名称|供应商名称|交易对手名称)[::]\s*([^\n,,;;|\t]{2,120}))/gi; + for (const m of fieldHint ? text.matchAll(fields) : []) { + if (m[2] !== void 0) { + try { + const name = nameFieldValue(JSON.parse('"' + m[2] + '"'), m[1]); + if (name) add(name); + } catch { + } + } else { + const name = nameFieldValue(m[3]); + if (name) add(name); + } + } + return [...new Set(out)]; +} +function taskAliases(slots) { + const relations = /* @__PURE__ */ new Map(), blocked = /* @__PURE__ */ new Set(); + const generic = /^(?:我们|我方|对方|双方|各方|甲方|乙方|丙方|用户|您|你|本平台|本服务|本产品|本项目|本系统|平台|服务|产品|游戏|项目|系统|科技|电子|信息|中国|简称|全称|co|corp|inc|ltd|llc)$/i; + const quoted = /^[“"「『]([^”"」』]{2,40})[”"」』]/; + for (const slot of slots) { + if (!["user", "tool"].includes(slot.source)) continue; + const original = slot.owner[slot.key]; + if (environmentText(original)) continue; + const text = recognitionText(original.replace(/```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$)|`[^`\n]*`/g, "\n"), true); + const definitions = /[((,,][ \t]*(?:(?:以下|下文)(?:简称|亦称|称)|简称(?:为)?)[ \t]*[::]?[ \t]*(?=[“"「『])/g; + for (const marker of text.matchAll(definitions)) { + const prefix = text.slice(Math.max(0, marker.index - 180), marker.index).trimEnd(); + const full = detectNames(prefix).filter((n) => prefix.endsWith(n) && (LEGAL_NAME.test(n) || /(?:Corporation|Corp\.?|Incorporated|Inc\.?|Limited|Ltd\.?|LLC|L\.L\.C\.|PLC|GmbH)$/i.test(n))).sort((a, b) => b.length - a.length)[0]; + if (!full || /(?:例如|示例|举例|样例|例子|假设|虚构)/.test(prefix.slice(prefix.lastIndexOf("\n") + 1, -full.length))) continue; + let tail = text.slice(marker.index + marker[0].length, marker.index + marker[0].length + 180); + for (let count = 0; count < 4; count++) { + const match = quoted.exec(tail); + if (!match) break; + const alias = match[1].trim(); + if (/^[\u3400-\u9fffA-Za-z0-9][\u3400-\u9fffA-Za-z0-9 &·.\-]{1,31}$/.test(alias) && nameFieldValue(alias) && !generic.test(alias) && alias.toLowerCase() !== full.toLowerCase()) { + const key = alias.toLowerCase(), prior = relations.get(key); + if (prior && prior.full.toLowerCase() !== full.toLowerCase()) blocked.add(key); + else relations.set(key, { alias, full }); + if (relations.size > 128) return { names: [], conflicts: blocked.size, limited: true }; + } + const rest = tail.slice(match[0].length), next = /^[ \t]*(?:或|、|及|和|\/)[ \t]*(?=[“"「『])/.exec(rest); + if (!next) break; + tail = rest.slice(next[0].length); + } + } + } + return { names: [...relations].filter(([key]) => !blocked.has(key)).map(([, value]) => value.alias), conflicts: blocked.size, limited: false }; +} +function escapeRE(s) { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +function namePattern(names) { + const root = /* @__PURE__ */ new Map(); + for (const name of names.slice().sort((a, b) => b.length - a.length)) { + let node = root; + for (const c of name) { + const upper = c.length === 1 ? c.toUpperCase() : c; + const key = upper.length === 1 && !(c.charCodeAt(0) >= 128 && upper.charCodeAt(0) < 128) ? upper : c; + if (!node.has(key)) node.set(key, /* @__PURE__ */ new Map()); + node = node.get(key); + } + node.set("", null); + } + const render = (node) => { + let prefix = ""; + while (node.size === 1 && !node.has("")) { + const [c, next] = node.entries().next().value; + prefix += escapeRE(c); + node = next; + } + const branches = []; + for (const [c, next] of node) if (c) branches.push(escapeRE(c) + render(next)); + if (node.has("")) branches.push(""); + return prefix + (branches.length > 1 ? "(?:" + branches.join("|") + ")" : branches[0] || ""); + }; + return render(root); +} + +// src/protocols.js +var NAME_FIELD = /^(?:company(?:_name)?|customer(?:_name)?|supplier(?:_name)?|counterparty(?:_name)?|entity_name|公司名称|客户名称|供应商名称|交易对手名称)$/i; +var OPAQUE_FIELD = /^(?:id|type|role|tool_call_id|tool_use_id|call_id|signature|encrypted_content|data|image_url|file_data|file_id|mime_type|mimeType|media_type)$/; +function inspectRequest(body, protocol) { + const slots = [], records = [], calls = /* @__PURE__ */ Object.create(null); + let nodes = 0; + const add = (owner, key, meta = {}) => { + if (typeof owner?.[key] === "string") slots.push({ owner, key, ...meta }); + }; + const data = (value, meta, depth = 0) => { + if (++nodes > 5e4 || depth > 48) throw new Error("input_structure_limit"); + if (!value || typeof value !== "object") return; + for (const k of Object.keys(value)) { + if (OPAQUE_FIELD.test(k)) continue; + if (typeof value[k] === "string") add(value, k, { ...meta, nameField: NAME_FIELD.test(k) ? k : null }); + else data(value[k], meta, depth + 1); + } + }; + const blocks = (value, meta, depth = 0) => { + if (++nodes > 5e4 || depth > 48) throw new Error("input_structure_limit"); + if (!Array.isArray(value)) { + data(value, meta, depth + 1); + return; + } + for (const p of value) { + if (!p || typeof p !== "object") continue; + if (["text", "input_text", "output_text", "summary_text", "reasoning_text"].includes(p.type) || !p.type && typeof p.text === "string") add(p, "text", meta); + else if (p.type === "thinking") add(p, "thinking", { ...meta, sealed: !!p.signature }); + else if (p.type === "tool_result") { + const m = { ...meta, source: "tool", tool: calls[p.tool_use_id] || "" }; + if (typeof p.content === "string") add(p, "content", m); + else blocks(p.content, m, depth + 1); + } else if (p.type === "tool_use") data(p.input, { ...meta, source: "call", tool: p.name || "" }, depth + 1); + else if (p.type === "resource") { + if (p.resource) add(p.resource, "text", meta); + } else if (p.functionCall) data(p.functionCall.args, { ...meta, source: "call", tool: p.functionCall.name || "" }, depth + 1); + else if (p.functionResponse) data(p.functionResponse.response, { ...meta, source: "tool", tool: p.functionResponse.name || "" }, depth + 1); + else if (p.type === "input_file" || p.type === "file") add(p, "filename", meta); + } + }; + let list; + if (protocol === "responses") list = Array.isArray(body.input) ? body.input : []; + else if (protocol === "gemini") list = Array.isArray(body.contents) ? body.contents : []; + else list = Array.isArray(body.messages) ? body.messages : []; + for (const m of list) { + if (!m || typeof m !== "object") continue; + if (m.type === "function_call" || m.type === "custom_tool_call") calls[m.call_id] = m.name || ""; + for (const c of m.tool_calls || []) if (c) calls[c.id] = c.function?.name || ""; + for (const p of Array.isArray(m.content) ? m.content : []) if (p?.type === "tool_use") calls[p.id] = p.name || ""; + } + if (protocol === "responses" && typeof body.input === "string") { + add(body, "input", { source: "user", index: 0 }); + records.push({ index: 0, role: "user", text: body.input }); + } + for (let index = 0; index < list.length; index++) { + const m = list[index]; + if (!m || typeof m !== "object") continue; + const source = ["system", "developer"].includes(m.role) ? "instruction" : m.role === "user" ? "user" : ["tool", "function"].includes(m.role) ? "tool" : "assistant"; + const meta = { source, index, tool: calls[m.tool_call_id] || (source === "tool" ? m.name || "" : "") }; + const before = slots.length; + if (typeof m.content === "string") add(m, "content", meta); + else blocks(m.content, meta); + blocks(m.parts, meta); + if (m.type === "function_call_output" || m.type === "custom_tool_call_output") { + const sm = { ...meta, source: "tool", tool: calls[m.call_id] || "" }; + if (typeof m.output === "string") add(m, "output", sm); + else data(m.output, sm); + } else if (m.type === "function_call") add(m, "arguments", { ...meta, source: "call", tool: m.name || "", json: true }); + else if (m.type === "custom_tool_call") add(m, "input", { ...meta, source: "call", tool: m.name || "" }); + else if (m.type === "reasoning") blocks(m.summary, { ...meta, source: "assistant" }); + for (const c of m.tool_calls || []) if (c?.function) add(c.function, "arguments", { ...meta, source: "call", tool: c.function.name || "", json: true }); + if (m.function_call) add(m.function_call, "arguments", { ...meta, source: "call", tool: m.function_call.name || "", json: true }); + const own = slots.slice(before).filter((s) => s.source === "user" && s.index === index).map((s) => s.owner[s.key]).join("\n"); + records.push({ index, role: m.role || m.type || "unknown", text: own }); + } + 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 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); + } + }; + schema(body.tools); + const user = records.filter((r) => r.role === "user" && r.text && !environmentText(r.text)).at(-1) || null; + return { slots, records, user }; +} +function publicContextSafe(view, allowed) { + if (!view.user) return false; + for (const r of view.records) { + if (r.index >= view.user.index || ["system", "developer"].includes(r.role)) continue; + if (r.role !== "user" || !environmentText(r.text)) return false; + } + for (const s of view.slots) { + if ((s.source === "instruction" || s.index < view.user.index) && [...allowed].some((n) => s.owner[s.key].includes(n))) return false; + if (["tool", "call"].includes(s.source) && !webTool(s.tool)) return false; + } + return true; +} +function safeInput(body, protocol) { + let nodes = 0; + const walk = (v, depth) => { + if (++nodes > 8e4 || depth > 64) throw new Error("input_structure_limit"); + if (typeof v === "number" && Number.isInteger(v) && !Number.isSafeInteger(v)) throw new Error("unsafe_numeric_value"); + if (!v || typeof v !== "object") return; + for (const k of Object.keys(v)) walk(v[k], depth + 1); + }; + walk(body, 0); +} + +// 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); +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; + if (typeof meta === "string") { + try { + meta = JSON.parse(meta); + } catch { + return null; + } + } + if (!meta || !["user", "agent_created_thread"].includes(meta.thread_source) || !validId(meta.thread_id) || !validId(meta.turn_id)) return null; + if (ctx.session && ctx.session !== meta.thread_id) return null; + return { session: meta.thread_id, turn: meta.turn_id }; +} +function sessionWorkspace(body, ctx) { + if (typeof ctx?.cwd === "string" && ctx.cwd.startsWith("/")) return ctx.cwd.replace(/\/$/, "") || "/"; + let workspace = ""; + for (const item of body?.input || body?.messages || []) { + if (!["user", "developer", "system"].includes(item?.role)) continue; + const texts = typeof item.content === "string" ? [item.content] : (Array.isArray(item.content) ? item.content : []).filter((p) => ["text", "input_text", "output_text"].includes(p?.type)).map((p) => p.text || ""); + for (const text of texts) { + for (const block of text.matchAll(/[\s\S]*?<\/environment_context>/g)) { + const cwd = /\s*([^<\n]+?)\s*<\/cwd>/.exec(block[0])?.[1]; + if (cwd?.startsWith("/")) workspace = cwd.replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&").replace(/\/$/, "") || "/"; + } + } + } + return workspace; +} +function readAuthorization(envelope, key, verifyContents = true) { + if (!validKey(key) || !envelope || typeof envelope.payload !== "string" || envelope.payload.length > 2 * 1024 * 1024 || !same(sign(key, PREFIX + envelope.payload), envelope.mac)) return null; + let record; + try { + record = JSON.parse(envelope.payload); + } catch { + return null; + } + record.names = envelope.names; + record.pattern = envelope.pattern; + if (record.v !== 1 || !validId(record.session) || record.session !== envelope.session || typeof record.workspace !== "string" || !record.workspace.startsWith("/") || !["active", "revoked"].includes(record.state) || !["all", "names"].includes(record.coverage) || !Number.isFinite(record.created) || record.created > Date.now() || !Array.isArray(record.names) || record.names.length > 32 || record.names.some((n) => typeof n !== "string" || n.length < 2 || n.length > 120) || record.coverage === "names" && record.state === "active" && !record.names.length || record.coverage === "all" && record.names.length) return null; + if (record.nameCount !== record.names.length || typeof record.pattern !== "string") return null; + if (verifyContents && digest(JSON.stringify({ names: record.names, pattern: record.pattern })) !== record.contentsHash) return null; + return record; +} +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 }; + 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" }; + const record = readAuthorization(matching[0], ctx.options?.authKey, false); + if (!record) return { record: null, managed: true, reason: "authorization_invalid" }; + if (record.state !== "active") return { record: null, managed: true, reason: "session_revoked" }; + if (sessionWorkspace(body, ctx) !== record.workspace) return { record: null, managed: true, reason: "task_identity_mismatch" }; + return { record, managed: true, reason: record.coverage === "all" ? "session_all_active" : "session_names_active" }; +} + +// src/company-guard.js +var ESCAPED_STRING = /"[^"\\]*(?:\\.[^"\\]*)+"/g; +var TOKEN = /\[\[NERO_ORG_[a-f0-9]{24}\]\]/g; +var NOTE = "Company identifiers of the form [[NERO_ORG_\u2026]] are opaque local labels. Copy them exactly in text and tool arguments; do not infer or expand them."; +var fail = (ctx, code) => { + ctx.reject(400, "NERO \u516C\u53F8\u540D\u4FDD\u62A4\uFF1A" + code); +}; +function addNote(body, protocol) { + var _a; + if (protocol === "responses") body.instructions = (body.instructions ? body.instructions + "\n\n" : "") + NOTE; + else if (protocol === "anthropic") { + if (Array.isArray(body.system)) body.system.push({ type: "text", text: NOTE }); + else body.system = (body.system ? body.system + "\n\n" : "") + NOTE; + } else if (protocol === "gemini") { + body.systemInstruction || (body.systemInstruction = { parts: [] }); + (_a = body.systemInstruction).parts || (_a.parts = []); + body.systemInstruction.parts.push({ text: NOTE }); + } else if (Array.isArray(body.messages)) body.messages.unshift({ role: "system", content: NOTE }); +} +function prepareRequest(body, ctx) { + var _a; + const budget = () => { + if (ctx.signal?.aborted) throw new Error("\u672C\u5730\u5904\u7406\u5DF2\u53D6\u6D88"); + }; + ctx.state.guard = { reverse: /* @__PURE__ */ Object.create(null), buffers: /* @__PURE__ */ Object.create(null), ready: false, failed: false }; + try { + const o = ctx.options || {}; + if (!validKey(o.authKey)) { + fail(ctx, "\u5C1A\u672A\u914D\u7F6E\u672C\u5730\u4FDD\u62A4\u5BC6\u94A5"); + return; + } + let proof = readProof(body[PROOF], body, o.authKey, ctx); + delete body[PROOF]; + const managed = resolveAuthorization(body, ctx); + if (managed.managed) proof = managed.record ? { mode: "original", scope: "session_task", coverage: managed.record.coverage, names: managed.record.names, pattern: managed.record.pattern } : null; + if (!["responses", "chat", "anthropic", "gemini"].includes(ctx.protocol)) throw new Error("\u4E0D\u652F\u6301\u7684\u8BF7\u6C42\u534F\u8BAE"); + safeInput(body, ctx.protocol); + const view = inspectRequest(body, ctx.protocol); + const metrics = ctx.state.guard.metrics = { matchedNames: 0, replacedNames: 0, replacements: 0, allowedOccurrences: 0, scopes: {} }; + const matched = /* @__PURE__ */ new Set(); + const scopeOf = (s) => s.source === "user" ? s.index === view.user?.index ? "user" : "history" : { tool: "tool_results", call: "tool_arguments", schema: "tool_schema", instruction: "instructions" }[s.source] || "history"; + let currentScope; + for (const slot of view.slots) { + const key = scopeOf(slot); + (_a = metrics.scopes)[key] || (_a[key] = { checkedTexts: 0, replacements: 0 }); + metrics.scopes[key].checkedTexts++; + } + let size = 0; + for (const s of view.slots) { + size += s.owner[s.key].length; + if (size > 4 * 1024 * 1024) throw new Error("\u6587\u5B57\u8D85\u8FC7 4 MiB\uFF0C\u8BF7\u7F29\u5C0F\u672C\u6B21\u8F93\u5165"); + } + if (proof?.coverage === "all") { + metrics.authorization = "original"; + metrics.authorizationReason = managed.reason; + metrics.authorizationCoverage = "all"; + ctx.state.guard.authorization = "original"; + ctx.state.guard.ready = true; + return body; + } + const requested = managed.managed ? new Set(proof?.names || []) : expandAllowed(proof?.names || [], o); + if (proof?.mode === "public_lookup" && !publicContextSafe(view, requested)) proof = null; + const allowed = proof ? requested : /* @__PURE__ */ new Set(); + ctx.state.guard.authorization = proof ? proof.mode : "masked"; + metrics.authorization = ctx.state.guard.authorization; + metrics.authorizationReason = managed.managed ? managed.reason : proof ? proof.scope === "session_task" ? "session_task_active" : "turn_grant_active" : ctx.grantStatus || "no_matching_grant"; + metrics.authorizationCoverage = proof ? "names" : "none"; + const names = new Set(configuredNames(o)); + const aliases = taskAliases(view.slots); + for (const n of aliases.names) names.add(n); + metrics.taskAliases = aliases.names.length; + metrics.aliasConflicts = aliases.conflicts; + metrics.aliasLimitReached = aliases.limited; + if (!proof?.pattern) for (const n of allowed) names.add(n); + for (const s of view.slots) { + budget(); + const text = s.owner[s.key]; + for (const n of detectNames(text)) names.add(n); + if (s.nameField) { + const name = nameFieldValue(text, s.nameField); + if (name) names.add(name); + } + if (s.source === "user") for (const n of directive(text)?.names || []) names.add(n); + if (text.includes("\\u")) for (const q of text.matchAll(ESCAPED_STRING)) { + let t; + try { + t = JSON.parse(q[0]); + } catch { + continue; + } + for (const n of detectNames(t)) names.add(n); + } + } + const candidates = [...names].filter((n) => typeof n === "string" && n.length >= 2).sort((a, b) => b.length - a.length); + const pattern = candidates.length ? namePattern(candidates) : ""; + const matcher = candidates.length ? new RegExp("\\[\\[NERO_ORG_[a-f0-9]{24}\\]\\]|(?:" + pattern + ")", "gi") : null; + const prefixMatcher = candidates.length ? new RegExp(namePattern([...new Set(candidates.map((n) => n.slice(0, 2)))]), "i") : null; + const literalMatchers = !ctx.sign ? candidates.map((n, rank) => ({ re: new RegExp(escapeRE(n), "gi"), rank })) : null; + const opaque = new RegExp(TOKEN.source, "gi"); + const approvedMatcher = proof?.pattern ? new RegExp(proof.pattern, "gi") : null; + const id = identity(body); + const scope = [ctx.session, id?.thread].filter(Boolean).join(":") || "request:" + Date.now() + ":" + Math.random(); + const signName = ctx.sign ? (name) => ctx.sign(o.authKey, scope + "\0" + name) : scopedSigner(o.authKey, scope + "\0"); + const forward = /* @__PURE__ */ Object.create(null), reverse = ctx.state.guard.reverse; + const allowedFold = new Set([...allowed].map((n) => n.toLowerCase())); + const tokenFor = (name) => { + if (forward[name]) return forward[name]; + const token = TOKEN_PREFIX + signName(name).slice(0, 24) + "]]"; + if (reverse[token] && reverse[token] !== name) throw new Error("\u540D\u79F0\u4EE3\u53F7\u51B2\u7A81"); + forward[name] = token; + reverse[token] = name; + return token; + }; + const replaceName = (name, offset, original, allow) => { + if (/^\[\[NERO_ORG_[a-f0-9]{24}\]\]$/.test(name)) return name; + if (/[A-Za-z0-9_]/.test(name[0]) && offset > 0 && /[A-Za-z0-9_]/.test(original[offset - 1])) return name; + if (/[A-Za-z0-9_]/.test(name.at(-1)) && /[A-Za-z0-9_]/.test(original[offset + name.length] || "")) return name; + matched.add(name); + metrics.matchedNames = matched.size; + if (allow && allowedFold.has(name.toLowerCase())) { + metrics.allowedOccurrences++; + return name; + } + const token = tokenFor(name); + metrics.replacements++; + metrics.scopes[currentScope].replacements++; + return token; + }; + const sub = (text, allow) => { + if (!matcher && !approvedMatcher) return text; + if (!literalMatchers && !approvedMatcher) return text.replace(matcher, (n, i, s) => replaceName(n, i, s, allow)); + const hits = []; + let m; + opaque.lastIndex = 0; + while (m = opaque.exec(text)) hits.push({ at: m.index, name: m[0], rank: -1 }); + if (approvedMatcher) { + approvedMatcher.lastIndex = 0; + while (m = approvedMatcher.exec(text)) hits.push({ at: m.index, name: m[0], rank: 0 }); + } + if (!literalMatchers && matcher) { + matcher.lastIndex = 0; + while (m = matcher.exec(text)) hits.push({ at: m.index, name: m[0], rank: 1 }); + } + for (const item of literalMatchers || []) { + item.re.lastIndex = 0; + while (m = item.re.exec(text)) { + hits.push({ at: m.index, name: m[0], rank: item.rank }); + item.re.lastIndex = m.index + 1; + } + } + hits.sort((a, b) => a.at - b.at || (approvedMatcher ? b.name.length - a.name.length : 0) || a.rank - b.rank); + const pieces = []; + let after = 0; + for (const hit of hits) { + if (hit.at < after) continue; + pieces.push(text.slice(after, hit.at), replaceName(hit.name, hit.at, text, allow)); + after = hit.at + hit.name.length; + } + return after ? pieces.join("") + text.slice(after) : text; + }; + for (const s of view.slots) { + budget(); + currentScope = scopeOf(s); + const allow = !!proof && (proof.mode === "original" || s.source === "user" && s.index === view.user?.index || ["tool", "call"].includes(s.source) && webTool(s.tool)); + let text = s.owner[s.key]; + if (!matcher && !approvedMatcher || !approvedMatcher && ctx.sign && !text.includes("\\u") && !prefixMatcher.test(text)) continue; + if (text.includes("\\")) text = text.replace(ESCAPED_STRING, (raw) => { + let value; + try { + value = JSON.parse(raw); + } catch { + return raw; + } + const next = sub(value, allow); + return next === value ? raw : JSON.stringify(next); + }); + text = sub(text, allow); + if (s.sealed && text !== s.owner[s.key]) throw new Error("\u7B7E\u540D\u601D\u8003\u5185\u5BB9\u4E0D\u80FD\u5B89\u5168\u6539\u5199\uFF0C\u8BF7\u4F7F\u7528\u5E72\u51C0\u7684\u65B0\u4E0A\u4E0B\u6587"); + s.owner[s.key] = text; + } + metrics.replacedNames = Object.keys(reverse).length; + if (metrics.replacedNames) addNote(body, ctx.protocol); + ctx.state.guard.ready = true; + return body; + } catch (e) { + fail(ctx, e instanceof Error ? e.message : "\u672C\u5730\u68C0\u67E5\u5931\u8D25"); + } +} +function restore(text, state, json = false) { + if (typeof text !== "string") return text; + return text.replace(TOKEN, (token) => { + const name = state.reverse[token]; + if (name !== void 0 && state.restoredTokens) state.restoredTokens[token] = true; + return name === void 0 ? token : json ? JSON.stringify(name).slice(1, -1) : name; + }); +} +function whole(value, state, depth = 0, data = false) { + if (!value || typeof value !== "object" || depth > 64) return; + for (const key of Object.keys(value)) { + if (!data && /^(?:id|type|role|name|model|call_id|tool_call_id|tool_use_id|signature|encrypted_content)$/.test(key)) continue; + if (typeof value[key] === "string") value[key] = restore(value[key], state, key === "arguments"); + else whole(value[key], state, depth + 1, data || key === "args" || key === "input" && value.type === "tool_use"); + } +} +function chunk(text, state, key, json = false, final = false) { + if (typeof text !== "string") return text; + let value = (state.buffers[key] || "") + text; + state.buffers[key] = ""; + if (!final) { + let cut = value.lastIndexOf(TOKEN_PREFIX); + if (cut >= 0) { + const tail = value.slice(cut); + if (tail.length < TOKEN_PREFIX.length + 26 && /^\[\[NERO_ORG_[a-f0-9]*\]?$/.test(tail)) { + state.buffers[key] = tail; + value = value.slice(0, cut); + } + } + if (!state.buffers[key]) for (let n = Math.min(value.length, TOKEN_PREFIX.length - 1); n > 0; n--) { + if (value.endsWith(TOKEN_PREFIX.slice(0, n))) { + state.buffers[key] = value.slice(-n); + value = value.slice(0, -n); + break; + } + } + } + return restore(value, state, json); +} +function clear(state, prefix) { + for (const key of Object.keys(state.buffers)) if (key.startsWith(prefix)) delete state.buffers[key]; +} +function pending(state, prefix = "") { + return Object.keys(state.buffers).some((k) => k.startsWith(prefix) && state.buffers[k]); +} +function streamError(ctx, state) { + state.failed = true; + receiptEvent(state, "reply_processed", false, "restoration_incomplete"); + const message = "NERO \u516C\u53F8\u540D\u8FD8\u539F\u672A\u5B8C\u6210\uFF0C\u5DF2\u505C\u6B62\u6B64\u56DE\u590D\uFF0C\u8BF7\u91CD\u8BD5\u3002"; + if (ctx.protocol === "responses") return { type: "error", code: "nero_restore_incomplete", message, param: null }; + if (ctx.protocol === "anthropic") return { type: "error", error: { type: "api_error", message } }; + return { error: { type: "nero_restore_incomplete", message } }; +} +function onEvent(ev, ctx) { + const state = ctx.state.guard; + if (!state?.ready) return; + if (!Object.keys(state.reverse).length) { + if (terminalEvent(ev, ctx.protocol)) receiptEvent(state, "reply_processed", terminalOK(ev), terminalOK(ev) ? "processed" : "upstream_incomplete", terminalLabel(ev, ctx.protocol)); + return; + } + if (state.failed) return null; + try { + if (ctx.protocol === "responses") { + const p = "r:" + (ev.output_index ?? 0) + ":"; + const key = p + (ev.content_index ?? ev.summary_index ?? 0) + ":" + (ev.type || "").replace(/\.(delta|done)$/, ""); + if (typeof ev.delta === "string" && /\.delta$/.test(ev.type)) ev.delta = chunk(ev.delta, state, key, ev.type === "response.function_call_arguments.delta"); + else { + whole(ev, state); + if (/\.(done)$/.test(ev.type)) { + if (ev.type === "response.output_item.done") clear(state, p); + else delete state.buffers[key]; + } + if (["response.completed", "response.incomplete", "response.failed"].includes(ev.type)) { + if (Array.isArray(ev.response?.output) && ev.response.output.length) clear(state, "r:"); + if (pending(state)) return streamError(ctx, state); + } + } + } else if (ctx.protocol === "anthropic") { + const p = "a:" + (ev.index ?? 0) + ":"; + if (ev.type === "content_block_delta") { + for (const key of ["text", "thinking", "partial_json"]) if (typeof ev.delta?.[key] === "string") ev.delta[key] = chunk(ev.delta[key], state, p + key, key === "partial_json"); + } else { + whole(ev, state); + if (ev.type === "content_block_stop" && pending(state, p)) return streamError(ctx, state); + if (ev.type === "message_stop" && pending(state)) return streamError(ctx, state); + } + } else if (Array.isArray(ev.choices)) { + for (const c of ev.choices) { + const p = "c:" + (c.index ?? 0) + ":", end = c.finish_reason != null; + c.delta || (c.delta = {}); + for (const key of ["content", "reasoning", "reasoning_content", "refusal"]) if (typeof c.delta[key] === "string" || end && state.buffers[p + key]) c.delta[key] = chunk(c.delta[key] || "", state, p + key, false, end); + for (const t of c.delta.tool_calls || []) if (t.function) t.function.arguments = chunk(t.function.arguments || "", state, p + "tool:" + (t.index ?? 0), true, end); + if (c.delta.function_call) c.delta.function_call.arguments = chunk(c.delta.function_call.arguments || "", state, p + "function", true, end); + if (end && pending(state, p)) return streamError(ctx, state); + } + } else if (Array.isArray(ev.candidates)) { + for (let ci = 0; ci < ev.candidates.length; ci++) { + const c = ev.candidates[ci], parts = c.content?.parts || []; + for (let pi = 0; pi < parts.length; pi++) { + const part = parts[pi], key = "g:" + (c.index ?? ci) + ":" + pi + ":" + !!part.thought; + if (typeof part.text === "string") part.text = chunk(part.text, state, key, false, !!c.finishReason); + if (part.functionCall) whole(part.functionCall.args, state, 0, true); + } + if (c.finishReason && pending(state, "g:" + (c.index ?? ci) + ":")) return streamError(ctx, state); + } + } else whole(ev, state); + if (terminalEvent(ev, ctx.protocol)) receiptEvent(state, "reply_processed", terminalOK(ev) && !state.failed && !pending(state), !terminalOK(ev) ? "upstream_incomplete" : state.failed || pending(state) ? "restoration_incomplete" : "processed", terminalLabel(ev, ctx.protocol)); + return ev; + } catch { + return streamError(ctx, state); + } +} +function onResponse(body, ctx) { + const state = ctx.state.guard; + if (!state?.ready) return; + whole(body, state); + receiptEvent(state, "reply_processed", !state.failed && !pending(state)); + return body; +} +var PREPARED = "__nero_company_prepared"; +function onRequest(body, ctx) { + const envelope = body[PREPARED]; + delete body[PREPARED]; + delete body[PROOF]; + const key = ctx.options?.authKey; + try { + if (!validKey(key)) throw new Error("\u672C\u5730\u4FDD\u62A4\u5BC6\u94A5\u4E0D\u53EF\u7528"); + if (envelope === void 0 || envelope === null) { + let metadata = body?.client_metadata?.["x-codex-turn-metadata"] || body?.client_metadata; + if (typeof metadata === "string") { + try { + metadata = JSON.parse(metadata); + } catch { + metadata = null; + } + } + const hint = /^[A-Za-z0-9][A-Za-z0-9_-]{1,127}$/.test(metadata?.thread_id || "") ? metadata.thread_id : void 0; + const result = prepareRequest(body, { ...ctx, session: ctx.session || hint }); + const state = ctx.state.guard; + if (state?.ready) { + state.fallback = true; + state.fallbackIdentity = identity(body); + state.restoredTokens = /* @__PURE__ */ Object.create(null); + receiptEvent(state, "request_checked", true); + } + return result; + } + if (!envelope || typeof envelope.payload !== "string") throw new Error("\u672C\u5730\u8131\u654F\u5904\u7406\u672A\u5B8C\u6210\uFF1A\u7F3A\u5C11\u5904\u7406\u7ED3\u679C"); + if (!same(sign(key, envelope.payload), envelope.mac)) throw new Error("\u672C\u5730\u8131\u654F\u5904\u7406\u7ED3\u679C\u7B7E\u540D\u4E0D\u5339\u914D"); + const p = JSON.parse(envelope.payload), now = Date.now(); + if (p.v !== 1 || p.protocol !== ctx.protocol || p.expires < now || p.expires > now + 3e4 || p.thread !== (identity(body)?.thread || "")) throw new Error("\u672C\u5730\u8131\u654F\u7ED3\u679C\u5DF2\u5931\u6548"); + if (p.error) throw new Error(p.error); + const reverse = /* @__PURE__ */ Object.create(null); + for (const [token, name] of Object.entries(p.reverse || {})) { + if (!/^\[\[NERO_ORG_[a-f0-9]{24}\]\]$/.test(token) || !validName(name)) throw new Error("\u540D\u79F0\u8FD8\u539F\u8BB0\u5F55\u65E0\u6548"); + reverse[token] = name; + } + ctx.state.guard = { reverse, buffers: /* @__PURE__ */ Object.create(null), ready: true, failed: false, receiptId: p.receiptId, restoredTokens: /* @__PURE__ */ Object.create(null) }; + if (p.schema?.length) { + const slots = inspectRequest({ tools: body.tools }, ctx.protocol).slots; + for (const [i, text] of p.schema) { + if (!slots[i] || typeof text !== "string") throw new Error("\u5DE5\u5177\u8BF4\u660E\u5904\u7406\u7ED3\u679C\u65E0\u6548"); + slots[i].owner[slots[i].key] = text; + } + } + receiptEvent(ctx.state.guard, "request_checked", true); + return body; + } catch (e) { + fail(ctx, e.message || "\u672C\u5730\u5904\u7406\u5931\u8D25"); + } +} +function terminalOK(ev) { + return !["error", "response.failed", "response.incomplete"].includes(ev.type); +} +function terminalLabel(ev, protocol) { + if (protocol === "chat") return ev.choices?.length && ev.choices.every((c) => ["stop", "tool_calls", "function_call"].includes(c.finish_reason)) ? "chat.completed" : void 0; + if (protocol === "gemini") return ev.candidates?.length && ev.candidates.every((c) => c.finishReason === "STOP") ? "gemini.completed" : void 0; + return ev.type; +} +function terminalEvent(ev, protocol) { + if (protocol === "responses") return ["response.completed", "response.failed", "response.incomplete"].includes(ev.type); + if (protocol === "anthropic") return ["message_stop", "error"].includes(ev.type); + if (protocol === "chat") return ev.choices?.length && ev.choices.every((c) => c.finish_reason != null); + return ev.candidates?.length && ev.candidates.every((c) => c.finishReason); +} +function receiptEvent(state, phase, ok, reason, eventType) { + if (!state?.fallback && !/^[a-f0-9-]{36}$/.test(state?.receiptId || "")) return; + if (phase === "reply_processed" && state.receiptDone) return; + if (phase === "reply_processed") state.receiptDone = true; + const replyReason = phase === "reply_processed" ? reason || (ok ? "processed" : "restoration_incomplete") : void 0; + const terminalType = ["response.completed", "response.failed", "response.incomplete", "message_stop", "chat.completed", "gemini.completed", "error"].includes(eventType) ? eventType : void 0; + if (state.fallback) { + const metrics = state.metrics || {}; + try { + console.info("NERO_COMPANY_GUARD_FALLBACK " + JSON.stringify({ phase, ok, thread: state.fallbackIdentity?.thread || null, turn: state.fallbackIdentity?.turn || null, cause: "prepared_result_unavailable", authorization: metrics.authorization || "masked", authorizationCoverage: metrics.authorizationCoverage || "none", matchedNames: metrics.matchedNames || 0, replacements: metrics.replacements || 0, reason: replyReason, eventType: terminalType, restoredNames: Object.keys(state.restoredTokens).length })); + } catch { + } + return; + } + try { + console.info("NERO_COMPANY_GUARD_RECEIPT " + JSON.stringify({ id: state.receiptId, phase, ok, reason: replyReason, eventType: terminalType, restoredNames: Object.keys(state.restoredTokens || {}).length })); + } catch { + } +} +export { + PREPARED, + onEvent, + onRequest, + onResponse, + prepareRequest +}; diff --git a/packages/company-guard/package-lock.json b/packages/company-guard/package-lock.json new file mode 100644 index 0000000..54efe6a --- /dev/null +++ b/packages/company-guard/package-lock.json @@ -0,0 +1,507 @@ +{ + "name": "@magpie-community/middleware-company-guard", + "version": "0.4.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@magpie-community/middleware-company-guard", + "version": "0.4.1", + "license": "MIT", + "devDependencies": { + "esbuild": "0.25.12" + }, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20", + "magpie": ">=0.1.3841" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + } + } +} diff --git a/packages/company-guard/package.json b/packages/company-guard/package.json new file mode 100644 index 0000000..83511ef --- /dev/null +++ b/packages/company-guard/package.json @@ -0,0 +1,71 @@ +{ + "name": "@magpie-community/middleware-company-guard", + "version": "0.4.3", + "type": "module", + "license": "MIT", + "description": "Local company-name masking, reversible replies and session approvals for Magpie", + "files": [ + "dist", + "src", + "vendor", + "company-guard.hooks.mjs", + "README.md", + "LICENSE", + "THIRD_PARTY_NOTICES.md", + "receipt-report.mjs", + "page", + "receipt-page.mjs" + ], + "magpie": { + "middleware": "./dist/company-guard.middleware.js", + "hooks": "./company-guard.hooks.mjs", + "options": { + "companies": [], + "gatewayTimeoutMs": 4000 + }, + "page": { + "title": "Company name protection", + "titles": { + "zh": "公司名称保护", + "zh-TW": "公司名稱保護" + }, + "file": "page/index-0.3.3.html", + "service": { + "port": 3469, + "option": "receiptPort" + } + } + }, + "main": "./receipt-page.mjs", + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/company-guard" + }, + "homepage": "https://github.com/cyanask/magpie-company-guard#readme", + "bugs": { + "url": "https://github.com/cyanask/magpie-company-guard/issues" + }, + "keywords": [ + "magpie-plugin", + "magpie", + "middleware", + "privacy", + "data-masking", + "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" + }, + "devDependencies": { + "esbuild": "0.25.12" + }, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20", + "magpie": ">=0.1.3841" + } +} diff --git a/packages/company-guard/page/app.js b/packages/company-guard/page/app.js new file mode 100644 index 0000000..90defb7 --- /dev/null +++ b/packages/company-guard/page/app.js @@ -0,0 +1,96 @@ +const $ = id => document.getElementById(id); +const short = value => value ? value.slice(0,8) : '未知'; +const scopeNames = {user:'用户文字',history:'历史',instructions:'指令',tool_results:'工具结果',tool_arguments:'工具参数',tool_schema:'工具说明'}; +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; +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() { + const selected=$('task').value,tasks=new Map(),rows=agentRows(); + for(const r of rows){const id=r.task || r.thread || '';if(id)tasks.set(id,(tasks.get(id)||0)+1);} + $('task').replaceChildren(new Option('全部任务','')); + for(const [id,n] of tasks){const title=rows.find(r=>(r.task || r.thread)===id)?.taskTitle,option=new Option(`${title || '会话 '+short(id)} · ${short(id)} · ${n} 条`,id);option.title=id;$('task').add(option);} + if(tasks.has(selected))$('task').value=selected; +} +function updateAgents() { + const selected=$('agent').value,previousLabel=$('agent').selectedOptions[0]?.textContent; + const choices=new Map((report?.agentOptions || []).map(a=>[a.id,a.label])); + for(const r of report?.rows || [])for(const id of agentsOf(r))if(!choices.has(id))choices.set(id,r.agentLabel || (id==='unknown'?'来源未记录':id)); + // Keep an explicitly selected agent when its requests leave the recent window. + if(selected&&!choices.has(selected))choices.set(selected,previousLabel || selected); + $('agent').replaceChildren(new Option('全部智能体','')); + for(const [id,name] of choices)$('agent').add(new Option(name,id)); + if(choices.has(selected))$('agent').value=selected; + updateTasks(); +} +function updateNotice() { + if(!report || $('notice').classList.contains('error'))return; + const tasks=new Set(agentRows().map(r=>r.task || r.thread).filter(Boolean)); + const mode=expanded?'查看明细时暂停刷新':$('auto').checked?'每10秒刷新':'自动刷新已暂停'; + $('notice').textContent=`更新于 ${new Date(report.readAt).toLocaleTimeString('zh-CN',{timeZone:'Asia/Shanghai',hour12:false})} · ${tasks.size} 个任务 · ${mode}`; +} +async function api(route,params={}) { + const url=new URL(route,base);for(const [k,v] of Object.entries(params))url.searchParams.set(k,v); + const response=await fetch(url,{headers:{'X-Receipt-Key':readKey},cache:'no-store',signal:AbortSignal.timeout(8000)}); + if(!response.ok)throw new Error('read_failed');return response.json(); +} +function closeDetail() { + clearTimeout(expiryTimer);document.querySelector('.detail-row')?.remove(); + const button=document.querySelector('button[aria-expanded="true"]');if(button){button.textContent='查看';button.setAttribute('aria-expanded','false');}expanded=null;updateNotice(); +} +async function showDetail(r,tr,button) { + if(expanded===r.id){closeDetail();return;}closeDetail();expanded=r.id;updateNotice(); + button.textContent='收起';button.setAttribute('aria-expanded','true'); + const row=el('tr',undefined,'detail-row'),cell=el('td'),content=el('div',undefined,'detail-pairs'),meta=el('div',undefined,'detail-meta');cell.colSpan=7;row.id='detail-'+r.id;button.setAttribute('aria-controls',row.id); + 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} 段`)); + 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 { + const d=await api('details',{id:r.id});if(expanded!==r.id || !row.isConnected)return; + content.replaceChildren(); + if(!d.available){content.append(el('p','未保留明细或已过期。新请求的原名称与代号可查看 30 分钟,重启后清空。','detail-message'));return;} + if(!d.pairs.length){content.append(el('p','本次没有名称替换。','detail-message'));return;} + const table=el('table',undefined,'pairs'),head=el('thead'),hr=el('tr');hr.append(el('th','替换前'),el('th','替换后的代号'));head.append(hr);table.append(head);const body=el('tbody'); + for(const pair of d.pairs){const line=el('tr');line.append(el('td',pair.original),el('td',pair.token,'mono'));body.append(line);}table.append(body);content.append(table); + expiryTimer=setTimeout(()=>{if(expanded===r.id)content.replaceChildren(el('p','明细已过期,回执数量仍可核对。','detail-message'));},Math.max(0,d.expiresAt-Date.now())); + } catch {if(expanded===r.id)content.replaceChildren(el('p','明细服务暂时不可用,请稍后刷新重试。','detail-message'));} +} +function render() { + closeDetail();const selected=$('task').value; + const rows=agentRows().filter(r=>!selected || (r.task || r.thread || '')===selected); + $('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);} + const diagnosticCount=report?.diagnostics?.observed || 0;$('diagnostics').hidden=!diagnosticCount; + $('diagnostics').textContent=diagnosticCount?`当日跨任务记录到 ${diagnosticCount} 次插件处理超时或异常;日志没有请求编号,无法归到某一条回执。`:''; + $('rows').replaceChildren(); + for(const r of rows){ + const tr=el('tr'),d=new Date(r.at),time=el('td',Number.isNaN(d.getTime())?'未知':d.toLocaleTimeString('zh-CN',{timeZone:'Asia/Shanghai',hour12:false}));time.title=r.at || '';tr.append(time); + tr.append(el('td',r.agentLabel || '来源未记录','agent-source')); + const ids=el('td'),task=el('span',r.taskTitle || '会话 '+short(r.task || r.thread),'task-name');task.title=r.taskTitle || r.task || r.thread || '未知';ids.append(task,el('span',short(r.task || r.thread)+' / '+short(r.id),'mono muted'));ids.title=(r.task || r.thread || '未知')+' / '+r.id;tr.append(ids); + tr.append(el('td',count(r.replacedNames)+' / '+count(r.replacements),'number'),el('td',count(r.restoredNames),'number'),el('td',r.processingMs==null?'—':r.processingMs+' ms','number')); + const cell=el('td'),button=el('button','查看','view');button.type='button';button.setAttribute('aria-expanded','false');button.addEventListener('click',()=>showDetail(r,tr,button));cell.append(button);tr.append(cell);$('rows').append(tr); + } + $('empty').hidden=rows.length!==0; +} +async function refresh() { + if(busy)return;const requestedDay=$('date').value;busy=true;$('refresh').disabled=true;$('notice').className='';$('notice').textContent='读取中…'; + try { + const next=await api('receipts',{date:requestedDay});if(requestedDay!==$('date').value)return;report=next;updateAgents(); + render();updateNotice(); + } catch {$('notice').className='error';$('notice').textContent=report?'读取失败,下方为上次结果;请刷新重试。':'读取失败,请刷新重试。';} + finally {busy=false;$('refresh').disabled=false;if(requestedDay!==$('date').value)refresh();} +} +$('date').value=new Date().toISOString().slice(0,10);$('filters').addEventListener('submit',e=>e.preventDefault());$('date').addEventListener('change',()=>{refresh();}); +$('agent').addEventListener('change',()=>{updateTasks();render();if(!busy)updateNotice();}); +$('task').addEventListener('change',render);$('refresh').addEventListener('click',refresh); +$('auto').addEventListener('change',()=>{if($('auto').checked&&pageVisible&&!expanded)refresh();else if(!busy)updateNotice();}); +async function start(){try{await magpie.ready;const options=await magpie.options.get();readKey=options.receiptReadKey; +if(!/^[a-f0-9]{64}$/.test(readKey||""))throw new Error("not_configured");base=new URL(".",location.href).href;pageVisible=magpie.visible; +magpie.onVisibility?.(value=>{pageVisible=value;if(!value)closeDetail();else if($('auto').checked&&!expanded)refresh();});await refresh();setInterval(()=>{if($("auto").checked&&pageVisible&&!expanded)refresh();},10000); +}catch{$("notice").className="error";$("notice").textContent="未连接回执服务,请重新打开此页。";$("refresh").disabled=true;}} +start(); diff --git a/packages/company-guard/page/authorization.html b/packages/company-guard/page/authorization.html new file mode 100644 index 0000000..3744e80 --- /dev/null +++ b/packages/company-guard/page/authorization.html @@ -0,0 +1,23 @@ + + +会话授权 +
+
+

会话授权

默认脱敏,仅对你确认的会话和范围放行原名。

+

正在读取授权…

+
申请放行

在目标会话单独发送 申请本会话原名放行,再到这里确认范围。

使用说明

待确认申请保留24小时,申请本身不会启用授权或暂停任务。任务名称只用于识别,授权以会话编号和工作目录为准。其他会话、分叉和子任务不会自动取得授权。

+ + +

已启用授权

+

授权持续到你主动恢复脱敏。恢复仅影响后续请求,已发送原文不能撤回;图片不做文字识别。

+
+ +
diff --git a/packages/company-guard/page/authorization.js b/packages/company-guard/page/authorization.js new file mode 100644 index 0000000..5338757 --- /dev/null +++ b/packages/company-guard/page/authorization.js @@ -0,0 +1,102 @@ +const $=id=>document.getElementById(id); +const short=value=>value?value.slice(0,8):"未知"; +let base,readKey,authorizationKey,authorizationNonce,editingRequest,authorizationBusy=false,revocationOpen=false; +let activeAuthorizations=[]; +function el(tag,text,cls) {const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;} +async function api(route,params={},timeout=8000) { + const url=new URL(route,base);for(const [k,v] of Object.entries(params))url.searchParams.set(k,v); + const response=await fetch(url,{headers:{'X-Receipt-Key':readKey},cache:'no-store',signal:AbortSignal.timeout(timeout)}); + if(!response.ok)throw new Error('read_failed');return response.json(); +} + +const authorizationErrors={invalid_names:'请填写有效公司名称,每行一个,最多32个;本次设置尚未改变。',request_expired:'申请已过期,请在目标会话重新提出申请。',operation_expired:'保存已过期,请刷新后重新确认。',operation_busy:'另一个窗口正在保存授权,请稍后刷新重试。',invalid_registry:'授权配置校验未通过,请保留当前设置并联系维护。',authorization_too_large:'名单或会话数量超过容量,请缩小范围。',authorization_unavailable:'本机授权服务暂不可用,请刷新重试。',authorization_not_found:'这份授权已变化,请刷新查看。'}; +function authorizationNotice(text,error=false){$('authorization-notice').textContent=text;$('authorization-notice').className=error?'error':'detail-message';} +async function authorizationPost(route,body){ + const response=await fetch(new URL('authorization/'+route,base),{method:'POST',headers:{'X-Receipt-Key':readKey,'X-Authorization-Key':authorizationKey,'X-Authorization-Nonce':authorizationNonce,'Content-Type':'application/json'},body:JSON.stringify(body),cache:'no-store',signal:AbortSignal.timeout(10000)}); + const value=await response.json();if(!response.ok)throw new Error(authorizationErrors[value.error]||'未能保存授权,请刷新重试。');return value; +} +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); + 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; + if(at){const date=new Date(at),time=el('time',(kind==='pending'?'申请于 ':'启用于 ')+date.toLocaleString('zh-CN',{timeZone:'Asia/Shanghai',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',hour12:false}),'authorization-time');time.dateTime=date.toISOString();time.title=date.toLocaleString('zh-CN',{timeZone:'Asia/Shanghai',hour12:false});scope.append(time);} + const button=el('button',kind==='pending'?'设置放行范围':'恢复脱敏');button.type='button';button.setAttribute('aria-label',(kind==='pending'?'设置放行范围 ':'恢复脱敏 ')+row.session); + button.addEventListener('click',event=>{if(!event.isTrusted||authorizationBusy)return;if(kind==='pending')openAuthorization(row);else openRevocation(row,card);});card.append(text,scope,button);return card; +} +async function refreshAuthorizations(){ + if(authorizationBusy)return; + revocationOpen=false; + try{ + const state=await api('authorization');authorizationNonce=state.nonce; + const options=await magpie.options.get(),entries=options.sessionAuthorizations||[]; + const verified=await authorizationPost('state',{entries}); + const managed=new Set(entries.map(e=>e.session)); + const pending=state.pending.filter(r=>!verified.active.some(a=>a.session===r.session&&a.requestId===r.id)); + $('authorization-pending').replaceChildren(...pending.map(r=>sessionCard(r,'pending'))); + $('authorization-pending-section').hidden=!pending.length; + const active=[...verified.active,...state.legacy.filter(r=>!managed.has(r.session))]; + activeAuthorizations=active; + $('authorization-active').replaceChildren(...active.map(r=>sessionCard(r,'active'))); + if(!active.length)$('authorization-active').append(el('p','当前没有会话原名授权,默认脱敏。','detail-message')); + authorizationNotice(`${pending.length} 个待确认申请 · ${active.length} 个已启用授权`); + }catch(error){authorizationNotice(error.message||'无法读取授权,请刷新重试。',true);} +} +function openAuthorization(row){ + editingRequest=row;$('authorization-form').reset();$('authorization-name-list').value='';$('authorization-file-status').textContent='';$('authorization-file').value=''; + $('authorization-target').textContent=`${row.taskTitle ? row.taskTitle+' · ' : ''}${row.session} · ${row.workspace}`;$('authorization-editor').hidden=false;updateAuthorizationScope();$('authorization-editor').scrollIntoView({block:'nearest'});$('authorization-name-list').focus(); + const prior=activeAuthorizations.find(a=>a.session===row.session);$('authorization-existing').textContent=prior?`当前范围:${prior.coverage==='all'?'全部公司名称':prior.nameCount+'个名称'}。本次确认将替换此会话的现有授权。`:'当前为默认脱敏。'; +} +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?'此会话后续发送的历史和工具文字也会保留公司原名。其他会话、分叉和子任务照常脱敏。':'名单外名称继续脱敏。其他会话、分叉和子任务不会自动取得授权。'; +} +function openRevocation(row,card){ + document.querySelector('.revocation-confirm')?.remove();revocationOpen=true;const confirm=el('div',undefined,'revocation-confirm'); + confirm.append(el('p','确认恢复此会话的默认脱敏?已发送的原文不会被撤回。')); + const yes=el('button','确认恢复脱敏'),no=el('button','取消');yes.type=no.type='button'; + yes.addEventListener('click',event=>{if(event.isTrusted)saveAuthorization({action:'revoke',session:row.session});});no.addEventListener('click',()=>{revocationOpen=false;confirm.remove();});confirm.append(yes,no);card.append(confirm); +} +async function waitForAuthorizationReload(plan){ + const deadline=Date.now()+15000; + while(Date.now()setTimeout(resolve,250)); + } + throw new Error('配置已提交,服务尚未重新连接。请刷新核对当前授权状态。'); +} +async function saveAuthorization(action){ + if(authorizationBusy)return;authorizationBusy=true;document.querySelectorAll('#authorization-panel button,#authorization-form input,#authorization-form textarea').forEach(b=>b.disabled=true); + let plan,message,errorState=false; + try{ + authorizationNotice('正在保存并同步到请求处理…'); + const before=await magpie.options.get(),entries=before.sessionAuthorizations||[]; + plan=await authorizationPost('plan',{...action,entries}); + const latest=await magpie.options.get();if(JSON.stringify(latest.sessionAuthorizations||[])!==JSON.stringify(entries))throw new Error('授权刚被其他窗口修改,请刷新后重新确认。'); + try{await magpie.options.set({...latest,sessionAuthorizations:plan.entries,sessionAuthorizationRevision:plan.revision});} + catch(error){const saved=await magpie.options.get();if(saved.sessionAuthorizationRevision!==plan.revision)throw error;} + // Saving options restarts the local service. Wait for the new process to + // report this revision before committing its persisted operation. + await waitForAuthorizationReload(plan); + await authorizationPost('commit',{operationId:plan.operationId,entryMac:plan.entryMac}); + closeAuthorization();message=action.action==='revoke'?'已恢复此会话的默认脱敏。':'已启用。仅上述会话和确认范围允许原名。'; + }catch(error){message=error.message||'保存未完成,请刷新核对当前状态。';errorState=true;if(plan){try{const state=await api('authorization');authorizationNonce=state.nonce;await authorizationPost('cancel',{operationId:plan.operationId,entryMac:plan.entryMac});}catch{}}} + finally{authorizationBusy=false;document.querySelectorAll('#authorization-panel button,#authorization-form input,#authorization-form textarea').forEach(b=>b.disabled=false);await refreshAuthorizations();if(message)authorizationNotice(message,errorState);} +} +$('authorization-refresh').addEventListener('click',refreshAuthorizations);$('authorization-cancel').addEventListener('click',closeAuthorization); +$('authorization-form').addEventListener('change',updateAuthorizationScope); +$('authorization-file').addEventListener('change',async()=>{const file=$('authorization-file').files[0];if(!file)return;$('authorization-name-list').value='';if(file.size>2*1024*1024){$('authorization-file-status').textContent='文件超过 2 MiB,请缩小名单。';return;}try{$('authorization-name-list').value=await file.text();$('authorization-file-status').textContent='已在本机读取文件,请核对范围后确认。';}catch{$('authorization-file-status').textContent='无法读取文件,请重新选择 UTF-8 文本文件。';}}); +// The service deliberately disallows native form submission in its sandbox. +// A trusted button click uses the existing explicit-consent and signed API path. +$('authorization-form').addEventListener('submit',event=>event.preventDefault()); +$('authorization-approve').addEventListener('click',event=>{if(!event.isTrusted||!editingRequest||!$('authorization-consent').checked)return;const coverage=$('authorization-form').elements.coverage.value,names=$('authorization-name-list').value.split(/[\n;;]/).map(n=>n.trim()).filter(Boolean);saveAuthorization({action:'approve',requestId:editingRequest.id,coverage,names:coverage==='names'?names:[]});}); + +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(); diff --git a/packages/company-guard/page/dashboard.html b/packages/company-guard/page/dashboard.html new file mode 100644 index 0000000..8b05a6c --- /dev/null +++ b/packages/company-guard/page/dashboard.html @@ -0,0 +1,24 @@ + + +脱敏回执 +
+

脱敏回执

+
+
+ + + + +
+
正在读取…
+ +
+
+
时间(北京)智能体任务 / 请求名称 / 替换处数还原名称用时明细
+
+ +
+
记录说明 · 仅本机查看

回执列表与替换明细按所有任务合计保留最近 25 个请求,超过后自动清理最早记录。清理不影响正在处理的请求还原。明细另有 30 分钟期限,只存内存,重启插件后清空;旧明细不能补出原名。自动刷新间隔为 10 秒,展开明细时暂停。

处理结果见汇总和明细。回复已通过流式处理并正常结束时,可通过流式记录确认完成;缺少独立完成通知会在明细中说明。等待完成通知不证明请求仍在运行;调用未完成可能由取消、上游失败或采集超限造成。未命中不代表没有敏感名称;回复未使用代号时,还原数可以为 0。

日期按 UTC 归档,时间按北京显示。日期和任务筛选只作用于保留的最近 25 个请求。已取得的处理确认随回执保存;复核报告另外保留固定样本的确认快照。智能体来源取自请求及本机索引,旧记录无法核实时显示“来源未记录”。

+
+ +
diff --git a/packages/company-guard/page/index-0.3.3.html b/packages/company-guard/page/index-0.3.3.html new file mode 100644 index 0000000..94749c0 --- /dev/null +++ b/packages/company-guard/page/index-0.3.3.html @@ -0,0 +1,2 @@ + +公司名称保护

正在打开公司名称保护…

diff --git a/packages/company-guard/page/open.js b/packages/company-guard/page/open.js new file mode 100644 index 0000000..58dacdd --- /dev/null +++ b/packages/company-guard/page/open.js @@ -0,0 +1,11 @@ +async function openReceipts() { + try { + await magpie.ready; + const options = await magpie.options.get(); + const port = Number(options.receiptPort || 3469); + if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error("invalid_port"); + const base=magpie.service || `http://127.0.0.1:${port}/`; + location.replace(new URL("session-authorization.html",base.endsWith("/")?base:base+"/").href); + } catch { document.getElementById("loading").textContent = "无法打开保护页面,请重新打开插件页面。"; } +} +openReceipts(); diff --git a/packages/company-guard/page/style.css b/packages/company-guard/page/style.css new file mode 100644 index 0000000..ff40ce5 --- /dev/null +++ b/packages/company-guard/page/style.css @@ -0,0 +1,43 @@ +:root {color-scheme:light dark} +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} +button {cursor:pointer;white-space:nowrap}button:hover:not(:disabled) {border-color:var(--magpie-accent,#a292ff)}button:disabled {opacity:.45;cursor:default}:focus-visible {outline:2px solid var(--magpie-accent,#a292ff);outline-offset:2px} +.filters {display:flex;flex-wrap:wrap;align-items:end;gap:10px;padding-bottom:12px;border-bottom:1px solid var(--magpie-line,#35353d)}label {display:flex;flex-direction:column;gap:4px;color:var(--magpie-muted,#aaaab5);font-size:12px}.task-filter {flex:1;min-width:230px;max-width:510px}select {max-width:100%;color:var(--magpie-fg,#ededf0)}#date {width:145px}.auto {flex-direction:row;align-items:center;gap:5px;height:31px}.auto input {width:15px;height:15px;margin:0} +.summary-line {display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:8px;padding:10px 0;color:var(--magpie-muted,#aaaab5);font-size:12px}#totals {display:flex;flex-wrap:wrap;gap:15px}#totals b {color:var(--magpie-fg,#ededf0);font-size:14px;font-weight:600;margin-right:3px;font-variant-numeric:tabular-nums}#notice.error {color:var(--magpie-error,#ef9191)} +.table-wrap {overflow:auto;border:1px solid var(--magpie-line,#35353d);border-radius:7px}table {width:100%;border-collapse:collapse;font-variant-numeric:tabular-nums}.requests {min-width:840px}th {text-align:left;font-weight:500;color:var(--magpie-muted,#aaaab5);background:var(--magpie-card,#222227);white-space:nowrap}th,td {padding:8px 10px;border-bottom:1px solid var(--magpie-line,#35353d);vertical-align:middle}tbody tr:last-child td {border-bottom:0}.number {text-align:right;white-space:nowrap}.mono {font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;overflow-wrap:anywhere}.muted {color:var(--magpie-muted,#aaaab5)} +#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} +[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} +.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-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)} +.authorization-guide code{font-family:inherit;color:var(--magpie-fg,#ededf0);font-weight:550;white-space:nowrap}.authorization-guide details{max-width:100%}.authorization-guide summary{white-space:nowrap;color:var(--magpie-muted,#aaaab5)} +.authorization-guide details[open]{flex-basis:100%}.authorization-guide details p{margin:8px 0 0;max-width:880px;line-height:1.6;color:var(--magpie-muted,#aaaab5)} +#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-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} +.authorization-editor{box-sizing:border-box;width:100%;max-width:940px;margin-top:12px;padding:12px 14px;border:1px solid var(--magpie-line,#35353d);border-radius:7px} +.authorization-editor-heading{display:flex;align-items:baseline;justify-content:space-between;flex-wrap:wrap;gap:4px 16px}.authorization-editor-heading h2{margin:0!important;line-height:1.5}.authorization-editor-heading p{margin:0;max-width:65%;font-size:11px;line-height:1.5} +.authorization-editor>.identity{margin:4px 0 8px;line-height:1.55} +.authorization-editor fieldset{display:flow-root;min-width:0;border:0;padding:0;margin:8px 0 6px}.authorization-editor legend{float:left;margin:0 16px 0 0;padding:0;font-size:12px;line-height:24px;font-weight:600}.authorization-editor label{font-size:12px} +.authorization-editor fieldset label{display:inline-flex;vertical-align:top;flex-direction:row;align-items:center;gap:6px;min-height:24px;margin-right:18px}.authorization-confirm,.file-label{display:flex;flex-direction:row;align-items:center;gap:7px} +.authorization-editor textarea{display:block;box-sizing:border-box;width:100%;margin:5px 0 7px;resize:vertical;font:inherit;border:1px solid var(--magpie-line,#414147);border-radius:5px;padding:7px 8px} +.file-label{gap:10px;flex-wrap:wrap}.authorization-footer{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px 16px;margin-top:10px;padding-top:9px;border-top:1px solid var(--magpie-line,#35353d)}.authorization-confirm{margin:0;min-height:29px}.authorization-actions{display:flex;gap:6px}.authorization-actions button{height:29px;padding:4px 10px} +.authorization-editor input[type="radio"],.authorization-confirm input{width:16px;height:16px;margin:0;flex:none} +.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))} diff --git a/packages/company-guard/receipt-page.mjs b/packages/company-guard/receipt-page.mjs new file mode 100644 index 0000000..463cf28 --- /dev/null +++ b/packages/company-guard/receipt-page.mjs @@ -0,0 +1,227 @@ +import fs from "node:fs/promises"; +import {constants} from "node:fs"; +import {createServer} from "node:http"; +import {timingSafeEqual, randomBytes, randomUUID} from "node:crypto"; +import path from "node:path"; +import os from "node:os"; +import {gunzipSync} from "node:zlib"; +import {getReceiptReport} from "./src/receipt-report.mjs"; +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"; + +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"}; + +// Titles and task kinds are display metadata only, never authorization. +// Read local indexes, never chat messages, and match complete session IDs. +async function withTaskTitles(rows, day, availableAgents) { + const idOf=row=>row.session || row.task || row.thread; + const ids=new Set(rows.map(idOf).filter(Boolean)),titles=new Map(),agents=new Map(); + const addAgent=(id,value)=>{const agent=receiptAgent(value);if(agent){availableAgents?.add(agent);const found=agents.get(id)||new Set();found.add(agent);agents.set(id,found);}}; + for(const row of rows)addAgent(idOf(row),row.agent); + if(ids.size)try{ + const file=path.join(process.env.CODEX_HOME || path.join(os.homedir(),".codex"),"session_index.jsonl"); + const fd=await fs.open(file,constants.O_RDONLY|constants.O_NOFOLLOW); + try{ + const stat=await fd.stat(); + if(stat.isFile()&&stat.uid===process.getuid()&&stat.size<=8*1024*1024){ + for(const line of (await fd.readFile("utf8")).split("\n")){ + let row;try{row=JSON.parse(line);}catch{continue;} + if(ids.has(row?.id)&&typeof row.thread_name==="string"){ + addAgent(row.id,"codex"); + const title=row.thread_name.replace(/[\u0000-\u001f\u007f]/g," ").trim().slice(0,300); + if(title)titles.set(row.id,title); + } + } + } + }finally{await fd.close();} + }catch{} // An unavailable title index must not affect grants or receipts. + const missing=new Set([...ids].filter(id=>!titles.has(id))); + if(ids.size && /^\d{4}-\d{2}-\d{2}$/.test(day || "")){ + // Hidden Codex tasks need not appear in its chat-title index. Magpie's + // routing history already records their kinds, including older receipts. + const labels=new Map([ + ["memory_consolidation","后台记忆整理"], ["memgen","后台记忆处理"], + ["guardian","后台审批复核"], ["guardian_review","后台审批复核"], + ["thread_title","后台标题生成"], ["thread_title_reconsideration","后台标题更新"], + ["composer_predictions","后台输入预测"], ["collab_spawn","子任务"], + ["compact","上下文压缩"], ["review","后台审阅"] + ]), kinds=new Map(); + const config=path.isAbsolute(process.env.XDG_CONFIG_HOME || "") ? process.env.XDG_CONFIG_HOME : path.join(os.homedir(),".config"); + // Receipt dates use UTC; routes use local dates, which may be adjacent. + for(const offset of [-1,0,1])try{ + const date=new Date(Date.parse(day+"T00:00:00Z")+offset*86400000).toISOString().slice(0,10); + const file=path.join(config,"magpie","routing",date+".jsonl"); + let content=await readTail(file); + if(!content){ + const fd=await fs.open(file+".gz",constants.O_RDONLY|constants.O_NOFOLLOW); + try{ + const stat=await fd.stat(); + if(stat.isFile()&&stat.uid===process.getuid()&&stat.size<=8*1024*1024) + content=gunzipSync(await fd.readFile(),{maxOutputLength:16*1024*1024}).toString("utf8"); + }finally{await fd.close();} + } + for(const line of content.split("\n")){ + let route;try{route=JSON.parse(line);}catch{continue;} + const knownAgent=receiptAgent(route?.agent);if(knownAgent)availableAgents?.add(knownAgent); + if(!ids.has(route?.session))continue; + addAgent(route.session,route.agent); + if(route.agent!=="codex" || !missing.has(route.session))continue; + const found=kinds.get(route.session) || new Set(); + found.add(labels.get(route.kind) || ""); kinds.set(route.session,found); + } + }catch{} // Missing, rotated or oversized history only affects the label. + for(const [id,found] of kinds){ + // A session with ordinary or unknown calls must not acquire a false kind. + if(!found.has(""))titles.set(id,found.size===1 ? [...found][0] : "后台任务"); + } + } + return rows.map(row=>{const own=receiptAgent(row.agent),found=own?[own]:[...(agents.get(idOf(row))||[])];return {...row,taskTitle:titles.get(idOf(row)) || "",agentIds:found,agentLabel:found.length?found.map(agent=>agentNames[agent]||agent).join("、"):"来源未记录"};}); +} + +// Runs inside Magpie's existing plugin host; no separate daemon or model call. +export const ReceiptPage = async (_input, options = {}) => { + await initializeOptions(options); + const port = Number(options.receiptPort || 3469); + const key = options.receiptReadKey; + if (!Number.isInteger(port) || port < 1024 || port > 65535 || !/^[a-f0-9]{64}$/.test(key || "")) { + console.warn("company_guard_receipt_page_not_configured"); return {}; + } + const root = stateRoot(options.stateDir); + 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"]]) { + 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 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"); + await secureDir(path.dirname(operationFile(id))); + const fd=await fs.open(operationFile(id),constants.O_RDONLY|constants.O_NOFOLLOW); + try {const stat=await fd.stat();if(!stat.isFile()||stat.uid!==process.getuid()||(stat.mode&0o077)||stat.size>4096)throw new Error("invalid_operation");return JSON.parse(await fd.readFile("utf8"));}finally{await fd.close();} + }; + 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 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"}); + 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)){ + const op=await readOperation(body.operationId); + if(op.created64||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/plan")return send(404,{error:"not_found"}); + let request, prior; + const legacy=await legacyTaskGrants(root); + if(body.action==="approve"){ + request=(await listAuthorizationRequests(root)).find(r=>r.id===body.requestId); + if(!request)return send(409,{error:"request_expired"}); + }else if(body.action==="revoke"){ + prior=body.entries.map(e=>readAuthorization(e,options.authKey)).find(r=>r.session===body.session&&r.state==="active")||legacy.find(r=>r.session===body.session); + if(!prior)return send(409,{error:"authorization_not_found"}); + }else return send(400,{error:"invalid_action"}); + const coverage=body.action==="revoke"?"all":body.coverage; + if(!["all","names"].includes(coverage))return send(400,{error:"invalid_scope"}); + const names=coverage==="names"&&Array.isArray(body.names)?[...new Set(body.names.map(n=>typeof n==="string"?n.trim():n))]:[]; + 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"}); + 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"); + try{const prior=JSON.parse(await fs.readFile(lock,"utf8"));if(prior.created { + res.setHeader("Cache-Control", "no-store"); + res.setHeader("X-Content-Type-Options", "nosniff"); + res.setHeader("Content-Type", "application/json; charset=utf-8"); + const send = (code, data) => {res.writeHead(code); res.end(JSON.stringify(data));}; + if (req.headers.host !== `127.0.0.1:${port}` || (req.headers.origin && req.headers.origin !== "null")) return send(403, {error:"forbidden"}); + res.setHeader("Access-Control-Allow-Origin", "null"); + res.setHeader("Vary", "Origin"); + if (req.method === "OPTIONS") { + res.setHeader("Access-Control-Allow-Methods", "GET, POST"); + res.setHeader("Access-Control-Allow-Headers", "X-Receipt-Key, X-Authorization-Key, X-Authorization-Nonce, Content-Type"); + return send(204, {}); + } + const url = new URL(req.url, `http://127.0.0.1:${port}`); + if (req.method === "GET" && assets.has(url.pathname)) { + const asset = assets.get(url.pathname), local = `http://127.0.0.1:${port}`; + res.setHeader("Content-Type", asset.type + "; charset=utf-8"); + res.setHeader("Referrer-Policy", "no-referrer"); + res.setHeader("Content-Security-Policy", `sandbox allow-scripts; default-src 'none'; script-src 'self' ${local}; style-src 'self' ${local} 'unsafe-inline'; connect-src 'self' ${local}; frame-src 'none'; object-src 'none'; form-action 'none'; base-uri 'none'; frame-ancestors 'self' wails://localhost`); + res.writeHead(200); res.end(asset.body); return; + } + 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==="/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 === "/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"}); + return send(200,readDetails(root,id)); + } + if (url.pathname !== "/receipts") return send(404, {error:"not_found"}); + const day = url.searchParams.get("date") || new Date().toISOString().slice(0,10); + if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) return send(400, {error:"invalid_date"}); + try { + const report = await getReceiptReport({day, root, appLog:options.appLog}); + const availableAgents=new Set(),rows=await withTaskTitles(report.rows,day,availableAgents); + send(200, {...report,rows,agentOptions:[...availableAgents].sort().map(id=>({id,label:agentNames[id]||id})),readAt:new Date().toISOString()}); + } catch { console.warn("company_guard_receipt_page_read_failed"); send(500, {error:"receipt_read_failed"}); } + }); + server.requestTimeout = 10000; + server.maxHeadersCount = 30; + services.set(port,server); + let retry, delay = 1000, recovering = false; + const schedule = () => { + if (retry) return; + retry = setTimeout(() => {retry=null;server.listen(port,"127.0.0.1");},delay); + retry.unref(); delay=Math.min(delay*2,30000); + }; + server.on("error", error => { + console.warn("company_guard_receipt_page_start_failed", error.code || "unknown"); + recovering=true; schedule(); + }); + server.on("listening", () => { + clearTimeout(retry); retry=null; delay=1000; + if(recovering)console.info("company_guard_receipt_page_recovered"); + recovering=false; + }); + server.on("close",schedule); + server.listen(port,"127.0.0.1"); + server.unref(); + return {}; +}; diff --git a/packages/company-guard/receipt-report.mjs b/packages/company-guard/receipt-report.mjs new file mode 100644 index 0000000..1e45434 --- /dev/null +++ b/packages/company-guard/receipt-report.mjs @@ -0,0 +1,14 @@ +#!/usr/bin/env node +import {getReceiptReport} from "./src/receipt-report.mjs"; +import {stateRoot} from "./src/grant-store.mjs"; +const arg = key => process.argv.includes(key) ? process.argv[process.argv.indexOf(key) + 1] : undefined; +const result = await getReceiptReport({day:arg("--date"),root:stateRoot(arg("--state-dir")),task:arg("--task"),appLog:arg("--app-log")}); +result.rows = result.rows.slice(0,Math.max(1,Math.min(100,Number(arg("--limit")) || 20))); +const rows = result.rows; +if (process.argv.includes("--json")) console.log(JSON.stringify(result,null,2)); +else { + console.log("| 时间(北京时间) | 任务 | 请求编号 | 状态 | 名称 / 替换处数 | 已还原名称 | 本地处理 ms |\n|---|---|---|---|---|---|---|"); + for(const r of rows) console.log(`| ${new Date(r.at).toLocaleTimeString("zh-CN",{timeZone:"Asia/Shanghai"})} | ${r.task || "未知"} | ${r.id} | ${r.statusLabel || r.status} | ${r.replacedNames ?? "?"} / ${r.replacements ?? "?"} | ${r.restoredNames ?? "?"} | ${r.processingMs ?? "?"} |`); + if (!rows.length) console.log("\n没有匹配的回执,不能据此判断请求已受保护。"); + console.log("\n"+result.limits.join(";")+"。"); +} diff --git a/packages/company-guard/src/company-guard.js b/packages/company-guard/src/company-guard.js new file mode 100644 index 0000000..7c113f9 --- /dev/null +++ b/packages/company-guard/src/company-guard.js @@ -0,0 +1,336 @@ +import { sign, scopedSigner, same, validKey } from "./crypto.js"; +import { PROOF, TOKEN_PREFIX, configuredNames, detectNames, directive, escapeRE, expandAllowed, identity, nameFieldValue, namePattern, readProof, taskAliases, validName, webTool } from "./policy.js"; +import { inspectRequest, publicContextSafe, safeInput } from "./protocols.js"; +import {resolveAuthorization} from "./session-authorization.js"; + +const ESCAPED_STRING = /"[^"\\]*(?:\\.[^"\\]*)+"/g; +const TOKEN = /\[\[NERO_ORG_[a-f0-9]{24}\]\]/g; +const NOTE = "Company identifiers of the form [[NERO_ORG_…]] are opaque local labels. Copy them exactly in text and tool arguments; do not infer or expand them."; +const fail = (ctx, code) => { ctx.reject(400, "NERO 公司名保护:" + code); }; + +function addNote(body, protocol) { + if (protocol === "responses") body.instructions = (body.instructions ? body.instructions + "\n\n" : "") + NOTE; + else if (protocol === "anthropic") { + if (Array.isArray(body.system)) body.system.push({type: "text", text: NOTE}); + else body.system = (body.system ? body.system + "\n\n" : "") + NOTE; + } else if (protocol === "gemini") { + body.systemInstruction ||= {parts: []}; body.systemInstruction.parts ||= []; + body.systemInstruction.parts.push({text: NOTE}); + } else if (Array.isArray(body.messages)) body.messages.unshift({role: "system", content: NOTE}); +} + +export function prepareRequest(body, ctx) { + const budget = () => { if (ctx.signal?.aborted) throw new Error("本地处理已取消"); }; + ctx.state.guard = {reverse: Object.create(null), buffers: Object.create(null), ready: false, failed: false}; + try { + const o = ctx.options || {}; + if (!validKey(o.authKey)) { fail(ctx, "尚未配置本地保护密钥"); return; } + let proof = readProof(body[PROOF], body, o.authKey, ctx); + delete body[PROOF]; + const managed = resolveAuthorization(body,ctx); + if (managed.managed) proof = managed.record ? {mode:"original",scope:"session_task",coverage:managed.record.coverage,names:managed.record.names,pattern:managed.record.pattern} : null; + if (!["responses", "chat", "anthropic", "gemini"].includes(ctx.protocol)) throw new Error("不支持的请求协议"); + safeInput(body, ctx.protocol); + const view = inspectRequest(body, ctx.protocol); + const metrics = ctx.state.guard.metrics = {matchedNames: 0, replacedNames: 0, replacements: 0, allowedOccurrences: 0, scopes: {}}; + const matched = new Set(); + const scopeOf = s => s.source === "user" ? (s.index === view.user?.index ? "user" : "history") : ({tool: "tool_results", call: "tool_arguments", schema: "tool_schema", instruction: "instructions"}[s.source] || "history"); + let currentScope; + for (const slot of view.slots) { + const key = scopeOf(slot); + metrics.scopes[key] ||= {checkedTexts: 0, replacements: 0}; + metrics.scopes[key].checkedTexts++; + } + let size = 0; + for (const s of view.slots) { size += s.owner[s.key].length; if (size > 4 * 1024 * 1024) throw new Error("文字超过 4 MiB,请缩小本次输入"); } + if (proof?.coverage === "all") { + metrics.authorization="original";metrics.authorizationReason=managed.reason;metrics.authorizationCoverage="all"; + ctx.state.guard.authorization="original";ctx.state.guard.ready=true; + return body; + } + const requested = managed.managed ? new Set(proof?.names || []) : expandAllowed(proof?.names || [], o); + if (proof?.mode === "public_lookup" && !publicContextSafe(view, requested)) proof = null; + const allowed = proof ? requested : new Set(); + ctx.state.guard.authorization = proof ? proof.mode : "masked"; + metrics.authorization = ctx.state.guard.authorization; + metrics.authorizationReason = managed.managed ? managed.reason : proof ? (proof.scope === "session_task" ? "session_task_active" : "turn_grant_active") : (ctx.grantStatus || "no_matching_grant"); + metrics.authorizationCoverage=proof?"names":"none"; + const names = new Set(configuredNames(o)); + const aliases = taskAliases(view.slots); + for (const n of aliases.names) names.add(n); + metrics.taskAliases = aliases.names.length; + metrics.aliasConflicts = aliases.conflicts; + metrics.aliasLimitReached = aliases.limited; + if(!proof?.pattern)for (const n of allowed) names.add(n); + for (const s of view.slots) { + budget(); + const text = s.owner[s.key]; + for (const n of detectNames(text)) names.add(n); + if (s.nameField) { const name = nameFieldValue(text, s.nameField); if (name) names.add(name); } + // Historical control text is a recognition hint, never an authorization. + if (s.source === "user") for (const n of directive(text)?.names || []) names.add(n); + if (text.includes("\\u")) for (const q of text.matchAll(ESCAPED_STRING)) { + let t; try { t = JSON.parse(q[0]); } catch { continue; } + for (const n of detectNames(t)) names.add(n); + } + + } + const candidates = [...names].filter(n => typeof n === "string" && n.length >= 2).sort((a, b) => b.length - a.length); + const pattern = candidates.length ? namePattern(candidates) : ""; + const matcher = candidates.length ? new RegExp("\\[\\[NERO_ORG_[a-f0-9]{24}\\]\\]|(?:" + pattern + ")", "gi") : null; + const prefixMatcher = candidates.length ? new RegExp(namePattern([...new Set(candidates.map(n=>n.slice(0,2)))]),"i") : null; + const literalMatchers = !ctx.sign ? candidates.map((n,rank)=>({re:new RegExp(escapeRE(n),"gi"),rank})) : null; + const opaque = new RegExp(TOKEN.source,"gi"); + const approvedMatcher=proof?.pattern?new RegExp(proof.pattern,"gi"):null; + const id = identity(body); + const scope = [ctx.session, id?.thread].filter(Boolean).join(":") || "request:" + Date.now() + ":" + Math.random(); + const signName = ctx.sign ? name => ctx.sign(o.authKey,scope+"\u0000"+name) : scopedSigner(o.authKey,scope+"\u0000"); + const forward = Object.create(null), reverse = ctx.state.guard.reverse; + const allowedFold = new Set([...allowed].map(n => n.toLowerCase())); + const tokenFor = name => { + if (forward[name]) return forward[name]; + const token = TOKEN_PREFIX + signName(name).slice(0, 24) + "]]"; + if (reverse[token] && reverse[token] !== name) throw new Error("名称代号冲突"); + forward[name] = token; reverse[token] = name; return token; + }; + const replaceName = (name, offset, original, allow) => { + if (/^\[\[NERO_ORG_[a-f0-9]{24}\]\]$/.test(name)) return name; + if (/[A-Za-z0-9_]/.test(name[0]) && offset > 0 && /[A-Za-z0-9_]/.test(original[offset - 1])) return name; + if (/[A-Za-z0-9_]/.test(name.at(-1)) && /[A-Za-z0-9_]/.test(original[offset + name.length] || "")) return name; + matched.add(name); metrics.matchedNames = matched.size; + if (allow && allowedFold.has(name.toLowerCase())) { metrics.allowedOccurrences++; return name; } + const token = tokenFor(name); + metrics.replacements++; metrics.scopes[currentScope].replacements++; + return token; + }; + const sub = (text, allow) => { + if (!matcher&&!approvedMatcher) return text; + if (!literalMatchers&&!approvedMatcher) return text.replace(matcher,(n,i,s)=>replaceName(n,i,s,allow)); + // Literal searches stay fast in the synchronous interpreter. Include + // overlaps, then retain the union-regex order: earliest, longest first. + const hits = []; let m; + opaque.lastIndex = 0; + while ((m=opaque.exec(text))) hits.push({at:m.index,name:m[0],rank:-1}); + if(approvedMatcher){approvedMatcher.lastIndex=0;while((m=approvedMatcher.exec(text)))hits.push({at:m.index,name:m[0],rank:0});} + if(!literalMatchers&&matcher){matcher.lastIndex=0;while((m=matcher.exec(text)))hits.push({at:m.index,name:m[0],rank:1});} + for (const item of literalMatchers||[]) { + item.re.lastIndex = 0; + while ((m=item.re.exec(text))) { + hits.push({at:m.index,name:m[0],rank:item.rank}); + item.re.lastIndex = m.index+1; + } + } + hits.sort((a,b)=>a.at-b.at || (approvedMatcher?b.name.length-a.name.length:0) || a.rank-b.rank); + const pieces = []; let after = 0; + for (const hit of hits) { + if (hit.at { + let value; try { value = JSON.parse(raw); } catch { return raw; } + const next = sub(value, allow); return next === value ? raw : JSON.stringify(next); + }); + text = sub(text, allow); + if (s.sealed && text !== s.owner[s.key]) throw new Error("签名思考内容不能安全改写,请使用干净的新上下文"); + s.owner[s.key] = text; + } + metrics.replacedNames = Object.keys(reverse).length; + if (metrics.replacedNames) addNote(body, ctx.protocol); + ctx.state.guard.ready = true; + return body; + } catch (e) { fail(ctx, e instanceof Error ? e.message : "本地检查失败"); } +} + +function restore(text, state, json = false) { + if (typeof text !== "string") return text; + return text.replace(TOKEN, token => { + const name = state.reverse[token]; + if (name !== undefined && state.restoredTokens) state.restoredTokens[token] = true; + return name === undefined ? token : json ? JSON.stringify(name).slice(1, -1) : name; + }); +} + +function whole(value, state, depth = 0, data = false) { + if (!value || typeof value !== "object" || depth > 64) return; + for (const key of Object.keys(value)) { + if (!data && /^(?:id|type|role|name|model|call_id|tool_call_id|tool_use_id|signature|encrypted_content)$/.test(key)) continue; + if (typeof value[key] === "string") value[key] = restore(value[key], state, key === "arguments"); + else whole(value[key], state, depth + 1, data || key === "args" || (key === "input" && value.type === "tool_use")); + } +} + +function chunk(text, state, key, json = false, final = false) { + if (typeof text !== "string") return text; + let value = (state.buffers[key] || "") + text; + state.buffers[key] = ""; + if (!final) { + let cut = value.lastIndexOf(TOKEN_PREFIX); + if (cut >= 0) { + const tail = value.slice(cut); + if (tail.length < TOKEN_PREFIX.length + 26 && /^\[\[NERO_ORG_[a-f0-9]*\]?$/.test(tail)) { + state.buffers[key] = tail; value = value.slice(0, cut); + } + } + if (!state.buffers[key]) for (let n = Math.min(value.length, TOKEN_PREFIX.length - 1); n > 0; n--) { + if (value.endsWith(TOKEN_PREFIX.slice(0, n))) { state.buffers[key] = value.slice(-n); value = value.slice(0, -n); break; } + } + } + return restore(value, state, json); +} + +function clear(state, prefix) { for (const key of Object.keys(state.buffers)) if (key.startsWith(prefix)) delete state.buffers[key]; } +function pending(state, prefix = "") { return Object.keys(state.buffers).some(k => k.startsWith(prefix) && state.buffers[k]); } +function streamError(ctx, state) { + state.failed = true; + receiptEvent(state, "reply_processed", false, "restoration_incomplete"); + const message = "NERO 公司名还原未完成,已停止此回复,请重试。"; + if (ctx.protocol === "responses") return {type: "error", code: "nero_restore_incomplete", message, param: null}; + if (ctx.protocol === "anthropic") return {type: "error", error: {type: "api_error", message}}; + return {error: {type: "nero_restore_incomplete", message}}; +} + +export function onEvent(ev, ctx) { + const state = ctx.state.guard; + if (!state?.ready) return; + if (!Object.keys(state.reverse).length) { if (terminalEvent(ev, ctx.protocol)) receiptEvent(state, "reply_processed", terminalOK(ev), terminalOK(ev) ? "processed" : "upstream_incomplete", terminalLabel(ev, ctx.protocol)); return; } + if (state.failed) return null; + try { + if (ctx.protocol === "responses") { + const p = "r:" + (ev.output_index ?? 0) + ":"; + const key = p + (ev.content_index ?? ev.summary_index ?? 0) + ":" + (ev.type || "").replace(/\.(delta|done)$/, ""); + if (typeof ev.delta === "string" && /\.delta$/.test(ev.type)) ev.delta = chunk(ev.delta, state, key, ev.type === "response.function_call_arguments.delta"); + else { + whole(ev, state); + if (/\.(done)$/.test(ev.type)) { + if (ev.type === "response.output_item.done") clear(state, p); else delete state.buffers[key]; + } + if (["response.completed", "response.incomplete", "response.failed"].includes(ev.type)) { + if (Array.isArray(ev.response?.output) && ev.response.output.length) clear(state, "r:"); + if (pending(state)) return streamError(ctx, state); + } + } + } else if (ctx.protocol === "anthropic") { + const p = "a:" + (ev.index ?? 0) + ":"; + if (ev.type === "content_block_delta") { + for (const key of ["text", "thinking", "partial_json"]) if (typeof ev.delta?.[key] === "string") ev.delta[key] = chunk(ev.delta[key], state, p + key, key === "partial_json"); + } else { + whole(ev, state); + if (ev.type === "content_block_stop" && pending(state, p)) return streamError(ctx, state); + if (ev.type === "message_stop" && pending(state)) return streamError(ctx, state); + } + } else if (Array.isArray(ev.choices)) { + for (const c of ev.choices) { + const p = "c:" + (c.index ?? 0) + ":", end = c.finish_reason != null; + c.delta ||= {}; + for (const key of ["content", "reasoning", "reasoning_content", "refusal"]) if (typeof c.delta[key] === "string" || (end && state.buffers[p + key])) c.delta[key] = chunk(c.delta[key] || "", state, p + key, false, end); + for (const t of c.delta.tool_calls || []) if (t.function) t.function.arguments = chunk(t.function.arguments || "", state, p + "tool:" + (t.index ?? 0), true, end); + if (c.delta.function_call) c.delta.function_call.arguments = chunk(c.delta.function_call.arguments || "", state, p + "function", true, end); + if (end && pending(state, p)) return streamError(ctx, state); + } + } else if (Array.isArray(ev.candidates)) { + for (let ci = 0; ci < ev.candidates.length; ci++) { + const c = ev.candidates[ci], parts = c.content?.parts || []; + for (let pi = 0; pi < parts.length; pi++) { + const part = parts[pi], key = "g:" + (c.index ?? ci) + ":" + pi + ":" + !!part.thought; + if (typeof part.text === "string") part.text = chunk(part.text, state, key, false, !!c.finishReason); + if (part.functionCall) whole(part.functionCall.args, state, 0, true); + } + if (c.finishReason && pending(state, "g:" + (c.index ?? ci) + ":")) return streamError(ctx, state); + } + } else whole(ev, state); + if (terminalEvent(ev, ctx.protocol)) receiptEvent(state, "reply_processed", terminalOK(ev) && !state.failed && !pending(state), !terminalOK(ev) ? "upstream_incomplete" : state.failed || pending(state) ? "restoration_incomplete" : "processed", terminalLabel(ev, ctx.protocol)); + return ev; + } catch { return streamError(ctx, state); } +} + +export function onResponse(body, ctx) { + const state = ctx.state.guard; + if (!state?.ready) return; + whole(body, state); receiptEvent(state, "reply_processed", !state.failed && !pending(state)); return body; +} + +export const PREPARED = "__nero_company_prepared"; +export function onRequest(body, ctx) { + const envelope = body[PREPARED]; + delete body[PREPARED]; delete body[PROOF]; + const key = ctx.options?.authKey; + try { + if (!validKey(key)) throw new Error("本地保护密钥不可用"); + if (envelope === undefined || envelope === null) { + // The async host can keep the original body when its result cannot cross + // the RPC boundary. Process it here instead of depending on that handoff. + // Confirmed session grants are read from the same protected options as + // the async path; without one, recognized names use default masking. + // A client thread id is a stable pseudonym salt, never an authorization. + let metadata = body?.client_metadata?.["x-codex-turn-metadata"] || body?.client_metadata; + if (typeof metadata === "string") { try { metadata = JSON.parse(metadata); } catch { metadata = null; } } + const hint = /^[A-Za-z0-9][A-Za-z0-9_-]{1,127}$/.test(metadata?.thread_id || "") ? metadata.thread_id : undefined; + const result = prepareRequest(body, {...ctx, session:ctx.session || hint}); + const state = ctx.state.guard; + if (state?.ready) { + state.fallback = true; + state.fallbackIdentity = identity(body); + state.restoredTokens = Object.create(null); + receiptEvent(state, "request_checked", true); + } + return result; + } + if (!envelope || typeof envelope.payload !== "string") throw new Error("本地脱敏处理未完成:缺少处理结果"); + if (!same(sign(key, envelope.payload), envelope.mac)) throw new Error("本地脱敏处理结果签名不匹配"); + const p = JSON.parse(envelope.payload), now = Date.now(); + if (p.v !== 1 || p.protocol !== ctx.protocol || p.expires < now || p.expires > now + 30000 || p.thread !== (identity(body)?.thread || "")) throw new Error("本地脱敏结果已失效"); + if (p.error) throw new Error(p.error); + const reverse = Object.create(null); + for (const [token, name] of Object.entries(p.reverse || {})) { + if (!/^\[\[NERO_ORG_[a-f0-9]{24}\]\]$/.test(token) || !validName(name)) throw new Error("名称还原记录无效"); + reverse[token] = name; + } + ctx.state.guard = {reverse, buffers: Object.create(null), ready: true, failed: false, receiptId: p.receiptId, restoredTokens: Object.create(null)}; + if (p.schema?.length) { + const slots = inspectRequest({tools: body.tools}, ctx.protocol).slots; + for (const [i, text] of p.schema) { + if (!slots[i] || typeof text !== "string") throw new Error("工具说明处理结果无效"); + slots[i].owner[slots[i].key] = text; + } + } + receiptEvent(ctx.state.guard, "request_checked", true); + return body; + } catch (e) { fail(ctx, e.message || "本地处理失败"); } +} + +function terminalOK(ev) { return !["error", "response.failed", "response.incomplete"].includes(ev.type); } +function terminalLabel(ev, protocol) { + if (protocol === "chat") return ev.choices?.length && ev.choices.every(c => ["stop", "tool_calls", "function_call"].includes(c.finish_reason)) ? "chat.completed" : undefined; + if (protocol === "gemini") return ev.candidates?.length && ev.candidates.every(c => c.finishReason === "STOP") ? "gemini.completed" : undefined; + return ev.type; +} +function terminalEvent(ev, protocol) { + if (protocol === "responses") return ["response.completed", "response.failed", "response.incomplete"].includes(ev.type); + if (protocol === "anthropic") return ["message_stop", "error"].includes(ev.type); + if (protocol === "chat") return ev.choices?.length && ev.choices.every(c => c.finish_reason != null); + return ev.candidates?.length && ev.candidates.every(c => c.finishReason); +} +function receiptEvent(state, phase, ok, reason, eventType) { + if (!state?.fallback && !/^[a-f0-9-]{36}$/.test(state?.receiptId || "")) return; + if (phase === "reply_processed" && state.receiptDone) return; + if (phase === "reply_processed") state.receiptDone = true; + const replyReason = phase === "reply_processed" ? reason || (ok ? "processed" : "restoration_incomplete") : undefined; + const terminalType = ["response.completed", "response.failed", "response.incomplete", "message_stop", "chat.completed", "gemini.completed", "error"].includes(eventType) ? eventType : undefined; + if (state.fallback) { + const metrics = state.metrics || {}; + try { console.info("NERO_COMPANY_GUARD_FALLBACK " + JSON.stringify({phase, ok, thread:state.fallbackIdentity?.thread || null, turn:state.fallbackIdentity?.turn || null, cause:"prepared_result_unavailable", authorization:metrics.authorization || "masked", authorizationCoverage:metrics.authorizationCoverage || "none", matchedNames:metrics.matchedNames || 0, replacements:metrics.replacements || 0, reason:replyReason, eventType:terminalType, restoredNames:Object.keys(state.restoredTokens).length})); } catch {} + return; + } + try { console.info("NERO_COMPANY_GUARD_RECEIPT " + JSON.stringify({id: state.receiptId, phase, ok, reason:replyReason, eventType:terminalType, restoredNames: Object.keys(state.restoredTokens || {}).length})); } catch {} +} diff --git a/packages/company-guard/src/crypto.js b/packages/company-guard/src/crypto.js new file mode 100644 index 0000000..79b242c --- /dev/null +++ b/packages/company-guard/src/crypto.js @@ -0,0 +1,41 @@ +import { sha256, hmac } from "../vendor/hashes.js"; + +// No TextEncoder/Node dependency: this module also runs in Magpie's moejs. +export function utf8(text) { + const out = []; + for (let i = 0; i < text.length; i++) { + let cp = text.charCodeAt(i); + if (cp >= 0xd800 && cp <= 0xdbff) { + const lo = text.charCodeAt(i + 1); + if (lo >= 0xdc00 && lo <= 0xdfff) { cp = 0x10000 + ((cp - 0xd800) << 10) + lo - 0xdc00; i++; } + else cp = 0xfffd; + } else if (cp >= 0xdc00 && cp <= 0xdfff) cp = 0xfffd; + if (cp < 0x80) out.push(cp); + else if (cp < 0x800) out.push(0xc0 | (cp >> 6), 0x80 | (cp & 63)); + else if (cp < 0x10000) out.push(0xe0 | (cp >> 12), 0x80 | ((cp >> 6) & 63), 0x80 | (cp & 63)); + else out.push(0xf0 | (cp >> 18), 0x80 | ((cp >> 12) & 63), 0x80 | ((cp >> 6) & 63), 0x80 | (cp & 63)); + } + return new Uint8Array(out); +} + +function hex(bytes) { let out = ""; for (const n of bytes) out += n.toString(16).padStart(2, "0"); return out; } +export function validKey(key) { return typeof key === "string" && /^[0-9a-f]{64}$/.test(key); } +function keyBytes(key) { + if (!validKey(key)) throw new Error("guard_key_missing"); + const bytes = new Uint8Array(32); + for (let i = 0; i < 32; i++) bytes[i] = parseInt(key.slice(i * 2, i * 2 + 2), 16); + return bytes; +} +export function sign(key, text) { + return hex(hmac(sha256, keyBytes(key), utf8(text))); +} +export function scopedSigner(key, prefix) { + const base = hmac.create(sha256, keyBytes(key)).update(utf8(prefix)); + return text => hex(base.clone().update(utf8(text)).digest()); +} +export function digest(text) { return hex(sha256(utf8(text))); } +export function same(a, b) { + if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) return false; + let d = 0; for (let i = 0; i < a.length; i++) d |= a.charCodeAt(i) ^ b.charCodeAt(i); + return d === 0; +} diff --git a/packages/company-guard/src/grant-store.mjs b/packages/company-guard/src/grant-store.mjs new file mode 100644 index 0000000..ec389c6 --- /dev/null +++ b/packages/company-guard/src/grant-store.mjs @@ -0,0 +1,111 @@ +import fs from "node:fs/promises"; +import { constants } from "node:fs"; +import path from "node:path"; +import os from "node:os"; +import { createHash, randomBytes } from "node:crypto"; +import {inspectRequest} from "./protocols.js"; +import {sessionIdentity, sessionWorkspace} from "./session-authorization.js"; + +export const hash = s => createHash("sha256").update(s).digest("hex"); +export const configRoot = () => path.join(path.isAbsolute(process.env.XDG_CONFIG_HOME || "") ? process.env.XDG_CONFIG_HOME : path.join(os.homedir(), ".config"), "magpie"); +export const stateRoot = explicit => explicit || path.join(configRoot(), "company-guard"); +export const grantPath = (root, session) => path.join(root, "grants", hash(session) + ".json"); + +export async function secureDir(dir, create = false) { + if (create) await fs.mkdir(dir, {recursive: true, mode: 0o700}); + const s = await fs.lstat(dir); + if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== process.getuid() || (s.mode & 0o077)) throw new Error("insecure_grant_directory"); +} +export async function readGrant(root, session) { + await secureDir(root); await secureDir(path.join(root, "grants")); + const f = await fs.open(grantPath(root, session), constants.O_RDONLY | constants.O_NOFOLLOW); + try { + const s = await f.stat(); + if (!s.isFile() || s.uid !== process.getuid() || (s.mode & 0o077) || s.size > 4 * 1024 * 1024) throw new Error("insecure_grant_record"); + const record = JSON.parse(await f.readFile("utf8")); + if (record.v !== 2 && s.size > 16384) throw new Error("insecure_grant_record"); + return record; + } finally { await f.close(); } +} +export async function writeGrant(root, session, record) { + await secureDir(root, true); await secureDir(path.join(root, "grants"), true); + const file = grantPath(root, session), temp = file + "." + randomBytes(8).toString("hex"); + await fs.writeFile(temp, JSON.stringify(record) + "\n", {flag: "wx", mode: 0o600}); + try { await fs.rename(temp, file); } finally { await fs.rm(temp, {force: true}); } +} +export async function revokeGrant(root, session, turn = null) { + let record; try { record = await readGrant(root, session); } catch (e) { if (e.code === "ENOENT") return; throw e; } + if (turn && record.turn !== turn) return; + await fs.unlink(grantPath(root, session)); +} + +const pendingWrites = new Map(); +function authorizationRequested(value) { + if(typeof value!=="string"||value.length>200||/(?:^|\n)\s*>|```|~~~/.test(value))return false; + let text=value.trim().replace(/[*_`]/g,"").replace(/\s+/g,"").replace(/(?:[,,]?(?:谢谢|麻烦了)|吧|一下)?[。!!]*$/,""); + const scope="(?:(?:本|当前|这个|该|此|这次|本次|本轮)(?:会话|对话|任务|聊天)(?:中|里)?的?|本轮|本次)"; + text=text.replace(/^(?:(?:我)?(?:想要?|希望|需要)|请(?:帮我|帮忙|为我)?|帮我|麻烦(?:帮我)?|我要)/,"").replace(/^(?:我)?(?:申请|请求)/,""); + text=text.replace(new RegExp("^(?:对|为|给|将|让|把)?"+scope),"").replace(/^(?:我)?(?:申请|请求)/,""); + // Match the whole current user request. Questions, explanations, quoted + // examples and instructions to restore masking cannot create applications. + const names="(?:公司名称|公司名|企业名称|企业名|名称)?"; + return new RegExp("^(?:(?:取消|关闭|停止|停用)(?:一下)?(?:对)?(?:"+scope+")?"+names+"脱敏|"+names+"(?:不再|不|不用|无需|不需要)脱敏|原名(?:放行|授权)|(?:放行|允许|保留|使用|允许使用)(?:公司|企业)?原名)$").test(text); +} +const requestDirectory = root => path.join(root,"authorization-requests"); +export async function listAuthorizationRequests(root) { + const dir = requestDirectory(root); + try { await secureDir(root); await secureDir(dir); } catch (error) { if (error.code === "ENOENT") return []; throw error; } + const rows = []; + for (const name of (await fs.readdir(dir)).filter(n => /^[a-f0-9]{64}\.json$/.test(n))) { + const fd = await fs.open(path.join(dir,name),constants.O_RDONLY|constants.O_NOFOLLOW); + try { + const stat = await fd.stat(); + if (!stat.isFile() || stat.uid !== process.getuid() || (stat.mode & 0o077) || stat.size > 4096) continue; + const row = JSON.parse(await fd.readFile("utf8")); + if (row.v === 1 && row.state === "pending" && typeof row.session === "string" && typeof row.workspace === "string" && row.requestedAt > Date.now()-24*60*60*1000) rows.push(row); + } finally { await fd.close(); } + } + return rows.sort((a,b)=>b.requestedAt-a.requestedAt).slice(0,64); +} + +export async function observeAuthorizationRequest(body, ctx) { + const id = sessionIdentity(body,ctx), workspace = sessionWorkspace(body,ctx); + if (!id || !workspace || !authorizationRequested(inspectRequest(body,ctx.protocol).user?.text)) return; + const root = stateRoot(ctx.options?.stateDir), requestId = hash(id.session+"\0"+id.turn); + const previous = pendingWrites.get(root) || Promise.resolve(); + const current = previous.catch(()=>{}).then(async () => { + const dir = requestDirectory(root); await secureDir(root,true); await secureDir(dir,true); + for(const name of (await fs.readdir(dir)).filter(n=>/^[a-f0-9]{64}\.json$/.test(n))){const file=path.join(dir,name),stat=await fs.lstat(file);if(stat.isFile()&&!stat.isSymbolicLink()&&stat.mtimeMs=64)return; + const row = {v:1,id:requestId,...id,workspace,state:"pending",requestedAt:Date.now()}; + try { await fs.writeFile(path.join(dir,requestId+".json"),JSON.stringify(row)+"\n",{flag:"wx",mode:0o600}); } + catch (error) { if (error.code !== "EEXIST") throw error; } + }); + pendingWrites.set(root,current); + try { await current; } finally { if(pendingWrites.get(root)===current)pendingWrites.delete(root); } +} + +export async function closeAuthorizationRequest(root, id) { + if (!/^[a-f0-9]{64}$/.test(id)) throw new Error("invalid_request"); + const dir = requestDirectory(root); await secureDir(dir); + // Keep a small marker so retries of the same user turn do not recreate it. + const file = path.join(dir,id+".json"), fd = await fs.open(file,constants.O_RDONLY|constants.O_NOFOLLOW); + let row; try { row=JSON.parse(await fd.readFile("utf8")); } finally { await fd.close(); } + const temp=file+"."+randomBytes(8).toString("hex"); + await fs.writeFile(temp,JSON.stringify({...row,state:"closed"})+"\n",{flag:"wx",mode:0o600}); + try { await fs.rename(temp,file); } finally { await fs.rm(temp,{force:true}); } +} + +export async function legacyTaskGrants(root) { + const dir=path.join(root,"grants"); + try { await secureDir(root); await secureDir(dir); } catch(error) {if(error.code==="ENOENT")return [];throw error;} + const rows=[]; + for(const name of (await fs.readdir(dir)).filter(n=>/^[a-f0-9]{64}\.json$/.test(n))) { + const fd=await fs.open(path.join(dir,name),constants.O_RDONLY|constants.O_NOFOLLOW); + let session;try{const stat=await fd.stat();if(stat.size>4*1024*1024||!stat.isFile()||stat.uid!==process.getuid()||(stat.mode&0o077))continue;session=JSON.parse(await fd.readFile("utf8")).session;}finally{await fd.close();} + if(typeof session!=="string")continue; + const row=await readGrant(root,session); + if(row.v===2&&row.scope==="session_task"&&row.state==="active"&&row.mode==="original"&&Array.isArray(row.names))rows.push(row); + } + return rows; +} diff --git a/packages/company-guard/src/local-options.mjs b/packages/company-guard/src/local-options.mjs new file mode 100644 index 0000000..7b3f238 --- /dev/null +++ b/packages/company-guard/src/local-options.mjs @@ -0,0 +1,89 @@ +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 {secureDir, stateRoot, configRoot} from "./grant-store.mjs"; +import {validKey} from "./crypto.js"; + +const fields = ["authKey", "receiptReadKey", "authorizationKey"]; +const pluginRoot = fileURLToPath(new URL("..", import.meta.url)).replace(/\/$/, ""); + +async function readPrivate(file, limit = 4096) { + const fd = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW); + try { + const stat = await fd.stat(); + if (!stat.isFile() || stat.uid !== process.getuid() || (stat.mode & 0o077) || stat.size > limit) + throw new Error("company_guard_unsafe_configuration"); + return await fd.readFile("utf8"); + } finally { await fd.close(); } +} + +async function writeTemporary(file, text) { + const temp = file + "." + randomUUID() + ".tmp"; + const fd = await fs.open(temp, "wx", 0o600); + try { await fd.writeFile(text); await fd.sync(); } + catch (error) { await fs.rm(temp, {force:true}); throw error; } + finally { await fd.close(); } + return temp; +} + +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 || ""); +} + +// The Bun hooks, page bridge and synchronous middleware must share the same +// keys. Publish only missing keys into this installation's existing options; +// never put credentials in process arguments or edit another plugin's entry. +async function publishKeys(keys, root) { + const file = path.join(configRoot(), "plugins.json"); + for (let attempt = 0; attempt < 3; attempt++) { + const before = await readPrivate(file, 2 * 1024 * 1024); + let config; + try { config = JSON.parse(before); } catch { throw new Error("company_guard_invalid_registry"); } + const matches = (config.plugins || []).filter(entry => owns(entry.spec)); + if (matches.length !== 1) throw new Error("company_guard_installation_not_unique"); + const entry = matches[0], options = entry.options || {}; + if (stateRoot(options.stateDir) !== root) throw new Error("company_guard_configuration_changed"); + for (const field of fields) if (options[field] !== undefined && options[field] !== keys[field]) + throw new Error("company_guard_key_conflict"); + if (fields.every(field => options[field] === keys[field])) return; + entry.options = {...options, ...keys}; + const temp = await writeTemporary(file, JSON.stringify(config, null, 2) + "\n"); + try { + if (await readPrivate(file, 2 * 1024 * 1024) !== before) continue; + await fs.rename(temp, file); + return; + } finally { await fs.rm(temp, {force:true}); } + } + throw new Error("company_guard_configuration_changed"); +} + +export async function initializeOptions(options = {}) { + for (const field of fields) if (options[field] !== undefined && !validKey(options[field])) + throw new Error("company_guard_invalid_existing_key"); + const root = stateRoot(options.stateDir); + await secureDir(root, true); + const file = path.join(root, "keys.json"); + let keys; + try { keys = JSON.parse(await readPrivate(file)); } + catch (error) { + if (error.code !== "ENOENT") throw new Error("company_guard_invalid_key_file"); + const initial = Object.fromEntries(fields.map(field => [field, options[field] ?? randomBytes(32).toString("hex")])); + const temp = await writeTemporary(file, JSON.stringify(initial) + "\n"); + try { + // Linking a fully written file gives concurrent initializers one winner; + // readers never see an empty or partially written key file. + try { await fs.link(temp, file); } catch (error) { if (error.code !== "EEXIST") throw error; } + } finally { await fs.rm(temp, {force:true}); } + keys = JSON.parse(await readPrivate(file)); + } + if (!keys || fields.some(field => !validKey(keys[field]))) throw new Error("company_guard_invalid_key_file"); + for (const field of fields) if (options[field] !== undefined && options[field] !== keys[field]) + throw new Error("company_guard_key_conflict"); + keys = Object.fromEntries(fields.map(field => [field, keys[field]])); + await publishKeys(keys, root); + Object.assign(options, keys); + return options; +} diff --git a/packages/company-guard/src/policy.js b/packages/company-guard/src/policy.js new file mode 100644 index 0000000..bfaa507 --- /dev/null +++ b/packages/company-guard/src/policy.js @@ -0,0 +1,245 @@ +import { sign, same } from "./crypto.js"; + +export const PROOF = "__nero_company_guard"; +export const TASK_NAME_LIMIT = 65536; +export const TOKEN_PREFIX = "[[NERO_ORG_"; +export function normalPrompt(s) { return typeof s === "string" ? s.replace(/\r\n/g, "\n").trim() : ""; } + +export function directive(prompt) { + const first = normalPrompt(prompt).split("\n", 1)[0]; + if (first.length > 600) return null; + const m = /^(本轮允许原名|本次允许原名|本轮不脱敏|本次不脱敏|允许原名|不脱敏|联网核查|互联网核查|互联核查)\s*[::]\s*(.+)$/.exec(first); + if (!m) return null; + const names = m[2].replace(/[。.]$/, "").split(/[;;、]/).map(s => s.trim()); + if (!names.length || names.length > 32 || names.some(s => !validName(s) || /^(所有|全部|任何|all|\*)$/i.test(s) || /[\n<>??!!]/.test(s))) return null; + return {mode: /核查$/.test(m[1]) ? "public_lookup" : "original", names: [...new Set(names)]}; +} + +export function identity(body) { + const c = body && body.client_metadata; + if (!c || typeof c !== "object") return null; + let m = c["x-codex-turn-metadata"] || c; + if (typeof m === "string") { try { m = JSON.parse(m); } catch { return null; } } + const ok = x => typeof x === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{1,127}$/.test(x); + if (!m || !ok(m.thread_id) || !ok(m.turn_id) || m.thread_source !== "user") return null; + return {thread: m.thread_id, turn: m.turn_id}; +} + +// The host supplies origin/session. Never recover ownership from prompt text. +export function taskSession(body, ctx) { + if (!["local", "magpie-key"].includes(ctx?.origin) || ctx?.agent !== "codex" || + !/^[A-Za-z0-9][A-Za-z0-9_-]{1,127}$/.test(ctx?.session || "")) return null; + const c = body?.client_metadata; + let m = c?.["x-codex-turn-metadata"] || c; + if (typeof m === "string") { try { m = JSON.parse(m); } catch { return null; } } + if (m && typeof m !== "object") return null; + // A human can explicitly authorize an existing chat created by an agent. + // Its exact host session still needs a local task record and genuine user turn. + if (m?.thread_source && !["user", "agent_created_thread"].includes(m.thread_source)) return null; + if (m?.thread_id && m.thread_id !== ctx.session) return null; + return ctx.session; +} + +export function readProof(proof, body, key, ctx) { + if (!proof || typeof proof.payload !== "string" || proof.payload.length > 2 * 1024 * 1024 || !same((ctx?.sign || sign)(key, proof.payload), proof.mac)) return null; + let p; try { p = JSON.parse(proof.payload); } catch { return null; } + if (p.v === 1 && proof.payload.length > 12000) return null; + const id = identity(body), now = Date.now(); + if (!Number.isFinite(p.expires) || p.expires <= now || p.expires > now + 15000) return null; + const session = taskSession(body, ctx); + const task = p.v === 2 && p.scope === "session_task" && !!session && p.thread === session; + if (!task && (!id || p.v !== 1 || p.thread !== id.thread || p.turn !== id.turn)) return null; + if (!["original", "public_lookup"].includes(p.mode) || !Array.isArray(p.names) || p.names.length > (task ? TASK_NAME_LIMIT : 32) || p.names.some(n => !validName(n))) return null; + return p; +} + +export function validName(s) { + return typeof s === "string" && s.length >= 2 && s.length <= 120 && !/^\s|\s$/.test(s) && /[A-Za-z\u00c0-\u024f\u3400-\u9fff]/.test(s) && !/[\x00-\x1f]/.test(s) && !s.includes(TOKEN_PREFIX); +} + +export function configuredNames(options) { + const out = []; + for (const c of options.companies || []) { + if (typeof c === "string") out.push(c); + else if (c && typeof c === "object") { out.push(c.name); if (Array.isArray(c.aliases)) out.push(...c.aliases); } + } + if (out.length > 512 || out.some(n => !validName(n))) throw new Error("invalid_company_options"); + return [...new Set(out)]; +} + +export function expandAllowed(names, options) { + const out = new Set(names); + for (const c of options.companies || []) { + if (!c || typeof c !== "object") continue; + const group = [c.name, ...(Array.isArray(c.aliases) ? c.aliases : [])]; + if (group.some(n => out.has(n))) for (const n of group) if (validName(n)) out.add(n); + } + return out; +} + +export function environmentText(s) { + const t = s.trim(); + return t.startsWith("") || t.startsWith("") || t.startsWith("# AGENTS.md instructions for "); +} + +// Exact tool names only. Generic execution is not evidence of a public source. +export function webTool(name) { + return ["web.run", "web__run", "functions.web__run", "mcp__codex_apps__search_service__web_search", "mcp__codex_apps__search_service__search", "mcp__codex_apps__search_service__browse"].includes(name); +} + +const LEGAL_NAME = /[\u3400-\u9fffA-Za-z0-9((][\u3400-\u9fffA-Za-z0-9()()·&..\-]{1,79}?(?:股份有限公司|有限责任公司|有限公司|股份公司|集团公司)/; +// Fold suffix letters only; keep the existing capitalized-name start and bounds. +// Lowercase limited is also an adjective. Explicit name fields and configured +// names can still declare that spelling; ordinary prose retains a capital L. +const ENGLISH_KIND = /(?:Co\.,?[ \t]+Ltd\.?|Corporation|Corp\.?|Incorporated|Inc\.?|Limited|Ltd\.?|LLC|L\.L\.C\.|PLC|GmbH)/.source.replace(/\\.|Limited|[A-Za-z]/g, value => value === "Limited" ? "L[Ii][Mm][Ii][Tt][Ee][Dd]" : value.length === 1 ? `[${value.toUpperCase()}${value.toLowerCase()}]` : value); +const KIND_SUFFIX = /(?:股份有限公司|有限责任公司|有限公司|股份公司|集团公司|集团|公司)$/; +const GENERIC_PARTS = /(?:非上市|拟上市|非公众|供应商|交易对手|发行人|保荐人|可比|其他|任何|所有|全部|上述|相关|目标|项目|主体|企业|真实|实际|一般|普通|外部|内部|境内|境外|国内|国外|上市|公众|有限|股份|母子|集团|关联|同控|控股|参股|全资|被投|投资|持股|合作|客户|这家|那家|本|贵|该|各|某|母|子|孙)/g; +const FIELD_DESCRIPTION = /的(?:公司|集团)$|避免|当作|当成|没有|并非|不是|是否|能否|不能|不应|不要|只对|仅对|包含|保留|保护|替换|脱敏|识别|显示|看到|查看|核实|确认|表示|说明|继续|启动|存在|属于|涉及|上传|下载|配置|插件|页面|功能|工具|规则|名称|原名|本轮|本次|字段|提示词|样本|包括|以及|而非|等非|某个|某家|一家|一个|哪些|这些|这种|这类|用于|构成|均以|通过|提供的/; +const cleanName = name => name.replace(/^.*(?:映射最初包含|另查到|单独归入)/, "").replace(/^(?:(?:请帮我|帮我|请|查询|核查|分析|关于|公司名为|客户为|供应商为|交易对手为|以及|来自))+/, ""); +const genericName = name => name.replace(KIND_SUFFIX, "").replace(GENERIC_PARTS, "") === ""; + +// Explicit name fields can carry short names. Generic roles and instructions +// are not names; configured names and aliases remain independent of this gate. +export function nameFieldValue(text, field = "") { + if (typeof text !== "string") return null; + const name = text.trim(); + if (!validName(name) || genericName(name)) return null; + if (/^(?:unknown|none|null|n\/a|string|number|boolean|object|array)$/i.test(name)) return null; + const full = LEGAL_NAME.exec(name); + if (full && full[0] === name) return name; + // Bare role keys also appear in code/table maps. Explicit name fields and + // configured names may still declare a name with this spelling. + if (/^(?:company|customer|supplier|counterparty)$/i.test(field) && /^(?:[A-Za-z_][A-Za-z0-9_]*\.)*[a-z][a-z0-9]*(?:_[a-z0-9]+)+$/.test(name)) return null; + return FIELD_DESCRIPTION.test(name) ? null : name; +} + +function recognitionText(text, quotes = false) { + // Consume unmatched backslash runs too, so nested JSON stays linear to scan. + return text.replace(/\\+(r\\+n|[nrt"])?/g, (raw, escaped) => !escaped ? raw : escaped === '"' ? (quotes ? '"' : raw) : "\n"); +} + +const LEGAL_HINT = /有限公司|有限责任公司|股份公司|集团公司/; +const ENGLISH_HINT = new RegExp("[ ,](?:"+ENGLISH_KIND+")\\b"); +const FIELD_HINT = /company|customer|supplier|counterparty|entity_name|公司名称|客户名称|供应商名称|交易对手名称/i; + +function scanLegalNames(text, visit) { + const suffixes = ["股份有限公司","有限责任公司","有限公司","股份公司","集团公司"]; + const next = suffixes.map(s=>text.indexOf(s)); + const legal = new RegExp(LEGAL_NAME.source,"g"); + let after = 0; + for (;;) { + let k = -1; + for (let i=0;i=0 && (k<0 || next[i]=0 && next[i] { if (validName(s)) out.push(s); }; + const legalHint = LEGAL_HINT.test(text), englishHint = ENGLISH_HINT.test(text), fieldHint = FIELD_HINT.test(text); + if (!legalHint && !englishHint && !fieldHint) return out; + // Normalize escaped separators only in the recognition view. Original text, + // numeric lexemes and the request's restoration map are never rewritten here. + text = recognitionText(text); + // Ordinary prose needs a legal company suffix. Bare 公司/集团 endings no + // longer declare names; explicit fields and configured aliases still do. + if (legalHint) scanLegalNames(text,m => { + let name = cleanName(m[0]); + // A quoted user definition can be followed by 与 + the contracting entity. + // Do not strip 与 from a company name outside that grammatical context. + if (name.startsWith("与") && /(?:用户|您|你|贵方)[”"」』]?[))]$/.test(text.slice(Math.max(0, m.index - 24), m.index).trimEnd().replace(/\\+(?=")/g, ""))) name = name.slice(1); + if (!genericName(name)) add(name); + }); + const en = new RegExp(/\b[A-Z][A-Za-z0-9&.'’-]*(?:[ \t]+[A-Za-z0-9&.'’-]+){0,7}[ ,]+/.source + ENGLISH_KIND + /\b\.?/.source, "g"); + for (const m of englishHint ? text.matchAll(en) : []) { + // A standard disclaimer phrase is not a company named Limited. + if (!/\bBUT\s+NOT\s+LIMITED\.?$/i.test(m[0])) add(m[0]); + } + const fields = /(?:"(company(?:_name)?|customer(?:_name)?|supplier(?:_name)?|counterparty(?:_name)?|entity_name|公司名称|客户名称|供应商名称|交易对手名称)"\s*:\s*"((?:[^"\\]|\\.)*)"|(?:公司名称|客户名称|供应商名称|交易对手名称)[::]\s*([^\n,,;;|\t]{2,120}))/gi; + for (const m of fieldHint ? text.matchAll(fields) : []) { + if (m[2] !== undefined) { try { const name = nameFieldValue(JSON.parse('"' + m[2] + '"'), m[1]); if (name) add(name); } catch { /* Malformed data cannot declare a name. */ } } + else { const name = nameFieldValue(m[3]); if (name) add(name); } + } + return [...new Set(out)]; +} + +// Rebuild aliases from visible task material; no learned global dictionary. +// Definitions cannot change an original-name grant or another request's state. +export function taskAliases(slots) { + const relations = new Map(), blocked = new Set(); + const generic = /^(?:我们|我方|对方|双方|各方|甲方|乙方|丙方|用户|您|你|本平台|本服务|本产品|本项目|本系统|平台|服务|产品|游戏|项目|系统|科技|电子|信息|中国|简称|全称|co|corp|inc|ltd|llc)$/i; + const quoted = /^[“"「『]([^”"」』]{2,40})[”"」』]/; + for (const slot of slots) { + if (!["user", "tool"].includes(slot.source)) continue; + const original = slot.owner[slot.key]; + if (environmentText(original)) continue; + const text = recognitionText(original.replace(/```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$)|`[^`\n]*`/g, "\n"), true); + const definitions = /[((,,][ \t]*(?:(?:以下|下文)(?:简称|亦称|称)|简称(?:为)?)[ \t]*[::]?[ \t]*(?=[“"「『])/g; + for (const marker of text.matchAll(definitions)) { + const prefix = text.slice(Math.max(0, marker.index - 180), marker.index).trimEnd(); + const full = detectNames(prefix).filter(n => prefix.endsWith(n) && (LEGAL_NAME.test(n) || /(?:Corporation|Corp\.?|Incorporated|Inc\.?|Limited|Ltd\.?|LLC|L\.L\.C\.|PLC|GmbH)$/i.test(n))).sort((a, b) => b.length - a.length)[0]; + if (!full || /(?:例如|示例|举例|样例|例子|假设|虚构)/.test(prefix.slice(prefix.lastIndexOf("\n") + 1, -full.length))) continue; + let tail = text.slice(marker.index + marker[0].length, marker.index + marker[0].length + 180); + for (let count = 0; count < 4; count++) { + const match = quoted.exec(tail); + if (!match) break; + const alias = match[1].trim(); + if (/^[\u3400-\u9fffA-Za-z0-9][\u3400-\u9fffA-Za-z0-9 &·.\-]{1,31}$/.test(alias) && nameFieldValue(alias) && !generic.test(alias) && alias.toLowerCase() !== full.toLowerCase()) { + const key = alias.toLowerCase(), prior = relations.get(key); + if (prior && prior.full.toLowerCase() !== full.toLowerCase()) blocked.add(key); + else relations.set(key, {alias, full}); + // Never accept an early subset while skipping possible conflicts. + if (relations.size > 128) return {names: [], conflicts: blocked.size, limited: true}; + } + const rest = tail.slice(match[0].length), next = /^[ \t]*(?:或|、|及|和|\/)[ \t]*(?=[“"「『])/.exec(rest); + if (!next) break; + tail = rest.slice(next[0].length); + } + } + } + return {names: [...relations].filter(([key]) => !blocked.has(key)).map(([, value]) => value.alias), conflicts: blocked.size, limited: false}; +} + +export function escapeRE(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } + +// Share common prefixes rather than making the engine retry thousands of +// complete names at each character. Longer names still take precedence. +export function namePattern(names) { + const root = new Map(); + for (const name of names.slice().sort((a,b)=>b.length-a.length)) { + let node = root; + for (const c of name) { + const upper = c.length === 1 ? c.toUpperCase() : c; + const key = upper.length === 1 && !(c.charCodeAt(0) >= 128 && upper.charCodeAt(0) < 128) ? upper : c; + if (!node.has(key)) node.set(key,new Map()); + node = node.get(key); + } + node.set("",null); + } + const render = node => { + let prefix = ""; + while (node.size === 1 && !node.has("")) { + const [c,next] = node.entries().next().value; + prefix += escapeRE(c); node = next; + } + const branches = []; + for (const [c,next] of node) if (c) branches.push(escapeRE(c)+render(next)); + if (node.has("")) branches.push(""); + return prefix + (branches.length > 1 ? "(?:"+branches.join("|")+")" : branches[0] || ""); + }; + return render(root); +} diff --git a/packages/company-guard/src/protocols.js b/packages/company-guard/src/protocols.js new file mode 100644 index 0000000..e6a7010 --- /dev/null +++ b/packages/company-guard/src/protocols.js @@ -0,0 +1,109 @@ +import { environmentText, webTool } from "./policy.js"; + +const NAME_FIELD = /^(?:company(?:_name)?|customer(?:_name)?|supplier(?:_name)?|counterparty(?:_name)?|entity_name|公司名称|客户名称|供应商名称|交易对手名称)$/i; +const OPAQUE_FIELD = /^(?:id|type|role|tool_call_id|tool_use_id|call_id|signature|encrypted_content|data|image_url|file_data|file_id|mime_type|mimeType|media_type)$/; + +export function inspectRequest(body, protocol) { + const slots = [], records = [], calls = Object.create(null); + let nodes = 0; + const add = (owner, key, meta = {}) => { if (typeof owner?.[key] === "string") slots.push({owner, key, ...meta}); }; + const data = (value, meta, depth = 0) => { + if (++nodes > 50000 || depth > 48) throw new Error("input_structure_limit"); + if (!value || typeof value !== "object") return; + for (const k of Object.keys(value)) { + if (OPAQUE_FIELD.test(k)) continue; + if (typeof value[k] === "string") add(value, k, {...meta, nameField: NAME_FIELD.test(k) ? k : null}); + else data(value[k], meta, depth + 1); + } + }; + const blocks = (value, meta, depth = 0) => { + if (++nodes > 50000 || depth > 48) throw new Error("input_structure_limit"); + if (!Array.isArray(value)) { data(value, meta, depth + 1); return; } + for (const p of value) { + if (!p || typeof p !== "object") continue; + if (["text", "input_text", "output_text", "summary_text", "reasoning_text"].includes(p.type) || (!p.type && typeof p.text === "string")) add(p, "text", meta); + else if (p.type === "thinking") add(p, "thinking", {...meta, sealed: !!p.signature}); + else if (p.type === "tool_result") { + const m = {...meta, source: "tool", tool: calls[p.tool_use_id] || ""}; + if (typeof p.content === "string") add(p, "content", m); else blocks(p.content, m, depth + 1); + } else if (p.type === "tool_use") data(p.input, {...meta, source: "call", tool: p.name || ""}, depth + 1); + else if (p.type === "resource") { if (p.resource) add(p.resource, "text", meta); } + else if (p.functionCall) data(p.functionCall.args, {...meta, source: "call", tool: p.functionCall.name || ""}, depth + 1); + else if (p.functionResponse) data(p.functionResponse.response, {...meta, source: "tool", tool: p.functionResponse.name || ""}, depth + 1); + else if (p.type === "input_file" || p.type === "file") add(p, "filename", meta); + } + }; + + let list; + if (protocol === "responses") list = Array.isArray(body.input) ? body.input : []; + else if (protocol === "gemini") list = Array.isArray(body.contents) ? body.contents : []; + else list = Array.isArray(body.messages) ? body.messages : []; + for (const m of list) { + if (!m || typeof m !== "object") continue; + if (m.type === "function_call" || m.type === "custom_tool_call") calls[m.call_id] = m.name || ""; + for (const c of m.tool_calls || []) if (c) calls[c.id] = c.function?.name || ""; + for (const p of Array.isArray(m.content) ? m.content : []) if (p?.type === "tool_use") calls[p.id] = p.name || ""; + } + if (protocol === "responses" && typeof body.input === "string") { + add(body, "input", {source: "user", index: 0}); records.push({index: 0, role: "user", text: body.input}); + } + for (let index = 0; index < list.length; index++) { + const m = list[index]; if (!m || typeof m !== "object") continue; + const source = ["system", "developer"].includes(m.role) ? "instruction" : m.role === "user" ? "user" : ["tool", "function"].includes(m.role) ? "tool" : "assistant"; + const meta = {source, index, tool: calls[m.tool_call_id] || (source === "tool" ? m.name || "" : "")}; + const before = slots.length; + if (typeof m.content === "string") add(m, "content", meta); else blocks(m.content, meta); + blocks(m.parts, meta); + if (m.type === "function_call_output" || m.type === "custom_tool_call_output") { + const sm = {...meta, source: "tool", tool: calls[m.call_id] || ""}; + if (typeof m.output === "string") add(m, "output", sm); else data(m.output, sm); + } else if (m.type === "function_call") add(m, "arguments", {...meta, source: "call", tool: m.name || "", json: true}); + else if (m.type === "custom_tool_call") add(m, "input", {...meta, source: "call", tool: m.name || ""}); + else if (m.type === "reasoning") blocks(m.summary, {...meta, source: "assistant"}); + for (const c of m.tool_calls || []) if (c?.function) add(c.function, "arguments", {...meta, source: "call", tool: c.function.name || "", json: true}); + if (m.function_call) add(m.function_call, "arguments", {...meta, source: "call", tool: m.function_call.name || "", json: true}); + const own = slots.slice(before).filter(s => s.source === "user" && s.index === index).map(s => s.owner[s.key]).join("\n"); + records.push({index, role: m.role || m.type || "unknown", text: own}); + } + 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 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 (typeof v[k] === "object") schema(v[k], depth + 1); + } + }; + schema(body.tools); + const user = records.filter(r => r.role === "user" && r.text && !environmentText(r.text)).at(-1) || null; + return {slots, records, user}; +} + +export function publicContextSafe(view, allowed) { + if (!view.user) return false; + for (const r of view.records) { + if (r.index >= view.user.index || ["system", "developer"].includes(r.role)) continue; + if (r.role !== "user" || !environmentText(r.text)) return false; + } + for (const s of view.slots) { + if ((s.source === "instruction" || s.index < view.user.index) && [...allowed].some(n => s.owner[s.key].includes(n))) return false; + if (["tool", "call"].includes(s.source) && !webTool(s.tool)) return false; + } + return true; +} + +export function safeInput(body, protocol) { + let nodes = 0; + const walk = (v, depth) => { + if (++nodes > 80000 || depth > 64) throw new Error("input_structure_limit"); + if (typeof v === "number" && Number.isInteger(v) && !Number.isSafeInteger(v)) throw new Error("unsafe_numeric_value"); + if (!v || typeof v !== "object") return; + for (const k of Object.keys(v)) walk(v[k], depth + 1); + }; + walk(body, 0); + // Preserve remote context, reasoning and client cache controls. Previously + // transmitted originals cannot be revoked by rewriting a later request. +} diff --git a/packages/company-guard/src/receipt-details.mjs b/packages/company-guard/src/receipt-details.mjs new file mode 100644 index 0000000..e315f22 --- /dev/null +++ b/packages/company-guard/src/receipt-details.mjs @@ -0,0 +1,32 @@ +// Viewer-only mapping. Never serialized to disk, sent upstream or used to mask +// another request. Keeping this optional view must not change request behavior. +const entries = new Map(); +const ttl = 30 * 60 * 1000, maxEntries = 25, maxBytes = 2 * 1024 * 1024; +let used = 0; +function remove(key) { + const entry = entries.get(key); if (!entry) return; + clearTimeout(entry.timer); used -= entry.bytes; entries.delete(key); +} +export function rememberDetails(root, receipt, reverse) { + try { + const pairs = Object.entries(reverse || {}).map(([token, original]) => ({original, token})); + const bytes = pairs.reduce((n,p) => n + 2 * (p.original.length + p.token.length), 0); + if (bytes > maxBytes) return; + const key = root + "\0" + receipt.id; + remove(key); + while (entries.size && (entries.size >= maxEntries || used + bytes > maxBytes)) remove(entries.keys().next().value); + const entry = {task:receipt.task, thread:receipt.thread, pairs, bytes, expiresAt:Date.now()+ttl}; + entry.timer = setTimeout(() => remove(key),ttl); entry.timer.unref(); + entries.set(key,entry); used += bytes; + } catch { /* The view is optional; never interrupt masking. */ } +} +export function readDetails(root, id) { + const key=root + "\0" + id, entry=entries.get(key); + if (!entry || entry.expiresAt <= Date.now()) {remove(key);return {available:false};} + return {available:true, task:entry.task, thread:entry.thread, pairs:entry.pairs, expiresAt:entry.expiresAt}; +} + +export function retainDetails(root, ids) { + const prefix = root + "\0"; + for (const key of entries.keys()) if (key.startsWith(prefix) && !ids.has(key.slice(prefix.length))) remove(key); +} diff --git a/packages/company-guard/src/receipt-report.mjs b/packages/company-guard/src/receipt-report.mjs new file mode 100644 index 0000000..95c839c --- /dev/null +++ b/packages/company-guard/src/receipt-report.mjs @@ -0,0 +1,61 @@ +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"; + +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"); + if (task && !/^(?:[a-f0-9-]{36}|id-[a-f0-9]{24})$/i.test(task)) throw new Error("invalid_task"); + const parse = s => { try { return JSON.parse(s); } catch { return null; } }; + const current = (await readTail(path.join(root,"receipts",day+".jsonl"))).split("\n").map(parse).filter(Boolean); + const grouped = new Map(); + for (const row of [...records, ...current]) { + if (!/^[a-f0-9-]{36}$/i.test(row?.id || "") || row.startedAt?.slice(0,10) !== day || !["prepared", "response_observed", "request_checked", "reply_processed"].includes(row.phase)) continue; + if (task && row.task !== task && row.thread !== task) continue; + const g = grouped.get(row.id) || {}; + g[row.phase] = row; grouped.set(row.id,g); + } + const log = await readTail(appLog || path.join(os.homedir(),"Library","Logs","magpie","app.log"),4*1024*1024); + for (const row of await readReceiptConfirmations(grouped.keys(), appLog, log)) grouped.get(row.id)[row.phase] = row; + const middleware = " middleware " + path.resolve(fileURLToPath(new URL("..", import.meta.url))) + " [error]: "; + const errors = []; + for (const line of log.split("\n")) { + const errorAt = line.indexOf(middleware); + if (errorAt >= 0) { + const match = /^(onRequest|onAccount|onProvider|onEvent|onResponse): (.*)$/.exec(line.slice(errorAt + middleware.length)); + const at = new Date(line.slice(0,19).replaceAll("/","-").replace(" ","T")); + if (match && Number.isFinite(at.getTime()) && at.toISOString().slice(0,10) === day) errors.push({at:at.toISOString(), hook:match[1], code:match[2] === "took too long" ? "callback_timeout" : "callback_error", requestId:null}); + } + } + const rows = [...grouped.entries()].map(([id,g]) => { + const p = g.prepared, reply = g.response_observed; + const streamComplete = g.request_checked?.ok === true && g.reply_processed?.ok === true && g.reply_processed.reason === "processed" && ["response.completed", "message_stop", "chat.completed", "gemini.completed"].includes(g.reply_processed.eventType) && reply?.hostCompletionObserved !== false; + const hostComplete = reply?.hostCompletionObserved === true && reply.replyCaptured === true; + const completionSource = hostComplete ? "host" : streamComplete ? "stream" : null; + let status = "未确认"; + if (p?.status === "failed" || (g.reply_processed?.ok === false && g.reply_processed.reason !== "upstream_incomplete") || reply?.remainingCurrentPlaceholders > 0) status = "处理失败"; + else if (["replaced","authorized","no_match"].includes(p?.status) && g.request_checked?.ok && g.reply_processed?.ok && completionSource) status = p?.status === "replaced" ? "已替换,回复处理完成" : p?.status === "authorized" ? "授权放行" : "未命中"; + let statusCode, statusLabel, statusReason; + if (status === "处理失败") { + statusCode = p?.status === "failed" ? "preparation_failed" : reply?.remainingCurrentPlaceholders > 0 ? "restoration_residue" : "reply_processing_failed"; + statusLabel = status; statusReason = statusCode === "preparation_failed" ? "输入保护准备失败。" : statusCode === "restoration_residue" ? "已采集的回复仍有本次名称代号。" : "插件记录了回复处理未成功;需核对调用终止原因。"; + } else if (status !== "未确认") { + statusCode = "completed"; statusLabel = status; statusReason = completionSource === "stream" ? "同步检查、回复处理和正常流式结束事件均已确认;独立完成通知未保留。" : "准备、同步检查、回复处理和宿主完成记录均已核对。"; + } else if (reply?.hostCompletionObserved === false || g.reply_processed?.reason === "upstream_incomplete") { + statusCode = "call_incomplete"; statusLabel = "调用未完成"; statusReason = "宿主未取得完整回复;可能为调用取消、上游失败、回复不完整或采集超限,不能直接判为还原故障。"; + } else if (!p) { + statusCode = "preparation_missing"; statusLabel = "准备回执缺失"; statusReason = "未取得输入保护的准备记录。"; + } else if (!g.request_checked?.ok) { + statusCode = "request_confirmation_missing"; statusLabel = "同步确认缺失"; statusReason = "缺少同步检查确认,不能认定输入保护已完成。"; + } else if (reply?.hostCompletionObserved && !reply.replyCaptured) { + statusCode = "reply_capture_missing"; statusLabel = "回复采集缺失"; statusReason = "宿主报告完成,但未取得可核对的回复副本。"; + } else if (reply?.hostCompletionObserved && !g.reply_processed) { + statusCode = "reply_confirmation_missing"; statusLabel = "回复确认缺失"; statusReason = "宿主已完成且已采集回复,但缺少插件处理确认;不能仅凭代号残留为零认定还原成功。"; + } 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)}; + }).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;日志轮转或宿主限流可能造成确认缺失"]}; +} diff --git a/packages/company-guard/src/receipts.mjs b/packages/company-guard/src/receipts.mjs new file mode 100644 index 0000000..9c9e012 --- /dev/null +++ b/packages/company-guard/src/receipts.mjs @@ -0,0 +1,148 @@ +import fs from "node:fs/promises"; +import {constants} from "node:fs"; +import path from "node:path"; +import os from "node:os"; +import {createHash, randomUUID} from "node:crypto"; +import {retainDetails} from "./receipt-details.mjs"; +import {secureDir, stateRoot} from "./grant-store.mjs"; + +export const RECEIPT_VERSION = "0.4.3"; +const writes = new Map(); +export const RECEIPT_LIMIT = 25; + +// Only confirmation metadata crosses from the synchronous middleware's log. +export function receiptCheckpoint(row) { + if (!/^[a-f0-9-]{36}$/i.test(row?.id || "") || !["request_checked", "reply_processed"].includes(row.phase) || typeof row.ok !== "boolean") return null; + return {id:row.id, phase:row.phase, ok:row.ok, + reason:["processed", "upstream_incomplete", "restoration_incomplete"].includes(row.reason) ? row.reason : undefined, + eventType:["response.completed", "response.failed", "response.incomplete", "message_stop", "chat.completed", "gemini.completed", "error"].includes(row.eventType) ? row.eventType : undefined, + restoredNames:Number.isSafeInteger(row.restoredNames) && row.restoredNames >= 0 ? row.restoredNames : null}; +} + +export async function readReceiptConfirmations(ids, appLog, text) { + const rows = [], selected = new Set(ids), marker = "NERO_COMPANY_GUARD_RECEIPT "; + const log = text ?? await readTail(appLog || path.join(os.homedir(), "Library", "Logs", "magpie", "app.log"), 4*1024*1024); + for (const line of log.split("\n")) { + const i = line.indexOf(marker); if (i < 0) continue; + try { const row = receiptCheckpoint(JSON.parse(line.slice(i + marker.length))); if (row && selected.has(row.id)) rows.push(row); } catch {} + } + return rows; +} + +// The official plugin host is the writer. Serialize its concurrent callbacks, +// 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)); + writes.set(root, next); + next.finally(() => { if (writes.get(root) === next) writes.delete(root); }).catch(() => {}); + return next; +} + +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 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)) { + const checkpoint = receiptCheckpoint(row); if (!checkpoint) throw new Error("invalid_receipt_checkpoint"); + row = {v:1, ...checkpoint, startedAt:row.startedAt}; + } + const group = groups.get(row.id) || {startedAt:row.startedAt, phases:new Map()}; + if (group.startedAt !== row.startedAt) throw new Error("receipt_time_mismatch"); + group.phases.set(row.phase, row); groups.set(row.id, group); + }; + for (const name of files) { + const fd = await fs.open(path.join(dir,name), constants.O_RDONLY | constants.O_NOFOLLOW); + try { + 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)); + } finally { await fd.close(); } + } + if (incoming) add(incoming); + // Save observed confirmations before pruning. A rotated log cannot undo them. + // An unavailable log must not prevent the hook's own receipt from being saved. + try { for (const row of await readReceiptConfirmations(groups.keys(), appLog)) add({...row, startedAt:groups.get(row.id).startedAt}); } catch {} + // Rank by request start, never by arrival of a late completion callback. + const kept = [...groups].sort((a,b) => b[1].startedAt.localeCompare(a[1].startedAt) || b[0].localeCompare(a[0])).slice(0,RECEIPT_LIMIT); + const output = new Map(); + for (const [,group] of kept) for (const row of group.phases.values()) { + const name = row.startedAt.slice(0,10)+".jsonl"; + output.set(name,(output.get(name)||"")+JSON.stringify(row)+"\n"); + } + // Persist retained data before removing any obsolete daily file. + for (const [name,text] of output) { + if (originals.get(name) === text) continue; + const file = path.join(dir,name), temp = file+"."+randomUUID()+".tmp"; + const fd = await fs.open(temp, "wx", 0o600); + try { await fd.writeFile(text); await fd.sync(); } finally { await fd.close(); } + try { await fs.rename(temp,file); } finally { await fs.rm(temp,{force:true}); } + } + 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))); + return {retained:kept.length,removed:groups.size-kept.length}; +} +const opaqueId = value => { + if (typeof value !== "string" || !value) return null; + return /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value) ? value : "id-" + createHash("sha256").update(value).digest("hex").slice(0,24); +}; +export function newReceipt(ctx, identity) { + return {v: 1, id: randomUUID(), task: opaqueId(ctx.session || identity?.thread), thread: opaqueId(identity?.thread), turn: opaqueId(identity?.turn), agent:receiptAgent(ctx.agent), version: RECEIPT_VERSION, protocol: ["chat","responses","anthropic","gemini"].includes(ctx.protocol) ? ctx.protocol : "unknown", startedAt: new Date().toISOString()}; +} + +export const receiptAgent = value => typeof value === "string" && /^[a-z0-9][a-z0-9._-]{0,63}$/i.test(value) ? value : null; + +// Whitelist every persisted field. No exception text, names, tokens or prompts. +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()}; + if (phase === "prepared") { + row.status = ["replaced", "no_match", "authorized", "failed"].includes(details.status) ? details.status : "failed"; + row.errorCode = details.error ? "preparation_failed" : null; + row.processingMs = count(details.processingMs); + row.matchedNames = count(details.metrics?.matchedNames); + row.replacedNames = count(details.metrics?.replacedNames); + row.replacements = count(details.metrics?.replacements); + row.allowedOccurrences = count(details.metrics?.allowedOccurrences); + row.authorization = ["original", "public_lookup", "masked"].includes(details.metrics?.authorization) ? details.metrics.authorization : "masked"; + row.authorizationCoverage = ["all","names","none"].includes(details.metrics?.authorizationCoverage) ? details.metrics.authorizationCoverage : "none"; + const reason = details.metrics?.authorizationReason; + row.authorizationReason = typeof reason === "string" && /^[a-z_]{1,64}$/.test(reason) ? reason : "unknown"; + row.taskAliases = count(details.metrics?.taskAliases); + row.aliasConflicts = count(details.metrics?.aliasConflicts); + row.aliasLimitReached = details.metrics?.aliasLimitReached === true; + row.scopes = {}; + for (const k of ["user", "history", "instructions", "tool_results", "tool_arguments", "tool_schema"]) { + const s = details.metrics?.scopes?.[k]; + if (s) row.scopes[k] = {checkedTexts: count(s.checkedTexts), replacements: count(s.replacements)}; + } + } else if (phase === "response_observed") { + row.hostCompletionObserved = details.success === true; + row.replyCaptured = details.replyCaptured === true; + row.remainingCurrentPlaceholders = count(details.remaining); + } else return; + await retainReceipts(stateRoot(ctx.options?.stateDir), row, ctx.options?.appLog); + } catch { + // Receipt failure must never turn a model request into a failure. + try { console.warn("company_guard_receipt_write_failed"); } catch {} + } +} + +export async function readTail(file, bytes = 8 * 1024 * 1024) { + 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()) return ""; + const start = Math.max(0, stat.size - bytes), buf = Buffer.alloc(Math.min(bytes, stat.size)); + const {bytesRead} = await fd.read(buf, 0, buf.length, start); + const text = buf.subarray(0, bytesRead).toString("utf8"); + return start ? text.slice(text.indexOf("\n") + 1) : text; + } catch (e) { if (e.code === "ENOENT") return ""; throw e; } + finally { await fd?.close(); } +} diff --git a/packages/company-guard/src/session-authorization.js b/packages/company-guard/src/session-authorization.js new file mode 100644 index 0000000..ee92e93 --- /dev/null +++ b/packages/company-guard/src/session-authorization.js @@ -0,0 +1,67 @@ +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 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; + if (typeof meta === "string") { try { meta = JSON.parse(meta); } catch { return null; } } + if (!meta || !["user", "agent_created_thread"].includes(meta.thread_source) || !validId(meta.thread_id) || !validId(meta.turn_id)) return null; + if (ctx.session && ctx.session !== meta.thread_id) return null; + return {session: meta.thread_id, turn: meta.turn_id}; +} + +// Codex states its current directory in its own environment block. Tool output +// and assistant messages cannot supply the directory for a session grant. +export function sessionWorkspace(body, ctx) { + if (typeof ctx?.cwd === "string" && ctx.cwd.startsWith("/")) return ctx.cwd.replace(/\/$/, "") || "/"; + let workspace = ""; + for (const item of body?.input || body?.messages || []) { + if (!["user", "developer", "system"].includes(item?.role)) continue; + const texts = typeof item.content === "string" ? [item.content] : (Array.isArray(item.content) ? item.content : []).filter(p => ["text", "input_text", "output_text"].includes(p?.type)).map(p => p.text || ""); + for (const text of texts) { + for (const block of text.matchAll(/[\s\S]*?<\/environment_context>/g)) { + const cwd = /\s*([^<\n]+?)\s*<\/cwd>/.exec(block[0])?.[1]; + if (cwd?.startsWith("/")) workspace = cwd.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/\/$/, "") || "/"; + } + } + } + return workspace; +} + +export function signAuthorization(record, key) { + const {names,pattern="",...header}=record; + const payload = JSON.stringify({...header,nameCount:names.length,contentsHash:digest(JSON.stringify({names,pattern}))}); + if (payload.length > 2 * 1024 * 1024 || !validKey(key)) throw new Error("authorization_too_large"); + return {session:record.session, payload, mac:sign(key, PREFIX + payload),names,pattern}; +} + +export function readAuthorization(envelope, key, verifyContents=true) { + if (!validKey(key) || !envelope || typeof envelope.payload !== "string" || envelope.payload.length > 2 * 1024 * 1024 || !same(sign(key,PREFIX+envelope.payload),envelope.mac)) return null; + let record; try { record = JSON.parse(envelope.payload); } catch { return null; } + record.names=envelope.names;record.pattern=envelope.pattern; + if (record.v !== 1 || !validId(record.session) || record.session !== envelope.session || typeof record.workspace !== "string" || !record.workspace.startsWith("/") || !["active","revoked"].includes(record.state) || !["all","names"].includes(record.coverage) || !Number.isFinite(record.created) || record.created > Date.now() || !Array.isArray(record.names) || record.names.length > 32 || record.names.some(n => typeof n !== "string" || n.length < 2 || n.length > 120) || (record.coverage === "names" && record.state === "active" && !record.names.length) || (record.coverage === "all" && record.names.length)) return null; + if(record.nameCount!==record.names.length||typeof record.pattern!=="string")return null; + // Complete list integrity is verified in the page service before publishing. + // The request runtime receives immutable host options, never a grant from the + // request body. It verifies the compact scope seal within its 250 ms budget. + if(verifyContents&&digest(JSON.stringify({names:record.names,pattern:record.pattern}))!==record.contentsHash)return null; + return record; +} + +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}; + 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"}; + const record = readAuthorization(matching[0],ctx.options?.authKey,false); + if (!record) return {record:null, managed:true, reason:"authorization_invalid"}; + if (record.state !== "active") return {record:null, managed:true, reason:"session_revoked"}; + if (sessionWorkspace(body,ctx) !== record.workspace) return {record:null, managed:true, reason:"task_identity_mismatch"}; + return {record, managed:true, reason:record.coverage === "all" ? "session_all_active" : "session_names_active"}; +} diff --git a/packages/company-guard/test/company-guard.test.mjs b/packages/company-guard/test/company-guard.test.mjs new file mode 100644 index 0000000..72c97c2 --- /dev/null +++ b/packages/company-guard/test/company-guard.test.mjs @@ -0,0 +1,267 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import {fileURLToPath} from "node:url"; +import {randomBytes} from "node:crypto"; +import {prepareRequest, onRequest, onResponse, onEvent, PREPARED} from "../src/company-guard.js"; +import {onRequest as hookRequest, onResponse as hookResponse} from "../company-guard.hooks.mjs"; +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"; + +// Synthetic fixtures only: no user credentials, companies, grants or history. +const NAME = ["单元", "测试", "科技", "有限", "公司"].join(""); +const SESSION = "11111111-1111-4111-8111-111111111111"; +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")])); +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); }}; +} +const metadata = () => ({thread_source:"user", thread_id:SESSION, turn_id:TURN}); +function request(protocol, text = NAME) { + const body = { + responses:() => ({input:[{role:"user", content:[{type:"input_text", text}]}]}), + chat:() => ({messages:[{role:"user", content:text}]}), + anthropic:() => ({messages:[{role:"user", content:[{type:"text", text}]}]}), + gemini:() => ({contents:[{role:"user", parts:[{text}]}]}) + }[protocol](); + body.client_metadata = metadata(); + return body; +} +function prepare(protocol, options) { + const ctx = context(protocol, options), body = request(protocol); + prepareRequest(body, ctx); + assert.equal(ctx.state.guard.ready, true); + assert(!JSON.stringify(body).includes(NAME)); + const token = Object.keys(ctx.state.guard.reverse)[0]; + assert(token?.startsWith("[[NERO_ORG_")); + return {ctx, body, token}; +} + +for (const protocol of ["responses", "chat", "anthropic", "gemini"]) { + test(protocol + ": request masking and reply restoration", () => { + const {ctx, token} = prepare(protocol); + const response = { + responses:() => ({output:[{type:"message", content:[{type:"output_text", text:token}]}]}), + chat:() => ({choices:[{message:{role:"assistant", content:token}}]}), + anthropic:() => ({content:[{type:"text", text:token}]}), + gemini:() => ({candidates:[{content:{parts:[{text:token}]}}]}) + }[protocol](); + onResponse(response, ctx); + assert(JSON.stringify(response).includes(NAME)); + assert(!JSON.stringify(response).includes(token)); + }); + + test(protocol + ": restore a name split across streaming chunks", t => { + const {ctx, token} = prepare(protocol); + const confirmations=[], info=console.info; + ctx.state.guard.receiptId=SESSION; + console.info=value=>confirmations.push(value); + t.after(()=>{console.info=info;}); + const events = [token.slice(0, 19), token.slice(19)].map((text, index) => ({ + responses:() => ({type:"response.output_text.delta", output_index:0, content_index:0, delta:text}), + chat:() => ({choices:[{index:0, delta:{content:text}, finish_reason:index ? "stop" : null}]}), + anthropic:() => ({type:"content_block_delta", index:0, delta:{type:"text_delta", text}}), + gemini:() => ({candidates:[{index:0, content:{parts:[{text}]}, ...(index ? {finishReason:"STOP"} : {})}]}) + }[protocol]())); + const output = events.map(event => { + const restored = onEvent(event, ctx); + assert(restored); + return protocol === "responses" ? restored.delta : protocol === "chat" ? restored.choices[0].delta.content : + protocol === "anthropic" ? restored.delta.text : restored.candidates[0].content.parts[0].text; + }).join(""); + assert.equal(output, NAME); + assert.equal(ctx.state.guard.failed, false); + if (["chat","gemini"].includes(protocol)) { + const row=confirmations.map(line=>JSON.parse(line.slice("NERO_COMPANY_GUARD_RECEIPT ".length))).find(r=>r.phase==="reply_processed"); + assert.equal(row.ok,true); + assert.equal(row.eventType,protocol+".completed"); + } + }); + + test(protocol + ": mask company names in tool arguments", () => { + const ctx = context(protocol), args = {company_name:NAME}; + const body = { + responses:() => ({input:[{type:"function_call", name:"lookup", call_id:"fixture", arguments:JSON.stringify(args)}]}), + chat:() => ({messages:[{role:"assistant", tool_calls:[{id:"fixture", type:"function", function:{name:"lookup", arguments:JSON.stringify(args)}}]}]}), + anthropic:() => ({messages:[{role:"assistant", content:[{type:"tool_use", id:"fixture", name:"lookup", input:args}]}]}), + gemini:() => ({contents:[{role:"model", parts:[{functionCall:{name:"lookup", args}}]}]}) + }[protocol](); + prepareRequest(body, ctx); + assert.equal(ctx.state.guard.ready, true); + assert(!JSON.stringify(body).includes(NAME)); + assert.equal(Object.values(ctx.state.guard.reverse)[0], NAME); + }); +} + +function authorization(ctx, state = "active", coverage = "names") { + return signAuthorization({v:1, session:SESSION, workspace:ctx.cwd, state, coverage, + names:coverage === "all" ? [] : [NAME], created:Date.now()}, ctx.options.authKey); +} +for (const coverage of ["names", "all"]) { + test("session authorization: " + coverage + " approval and revocation", () => { + const ctx = context("responses"), body = request("responses"); + ctx.options.sessionAuthorizations = [authorization(ctx, "active", coverage)]; + prepareRequest(body, ctx); + assert(JSON.stringify(body).includes(NAME)); + assert.equal(ctx.state.guard.metrics.authorizationCoverage, coverage); + ctx.options.sessionAuthorizations = [authorization(ctx, "revoked", coverage)]; + const next = request("responses"); + prepareRequest(next, ctx); + assert(!JSON.stringify(next).includes(NAME)); + assert.equal(ctx.state.guard.metrics.authorizationReason, "session_revoked"); + }); +} +test("authorization cannot cross sessions or workspaces; altered seals do not authorize", () => { + const ctx = context("responses"), approved = authorization(ctx); + ctx.options.sessionAuthorizations = [approved]; + const other = request("responses"); other.client_metadata.thread_id = TURN; ctx.session = TURN; + prepareRequest(other, ctx); assert(!JSON.stringify(other).includes(NAME)); + ctx.session = SESSION; ctx.cwd += "/different"; + const moved = request("responses"); prepareRequest(moved, ctx); assert(!JSON.stringify(moved).includes(NAME)); + ctx.cwd = "/tmp/company-guard-fixture"; + ctx.options.sessionAuthorizations = [{...approved, mac:"0".repeat(64)}]; + const altered = request("responses"); prepareRequest(altered, ctx); assert(!JSON.stringify(altered).includes(NAME)); +}); + +async function installation(t, supplied = {}) { + const directory = await fs.mkdtemp(path.join(os.tmpdir(), "company-guard-test-")); + const previous = process.env.XDG_CONFIG_HOME; + process.env.XDG_CONFIG_HOME = directory; + t.after(async () => { if (previous === undefined) delete process.env.XDG_CONFIG_HOME; else process.env.XDG_CONFIG_HOME = previous; await fs.rm(directory, {recursive:true, force:true}); }); + const configDirectory = path.join(directory, "magpie"); await fs.mkdir(configDirectory, {mode:0o700}); + const configFile = path.join(configDirectory, "plugins.json"); + const config = {plugins:[{spec:ROOT, options:{companies:[NAME], ...supplied}}, {spec:"fixture-other", options:{keep:true}}], prefer:{fixture:"fixture-other"}}; + await fs.writeFile(configFile, JSON.stringify(config), {mode:0o600}); + return {options:{...config.plugins[0].options}, configFile, keyFile:path.join(configDirectory, "company-guard", "keys.json"), config}; +} +test("fresh install generates three private persistent keys and preserves unrelated settings", async t => { + const setup = await installation(t); + const options = await initializeOptions(setup.options); + for (const field of keyFields) assert.match(options[field], /^[a-f0-9]{64}$/); + assert.equal(new Set(keyFields.map(field => options[field])).size, 3); + assert.equal((await fs.stat(setup.keyFile)).mode & 0o777, 0o600); + assert.equal((await fs.stat(path.dirname(setup.keyFile))).mode & 0o777, 0o700); + 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}); + for (const field of keyFields) assert.equal(again[field], options[field]); + assert.equal((await fs.stat(setup.configFile)).mode & 0o777, 0o600); +}); +test("a pinned GitHub installation initializes without a local-path registration", async t => { + const setup = await installation(t); + setup.config.plugins[0].spec = "github:cyanask/magpie-company-guard#main"; + await fs.writeFile(setup.configFile, JSON.stringify(setup.config)); + const options = await initializeOptions(setup.options); + 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"]) { + test("community installation initializes: " + spec, async t => { + const setup = await installation(t); + setup.config.plugins[0].spec = spec; + await fs.writeFile(setup.configFile, JSON.stringify(setup.config)); + const options = await initializeOptions(setup.options); + const saved = JSON.parse(await fs.readFile(setup.configFile)); + for (const field of keyFields) assert.equal(saved.plugins[0].options[field], options[field]); + }); +} +test("duplicate installations are rejected instead of changing both entries", async t => { + const setup = await installation(t); + setup.config.plugins.push({spec:"github:cyanask/magpie-company-guard"}); + const before = JSON.stringify(setup.config); await fs.writeFile(setup.configFile, before); + await assert.rejects(initializeOptions(setup.options), /installation_not_unique/); + assert.equal(await fs.readFile(setup.configFile, "utf8"), before); +}); +test("existing keys, explicit port and signed authorizations survive initialization", async t => { + const keys = newKeys(), ctx = context("responses", keys), approved = authorization(ctx); + const setup = await installation(t, {...keys, receiptPort:3478, sessionAuthorizations:[approved]}); + const before = await fs.readFile(setup.configFile, "utf8"); + const options = await initializeOptions(setup.options); + assert.equal(await fs.readFile(setup.configFile, "utf8"), before); + assert.equal(options.receiptPort, 3478); + for (const field of keyFields) assert.equal(options[field], keys[field]); + const body = request("responses"); prepareRequest(body, context("responses", options)); + assert(JSON.stringify(body).includes(NAME)); +}); +test("partial configuration retains its existing protection key", async t => { + const authKey = randomBytes(32).toString("hex"), setup = await installation(t, {authKey}); + const options = await initializeOptions(setup.options); + assert.equal(options.authKey, authKey); + assert.match(options.receiptReadKey, /^[a-f0-9]{64}$/); + assert.match(options.authorizationKey, /^[a-f0-9]{64}$/); +}); +test("concurrent initializers share one complete key file", async t => { + const setup = await installation(t); + const results = await Promise.all(Array.from({length:6}, () => initializeOptions({...setup.options}))); + for (const options of results) for (const field of keyFields) assert.equal(options[field], results[0][field]); + assert.deepEqual(JSON.parse(await fs.readFile(setup.keyFile)), Object.fromEntries(keyFields.map(field => [field, results[0][field]]))); +}); +test("invalid existing options are rejected without overwriting configuration", async t => { + const setup = await installation(t, {authKey:"invalid"}); + const before = await fs.readFile(setup.configFile, "utf8"); + await assert.rejects(initializeOptions(setup.options), /invalid_existing_key/); + assert.equal(await fs.readFile(setup.configFile, "utf8"), before); + await assert.rejects(fs.stat(setup.keyFile), {code:"ENOENT"}); +}); +test("corrupt or conflicting stored keys are preserved and rejected", async t => { + const setup = await installation(t); await initializeOptions(setup.options); + const original = await fs.readFile(setup.keyFile, "utf8"); + await assert.rejects(initializeOptions({...setup.options, authKey:randomBytes(32).toString("hex")}), /key_conflict/); + assert.equal(await fs.readFile(setup.keyFile, "utf8"), original); + await fs.writeFile(setup.keyFile, "invalid-json"); + await assert.rejects(initializeOptions(setup.options), /invalid_key_file/); + assert.equal(await fs.readFile(setup.keyFile, "utf8"), "invalid-json"); +}); +test("symlinked or permissive key files are rejected", async t => { + const setup = await installation(t); await initializeOptions(setup.options); + await fs.chmod(setup.keyFile, 0o644); + await assert.rejects(initializeOptions(setup.options), /invalid_key_file/); + await fs.chmod(setup.keyFile, 0o600); + const target = setup.keyFile + ".saved"; await fs.rename(setup.keyFile, target); await fs.symlink(target, setup.keyFile); + await assert.rejects(initializeOptions(setup.options), /invalid_key_file/); +}); +test("fresh hook preparation and native middleware share keys and remove the private envelope", async t => { + const setup = await installation(t), body = request("responses"), hook = context("responses", setup.options); + hook.options = setup.options; + await hookRequest(body, hook); + assert(body[PREPARED]); + const native = context("responses", JSON.parse(await fs.readFile(setup.configFile)).plugins[0].options); + const messages=[], info=console.info; + console.info=value=>messages.push(value); + t.after(()=>{console.info=info;}); + middlewareRequest(body, native); + assert.equal(body[PREPARED], undefined); + assert(!JSON.stringify(body).includes(NAME)); + for (const field of keyFields) assert(!JSON.stringify(body).includes(native.options[field])); + const token = Object.keys(native.state.guard.reverse)[0], reply = {output:[{content:[{type:"output_text", text:token}]}]}; + middlewareEvent({type:"response.completed",response:reply}, native); + middlewareResponse(reply, native); assert(JSON.stringify(reply).includes(NAME)); + console.info=info; + + // Reuse this real hook/middleware exchange to exercise confirmation loss. + const root=path.dirname(setup.keyFile), appLog=path.join(root,"app.log"), day=hook.state.receipt.startedAt.slice(0,10); + await fs.writeFile(appLog,messages.join("\n")+"\n",{mode:0o600}); + await retainReceipts(root,undefined,appLog); + const file=path.join(root,"receipts",day+".jsonl"), records=(await fs.readFile(file,"utf8")).trim().split("\n").map(JSON.parse); + const report=async(saved=[]) => (await getReceiptReport({day,root,appLog,records:saved})).rows.find(r=>r.id===hook.state.receipt.id); + assert.equal((await report()).statusCode,"completed"); + assert.equal((await report()).completionSource,"stream"); + assert.equal((await report()).agent,"codex"); + await fs.writeFile(appLog,""); + assert.equal((await report()).statusCode,"completed","persisted confirmations survive log rotation"); + 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"); + await hookResponse(reply,{...hook,success:false}); + assert.equal((await report(records)).statusCode,"call_incomplete","explicit failed completion is never promoted by a stream checkpoint"); + await hookResponse({output:[{content:[{type:"output_text",text:token}]}]},{...hook,success:true}); + assert.equal((await report(records)).statusCode,"restoration_residue","actual residual tokens still fail"); +}); diff --git a/packages/company-guard/vendor/LICENSE.magpie b/packages/company-guard/vendor/LICENSE.magpie new file mode 100644 index 0000000..f840b8d --- /dev/null +++ b/packages/company-guard/vendor/LICENSE.magpie @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 yetone + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/company-guard/vendor/LICENSE.noble-hashes b/packages/company-guard/vendor/LICENSE.noble-hashes new file mode 100644 index 0000000..9297a04 --- /dev/null +++ b/packages/company-guard/vendor/LICENSE.noble-hashes @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/packages/company-guard/vendor/LICENSE.word-guard b/packages/company-guard/vendor/LICENSE.word-guard new file mode 100644 index 0000000..e6bc674 --- /dev/null +++ b/packages/company-guard/vendor/LICENSE.word-guard @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 magpie-community contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/company-guard/vendor/hashes.js b/packages/company-guard/vendor/hashes.js new file mode 100644 index 0000000..452afbb --- /dev/null +++ b/packages/company-guard/vendor/hashes.js @@ -0,0 +1,462 @@ +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + +function isBytes(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; +} +var atitle = (title) => title ? `"${title}" ` : ""; +function anumber(n, title = "") { + if (typeof n !== "number") + throw new TypeError(atitle(title) + "expected number, got " + typeof n); + if (!Number.isSafeInteger(n) || n < 0) + throw new RangeError(atitle(title) + "expected integer >= 0, got " + n); + return n; +} +function abytes(value, length, title = "") { + if (isBytes(value) && (length === void 0 || value.length === length)) + return value; + if (length !== void 0) + anumber(length, "length"); + const bytes = isBytes(value); + const ofLen = length !== void 0 ? ` of length ${length}` : ""; + const got = bytes ? `length=${value.length}` : `type=${typeof value}`; + const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got; + if (!bytes) + throw new TypeError(message); + throw new RangeError(message); +} +function ahash(h) { + if (typeof h !== "function" || typeof h.create !== "function") + throw new TypeError("expected hash wrapped by utils.createHasher"); + anumber(h.outputLen); + anumber(h.blockLen); + if (h.outputLen < 1 || h.blockLen < 1) + throw new Error("hash blockLen / outputLen must be >= 1"); +} +var aobject = (value, label) => { + if (value === null || typeof value !== "object" || Array.isArray(value)) + throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value); +}; +var aopts = (value, label) => { + aobject(value, label); + const proto = Object.getPrototypeOf(value); + if (proto !== Object.prototype && proto !== null) + throw new TypeError(`"${label}" expected plain object`); + if (Object.hasOwn(value, "__proto__")) + throw new TypeError(`"${label}.__proto__" is not allowed`); +}; +function aexists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("hash was destroyed"); + if (checkFinished && instance.finished) + throw new Error("digest() was already called"); +} +function aoutput(out, instance) { + abytes(out, void 0, "output"); + const min = instance.outputLen; + if (!(out.length >= min)) { + throw new RangeError('"output" expected length >= ' + min); + } +} +function clean(...arrays) { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } +} +function createView(arr) { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +} +function rotr(word, shift) { + return word << 32 - shift | word >>> shift; +} +function checkOpts(defaults, opts, title = "opts") { + aopts(defaults, "defaults"); + if (opts !== void 0) + aopts(opts, title); + const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts); + return merged; +} +function createHasher(hashCons, info = {}) { + if (typeof hashCons !== "function") + throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons); + info = checkOpts({}, info, "info"); + const hashC = (msg, opts) => hashCons(opts).update(msg).digest(); + const tmp = hashCons(void 0); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.canXOF = tmp.canXOF; + hashC.create = (opts) => hashCons(opts); + Object.assign(hashC, info); + return Object.freeze(hashC); +} +var oidNist = (suffix) => ({ + // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet. + // Larger suffix values would need base-128 OID encoding and a different length byte. + oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix]) +}); + +var _HMAC = class { + constructor(hash, key) { + __publicField(this, "oHash"); + __publicField(this, "iHash"); + __publicField(this, "blockLen"); + __publicField(this, "outputLen"); + __publicField(this, "canXOF", false); + __publicField(this, "finished", false); + __publicField(this, "destroyed", false); + ahash(hash); + abytes(key, void 0, "key"); + this.iHash = hash.create(); + if (typeof this.iHash.update !== "function") + throw new Error("expected Hash instance"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 54; + this.iHash.update(pad); + this.oHash = hash.create(); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 54 ^ 92; + this.oHash.update(pad); + clean(pad); + } + update(buf) { + aexists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const buf = out.subarray(0, this.outputLen); + this.iHash.digestInto(buf); + this.oHash.update(buf); + this.oHash.digestInto(buf); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.canXOF = canXOF; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + clone() { + return this._cloneInto(); + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +}; +var hmac = /* @__PURE__ */ (() => { + const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest()); + hmac_.create = (hash, key) => new _HMAC(hash, key); + return hmac_; +})(); + +var fromNumH = (n) => n / 2 ** 32 | 0; +var fromNumL = (n) => n >>> 0; +function setU64FromNum(view, byteOffset, n, isLE) { + const h = fromNumH(n); + const l = fromNumL(n); + view.setUint32(byteOffset, isLE ? l : h, isLE); + view.setUint32(byteOffset + 4, isLE ? h : l, isLE); +} + +function Chi(a, b, c) { + return a & b ^ ~a & c; +} +function Maj(a, b, c) { + return a & b ^ a & c ^ b & c; +} +var HashMD = class { + constructor(blockLen, outputLen, padOffset, isLE) { + __publicField(this, "blockLen"); + __publicField(this, "outputLen"); + __publicField(this, "canXOF", false); + __publicField(this, "padOffset"); + __publicField(this, "isLE"); + // For partial updates less than block size + __publicField(this, "buffer"); + __publicField(this, "view"); + __publicField(this, "finished", false); + __publicField(this, "length", 0); + __publicField(this, "pos", 0); + __publicField(this, "destroyed", false); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + aexists(this); + abytes(data); + const { view, buffer, blockLen } = this; + const len = data.length; + let processed = false; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + processed = true; + continue; + } + buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + processed = true; + } + } + this.length += data.length; + if (processed) + this.roundClean(); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + buffer[pos++] = 128; + buffer.fill(0, pos); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + buffer.fill(0); + } + setU64FromNum(view, blockLen - 8, this.length * 8, isLE); + this.process(view, 0); + this.roundClean(); + const oview = out === buffer ? view : createView(out); + const len = this.outputLen; + const outLen = len / 4; + const state = this.get(); + if (len % 4 || outLen > state.length) + throw new Error("invalid outputLen"); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneIntoMeta(to) { + const { buffer, length, finished, destroyed, pos } = this; + to.destroyed = destroyed; + to.finished = finished; + to.length = length; + to.pos = pos; + if (pos) + to.buffer.set(buffer); + return to; + } + clone() { + return this._cloneInto(); + } +}; +var SHA256_IV = /* @__PURE__ */ Uint32Array.from([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]); + +var SHA256_K = /* @__PURE__ */ Uint32Array.from([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]); +var SHA256_W = /* @__PURE__ */ new Uint32Array(64); +var SHA2_32B = class extends HashMD { + constructor(outputLen, IV) { + super(64, outputLen, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + // Numeric initializers matter: starting the fields as `undefined` changes + // V8's field representation and makes sha256 3x slower (measured). + __publicField(this, "A", 0); + __publicField(this, "B", 0); + __publicField(this, "C", 0); + __publicField(this, "D", 0); + __publicField(this, "E", 0); + __publicField(this, "F", 0); + __publicField(this, "G", 0); + __publicField(this, "H", 0); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + _cloneInto(to) { + (to || (to = new this.constructor())).set(...this.get()); + return this._cloneIntoMeta(to); + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; + SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; + } + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = sigma0 + Maj(A, B, C) | 0; + H = G; + G = F; + F = E; + E = D + T1 | 0; + D = C; + C = B; + B = A; + A = T1 + T2 | 0; + } + A = A + this.A | 0; + B = B + this.B | 0; + C = C + this.C | 0; + D = D + this.D | 0; + E = E + this.E | 0; + F = F + this.F | 0; + G = G + this.G | 0; + H = H + this.H | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + clean(SHA256_W); + } + destroy() { + this.destroyed = true; + this.set(0, 0, 0, 0, 0, 0, 0, 0); + clean(this.buffer); + } +}; +var _SHA256 = class extends SHA2_32B { + constructor() { + super(32, SHA256_IV); + } +}; +var sha256 = /* @__PURE__ */ createHasher( + () => new _SHA256(), + /* @__PURE__ */ oidNist(1) +); +export { + hmac, + sha256 +}; diff --git a/packages/company-guard/vendor/magpie-pagebridge.js b/packages/company-guard/vendor/magpie-pagebridge.js new file mode 100644 index 0000000..93c7ffa --- /dev/null +++ b/packages/company-guard/vendor/magpie-pagebridge.js @@ -0,0 +1,190 @@ +// The page's side of a plugin page's messages to magpie's window +// (docs/subsystems/plugin-runtime.md, P4). A plugin's page loads it with +// ; it is served beside every +// page's own files. +// +// await magpie.ready the window's theme, once it has answered +// magpie.theme { dark, lang, tokens: { bg, fg, … } } +// magpie.onTheme(fn) fn(theme) on each change of it +// await magpie.options.get() the plugin's own options (plugins.json) +// await magpie.options.set(o) sets them, and answers with them +// await magpie.read(name, p) a read its package.json's +// magpie.permissions declares +// magpie.context where a panel is (P5): { provider: { +// id, name } } in a provider's editor, +// else {}; set once magpie.ready is +// magpie.service the address of the page's local service +// (package.json's magpie.page.service) +// through magpie, set once magpie.ready +// is, on a page a browser opened through +// magpie web; "" where 127.0.0.1 is the +// service's own computer (the app's +// window) or magpie is older +// magpie.onAction(fn) fn({ id, provider | agent: { id, name } }) +// when one of its magpie.actions is picked +// in a row's menu (P6); one picked before +// fn was given waits for it +// magpie.visible false while the reader is on another of +// the window's pages +// magpie.onVisibility(fn) fn(visible) as the reader leaves the +// page and comes back, to pause what only +// matters while it is seen; a page left +// 10 minutes is let go, and loads again +// when next opened, unless package.json +// says magpie.page.keepAlive +// +// A panel (magpie.panels) is as tall as what it draws: the window is told +// its height as it changes. +// +// What the page leaves unstyled takes magpie's look: the bridge adds a +// stylesheet of no weight (:where()) for the font, colours, headings, +// buttons, fields and tables, and the theme's colours are the page's +// --magpie- variables. +// +// The page can't reach the network or magpie's API itself: everything goes +// through the window, which answers only what the package declared. An +// error the page doesn't catch shows the window's "This page stopped +// working" in its place. +(() => { + const waiting = new Map(); + let next = 0; + const themed = []; + const watched = []; + let acting = null; + const acted = []; + function call(method, params) { + const id = ++next; + return new Promise((resolve, reject) => { + waiting.set(id, { resolve, reject }); + parent.postMessage({ magpie: 1, id, method, params }, "*"); + }); + } + function paint(theme) { + const root = document.documentElement; + root.dataset.theme = theme.dark ? "dark" : "light"; + // the frame's canvas matches the window's, not a white sheet in dark + root.style.colorScheme = theme.dark ? "dark" : "light"; + root.lang = theme.lang || "en"; + for (const [k, v] of Object.entries(theme.tokens || {})) root.style.setProperty("--magpie-" + k, v); + } + addEventListener("message", (e) => { + if (e.source !== parent) return; + const m = e.data; + if (!m || m.magpie !== 1) return; + if (m.event === "theme") { + api.theme = m.data; + paint(m.data); + for (const fn of themed) { try { fn(m.data); } catch (err) { report(err); } } + return; + } + if (m.event === "visibility") { + api.visible = !!m.data?.visible; + for (const fn of watched) { try { fn(api.visible); } catch (err) { report(err); } } + return; + } + if (m.event === "action") { + if (acting) act(m.data); else acted.push(m.data); + return; + } + const w = waiting.get(m.id); + if (!w) return; + waiting.delete(m.id); + if (m.error) w.reject(new Error(m.error)); else w.resolve(m.result); + }); + function report(err) { + parent.postMessage({ magpie: 1, method: "error", params: { message: String(err?.message || err) } }, "*"); + } + // a script's error reaches a sandboxed page only as "Script error." (its + // files are another origin's to it); the window then says "The page hit + // an error" in the reader's language, and the console has the rest + // + // The size watch below can be told its own "ResizeObserver loop + // completed with undelivered notifications" when the window resizes the + // frame in the same frame of drawing; that is no error of the page's, + // and WebKit hands it to a sandboxed page as a bare "Script error." with + // no file, so one that comes while the watch has just run is let go + let measuring = false; + addEventListener("error", (e) => { + if (/ResizeObserver loop/.test(e.message) || (measuring && !e.error && !e.filename)) { e.preventDefault(); return; } + report(e.error || (e.message === "Script error." ? "" : e.message)); + }); + addEventListener("unhandledrejection", (e) => report(e.reason)); + function act(data) { + try { Promise.resolve(acting(data)).catch(report); } catch (err) { report(err); } + } + const api = { + theme: null, + context: {}, + service: "", + visible: true, + onTheme(fn) { themed.push(fn); }, + onVisibility(fn) { watched.push(fn); }, + onAction(fn) { + acting = fn; + for (const d of acted.splice(0)) act(d); + }, + options: { + get: () => call("options.get"), + set: (options) => call("options.set", { options }), + }, + read: (name, params) => call("read", { name, params }), + }; + api.ready = call("hello").then(({ context, service, visible, ...theme }) => { + api.theme = theme; + if (visible === false) api.visible = false; + api.context = context || {}; + api.service = ""; + try { if (service) api.service = new URL(service, location.href).href; } catch { /* none */ } + paint(theme); + return theme; + }); + // how tall the page draws, for a panel's frame; a page's frame fills its + // view, and the window doesn't heed it there + let told = -1; + const size = () => { + const h = Math.ceil(document.documentElement.getBoundingClientRect().height); + if (h === told) return; + told = h; + parent.postMessage({ magpie: 1, method: "size", params: { height: h } }, "*"); + }; + const watch = () => { + new ResizeObserver(() => { + if (!measuring) { measuring = true; setTimeout(() => { measuring = false; }); } + size(); + }).observe(document.documentElement); + size(); + }; + if (document.readyState === "loading") addEventListener("DOMContentLoaded", watch); else watch(); + // magpie's look for what the page leaves unstyled: its font, colours, + // headings, buttons, fields and tables, so a page with no stylesheet of + // its own reads as part of the window, not a browser's default sheet. + // Every rule is :where(), of no weight: any rule of the page's wins. + const base = document.createElement("style"); + base.dataset.magpie = "base"; + base.textContent = ` +:where(html) { background: var(--magpie-bg, Canvas); color: var(--magpie-fg, CanvasText); font: 13px/1.45 var(--magpie-font, -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif); -webkit-font-smoothing: antialiased; } +:where(body) { margin: 0; padding: 20px 24px; } +:where(h1, h2, h3, h4) { font-weight: 600; margin: 0 0 8px; letter-spacing: -.01em; } +:where(h1) { font-size: 20px; } :where(h2) { font-size: 15px; } :where(h3, h4) { font-size: 13px; } +:where(p) { margin: 0 0 8px; } +:where(small, .muted) { color: var(--magpie-muted, GrayText); } +:where(a) { color: var(--magpie-accent, LinkText); text-decoration: none; } +:where(a:hover) { text-decoration: underline; } +:where(button, input, textarea, select) { font: inherit; color: inherit; } +:where(button) { background: var(--magpie-card, ButtonFace); border: 1px solid var(--magpie-line, ButtonBorder); border-radius: 6px; padding: 3px 10px; } +:where(button:hover:not(:disabled)) { border-color: var(--magpie-muted, ButtonBorder); } +:where(button[aria-pressed="true"], button[aria-selected="true"]) { background: var(--magpie-accent-soft, Highlight); border-color: transparent; color: var(--magpie-accent, HighlightText); } +:where(button:disabled) { opacity: .5; } +:where(input, textarea, select) { background: var(--magpie-card, Field); border: 1px solid var(--magpie-line, ButtonBorder); border-radius: 6px; padding: 4px 8px; } +:where(:focus-visible) { outline: 2px solid var(--magpie-accent, Highlight); outline-offset: 1px; } +:where(table) { border-collapse: collapse; width: 100%; } +:where(th) { text-align: left; font-weight: 500; font-size: 12px; color: var(--magpie-muted, GrayText); } +:where(th, td) { padding: 6px 8px; border-bottom: 1px solid var(--magpie-line, ButtonBorder); } +:where(code, kbd, pre) { font-family: var(--magpie-code, ui-monospace, Menlo, monospace); font-size: 12px; } +:where(pre) { background: var(--magpie-card, Canvas); border: 1px solid var(--magpie-line, ButtonBorder); border-radius: 8px; padding: 8px 10px; overflow: auto; } +:where(hr) { border: 0; border-top: 1px solid var(--magpie-line, ButtonBorder); margin: 12px 0; } +:where(::selection) { background: var(--magpie-accent-soft, Highlight); } +`; + (document.head || document.documentElement).prepend(base); + window.magpie = api; +})(); diff --git a/registry.json b/registry.json index 419cd6b..c2b260d 100644 --- a/registry.json +++ b/registry.json @@ -97,6 +97,8 @@ "summary": { "en": "Seven composable output styles, all off by default, with a selection panel and prompt-cache-stable injection that preserves Codex instructions. Unofficial; by manjughosa.", "zh": "七种可组合的输出样式,全部默认关闭;带选择面板,注入不破坏提示缓存,也不改写 Codex instructions。由 manjughosa 独立开发并维护,非官方出品。" } }, { "package": "@magpie-community/middleware-word-guard", "name": "Word Guard", "kind": "middleware", "community": true, "summary": { "en": "New API's sensitive-word filter: turn away or mask words and patterns in what you send, and in replies.", "zh": "New API 的敏感词过滤:拒绝或替换你发出的内容和回复里的词与正则。" } }, + { "package": "@magpie-community/middleware-company-guard", "name": "Company Guard", "kind": "middleware", "community": true, + "summary": { "en": "Recognize and mask company names with stable session aliases, restore replies, and show local receipts and explicit Codex session approvals. Unlike Word Guard, names can be restored. Text only; rule-based detection.", "zh": "识别公司名称并使用会话内稳定代号,回复返回本机时还原,提供本地回执与需明确确认的 Codex 会话授权。区别于 Word Guard 的词表拒绝或替换,支持名称还原;仅处理文字,采用规则识别。" } }, { "package": "@magpie-community/middleware-think-tags", "name": "Think Tags", "kind": "middleware", "community": true, "summary": { "en": "Take a model's leading , or block out of its reply's text, or put a Chat reply's reasoning into it.", "zh": "去掉回复正文开头的 、 或 思考块,或把 Chat 回复的思考内容放进正文。" } }, { "package": "@magpie-community/middleware-empty-reply", "name": "Empty Reply", "kind": "middleware", "community": true,