Compare commits

...
6 Commits
Author SHA1 Message Date
yunyingk b49f25a2bc Merge pull request #259 from yunyingk/codex/release-v0.11.14
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.14: extra risk filters and link identities
2026-10-22 12:41:32 +08:00
gitea b1769d8a25 Release v0.11.14: extra risk filters and link identities 2026-10-22 12:39:02 +08:00
yunyingk 0582bc7898 Merge pull request #258 from yunyingk/mac15/assist-link-person-names
Report verified personnel names for assistance links
2026-10-22 12:38:07 +08:00
yunyingk 6d310ba945 Merge pull request #257 from yunyingk/mac15/approval-extra-risk
Add approval record extra risk filtering
2026-10-22 12:36:35 +08:00
gitea 41e0bfba71 Report verified personnel names for assistance links 2026-10-22 12:35:28 +08:00
gitea b5dd3560b6 Add approval record extra risk filtering 2026-10-22 12:34:54 +08:00
20 changed files with 527 additions and 19 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.13",
"version": "0.11.14",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+8
View File
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.11.14] - 2026-10-22
### Added
- 审核记录 `list/search` 新增 `--has-extra-risk`,按系统检测的 `warning/error` 筛选额外风险,返回风险明细、数量与无法判断的记录数;沿用现有查询条件和分页,100 条为共享单页上限,没有独立的总量限制(#257)。
### Fixed
- 合思与 Seal 协助链接自动返回实际人员姓名及已核实的角色或权限;身份查询失败明确标记未核实,Skill 要求汇报人员姓名、目标系统、权限和有效期(#258)。
## [0.11.13] - 2026-10-20
### Added
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.13",
"version": "0.11.14",
"private": true,
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
"license": "MIT",
+4 -4
View File
@@ -1,9 +1,9 @@
---
name: seal-use
description: "v0.11.13: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.11.14: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.11.13
short-description: Seal tenant and Hose approval automation (v0.11.13)
version: 0.11.14
short-description: Seal tenant and Hose approval automation (v0.11.14)
---
# Seal Use
@@ -123,7 +123,7 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
| --- | --- | --- |
| 第一次接入、不会找凭据、需要截图 | `references/first-time-user.md` | 用户交付材料后,再读 `enterprise-onboarding.md` 做来源决策 |
| 判断材料来源、Token 边界、cURL、Hose 提权 | `references/enterprise-onboarding.md` | 需要具体域名/员工探测时,再读 `hose-enterprise-init.md` |
| Hose 登录检查、认证失败、生成授权链接 | `references/hose-enterprise-auth.md` | 需要重新接入或判断材料类型时,先读 `enterprise-onboarding.md` |
| Hose 登录检查、认证失败、合思/Seal 协助链接及登录人员身份 | `references/hose-enterprise-auth.md` | 需要重新接入或判断材料类型时,先读 `enterprise-onboarding.md` |
| Hose 域名探测、角色/员工发现、管理员选择 | `references/hose-enterprise-init.md` | 不要先加载部署或规则文档 |
| 配置、同步或排查发布到 HoseCloud | `references/hose-enterprise-deploy.md` | 涉及生产/测试配对或模拟时,再读 `staging-simulation-workflow.md` |
| 生产草稿、测试同步、模拟、回归、发布 | `references/staging-simulation-workflow.md` | 需要客诉证据定界时,再读 `customer-feedback-rule-remediation.md` |
@@ -16,6 +16,31 @@ Default output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDo
If there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.
## Find Runs With Extra Risks
审核结果区分 `result.rulesResult[].findings`(绑定规则的检查发现)与 `result.otherFindings[]`(额外发现)。额外发现中的 `warning` / `error` 计为额外风险,`info` 仅为提示;不根据最终审批结论或摘要文本推断额外风险。
前端将规则内发现映射为 `source: "rule"`,额外发现映射为 `source: "system"` 并标注“系统检测”。这是展示层根据字段来源派生的分类,不是当前审核列表接口已接入的筛选参数。“系统检测”也可能是 `info`,因此不能将全部系统检测项都计为风险。原始等级枚举为 `info / warning / error`;页面的“需复核”还可能由规则的 `UNCERTAIN` 结论派生。
```bash
# 从最近一页 100 条记录中筛出含额外风险的记录
seal-use approval-runs list --has-extra-risk --limit 100 --corp <corpId>
# 在时间、运行状态、人工结果等条件下筛选
seal-use approval-runs search --has-extra-risk --status completed --startDate 2026-10-01 --endDate 2026-10-22 --limit 100 --corp <corpId>
# 继续检查下一页;offset 按上游记录数推进,不按 matched 推进
seal-use approval-runs list --has-extra-risk --limit 100 --offset 100 --corp <corpId>
```
- `limit` 是筛选前读取的页大小(默认 50,最多 100),不会为凑满命中数自动翻页。`offset` 同样作用于上游结果集。
- `scanned` 是本页上游返回的条数,`matched` 是所有本地筛选后的返回条数。`total` 保留上游筛选条件下的记录总数,**不是额外风险单据总数**。
- 启用筛选时,`unknown` 是通过其他本地条件后,因结果缺失或格式异常而无法判断额外风险的条数。这些记录不混入命中列表;无筛选读取时,可通过 `extraFindingsStatus: "unknown"` 定位。
- 记录摘要包含 `otherFindingCount`(含 info 的额外发现总数)、`extraRiskCount`、`hasExtraRisk`、`extraFindingsStatus`。空数组表示已知无额外发现;缺失/异常数据的数量和布尔值为 `null`。
- 本筛选读取结构化的 `otherFindings`。前端还会转换旧版结果中的 `otherRisks` 等字段,但本筛选不推断旧版关联关系;未提供 `otherFindings` 的历史记录计为 `unknown`。
- 启用筛选时,每条命中记录附带 `extraRisks`,含风险标题、等级和描述。一次审核可能有多个风险,`matched` 按审核记录计数;同一单据多次审核也可能返回多条记录。
- `approval-runs result <recordId> --summary` 和 `get <recordId> --summary` 的 AI 结果也返回上述计数字段。查看全部额外发现可用 `get <recordId> --fields result.otherFindings`。
## Read Compact Run Detail
Use `--summary` for most diagnosis and support questions.
+1 -1
View File
@@ -98,7 +98,7 @@ seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sou
seal-use approval-runs count [--status APPROVED] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--corp <corpId>]
seal-use approval-runs export [--sn <SN1,SN2>] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads|--to-downloads] [--with-flow] [--out <file>] [--corp <corpId>]
seal-use approval-runs hose-flow <recordId|SN> [--corp <corpId>]
seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]
seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--has-extra-risk] [--limit 20] [--includeBridge true] [--corp <corpId>]
seal-use approval-runs pick --sn <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision] [--corp <corpId>]
seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp <corpId>]
seal-use approval-runs cited-rules <recordId> [--corp <corpId>]
@@ -67,8 +67,21 @@ Important:
- `seal-use auth check` proves this stage works but redacts the token, so it is not enough when the user needs the actual clickable Hose link.
- **Dedicated CLI Command**: Use `seal-use auth hose-link --corp <corpId> [--expire <duration>] [--force]`. This command directly generates an independent provisional auth link without reading or mutating internal CLI session cache. It supports `--expire` (default `2h`, e.g. `7d` or `7200`).
- **Formatting Requirement**: When returning a Hose authorization link (`auth hose-link`) to the user, directly use the CLI JSON output:
1. The operator identity: directly display the returned `staffId` (or `staffName` if present in output; do NOT make additional network calls or auth checks to search for personal names),
1. The operator identity: **always report the person's name from `staffName`**. The CLI automatically looks up the exact Hose employee for `auth hose-link`, and the actual Seal session user for `auth link`. Do not use `staffId` as a person's name, infer a name from an ID, or assume both systems use the same person. If `identityStatus` is `unresolved` (`staffName: null`), explicitly report that the identity name could not be verified; do not silently omit it or guess,
2. The exact expiration time in Beijing time (`expiresAt`),
3. BOTH a code block (` ```text ... ``` `) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
- **Seal AI Platform Direct Link**: If the user needs a delegation link for the Seal AI audit platform (`https://*.sealai.cc`) instead of Hose/易快报, use `seal-use auth link --corp <corpId> [--note <note>]`.
## Assistance link identity and reporting contract
This contract applies to both `auth hose-link` and `auth link`, including `auth link --from-link`.
- `staffName` is the verified person's name, or `null`; `identityStatus` is `resolved` / `unresolved`. Identity lookups do not switch the configured employee, modify enterprise configuration, reset a password, or request additional privileges.
- Hose links return `roleNames` from that exact employee's role assignments. `null` means role names could not be verified; an empty array means the employee response explicitly contained no roles. Never infer “主管理员” merely because the CLI can generate a link.
- Seal links return the actual session user's `isAdmin` and `permissions`. Report administrative access only when confirmed by those fields; `null` means the lookup failed. Seal permissions describe Seal access and must not be presented as Hose permissions.
- If an identity lookup fails, the generated link remains usable, the command returns `staffName: null` / `identityStatus: "unresolved"`, and a diagnostic is written to `stderr`. Additional role-lookup failure preserves a verified name but returns `roleNames: null`. Never claim that an unresolved identity is an administrator.
- A user-facing link report must include **enterprise name, person's name, verified role/permissions (or explicitly unknown), target system, and exact Beijing expiration time**. Include both a code block and a clickable link. If returning Hose and Seal links together, report identity and permissions separately for each.
- Do not show raw tokens, full phone numbers, or internal IDs as explanatory prose. Do not fetch or list unrelated administrator candidates just to describe the identity of an existing link.
Example presentation: “企业:示例公司;合思登录身份:张三(主管理员);有效期至北京时间 …”;“Seal 登录身份:李四(依据 CLI 返回的管理员标记及权限说明);有效期至北京时间 …”。The names may differ; use each command's actual output.
+139
View File
@@ -0,0 +1,139 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { runCli } from "../runner.js"
const envKeys = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE", "SEAL_DISABLE_BG_UPDATE"] as const
const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
const oldFetch = globalThis.fetch
let dir: string
let requests: Request[]
const fixtures = [
{ id: "warning", result: { decision: "APPROVE", otherFindings: [
{ title: "说明", description: "仅说明", level: "info" },
{ title: "主体差异", description: "付款主体与销方不同", level: "warning" }
] } },
{ id: "error", result: { decision: "REJECT", otherFindings: [{ title: "金额差异", description: "金额不一致", level: "error" }] } },
{ id: "info", result: { otherFindings: [{ title: "说明", description: "无需处理", level: "info" }] } },
{ id: "rule-only", result: { rulesResult: [{ id: "rule-1", findings: [{ level: "error" }] }], otherFindings: [] } },
{ id: "missing", result: {} },
{ id: "malformed", result: { otherFindings: "bad" } }
].map((record, index) => ({
...record, sourceDocumentSN: `SN-${index}`, status: "completed", createdAt: 1792639007830 - index,
pipelineData: { humanResult: index === 0 ? "驳回" : "通过" },
sourceExtendData: { _langfuseTraceId: `trace-${index}` }
}))
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "seal-extra-risk-cli-"))
const enterprises = join(dir, "enterprises")
mkdirSync(enterprises)
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises
process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json")
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
process.env.SEAL_USE_USAGE_FILE = join(dir, "usage.json")
process.env.SEAL_DISABLE_BG_UPDATE = "1"
writeFileSync(join(enterprises, "extra-risk-test.json"), JSON.stringify({
id: "extra-risk-test", name: "Extra Risk Test", environment: "test",
seal: { url: "https://extra-risk.example.test" },
source: { type: "seal", token: "test-token", sealUrl: "https://extra-risk.example.test", staffId: "fixture" }
}))
requests = []
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const request = new Request(input, init)
requests.push(request)
const url = new URL(request.url)
if (request.method !== "GET") return Response.json({ error: "unexpected mutation" }, { status: 405 })
if (url.pathname === "/api/v1/approvals") {
const offset = Number(url.searchParams.get("offset") ?? 0)
const limit = Number(url.searchParams.get("limit") ?? 50)
return Response.json({ data: { records: fixtures.slice(offset, offset + limit), total: 1000 } })
}
const record = fixtures.find(item => url.pathname === `/api/v1/approvals/${item.id}`)
return record ? Response.json({ data: record }) : Response.json({ error: "unexpected read" }, { status: 404 })
}) as typeof fetch
})
afterEach(() => {
for (const key of envKeys) {
if (oldEnv[key] === undefined) delete process.env[key]
else process.env[key] = oldEnv[key]
}
globalThis.fetch = oldFetch
rmSync(dir, { recursive: true, force: true })
})
function cli(...argv: string[]) { return runCli(["approval-runs", ...argv, "--corp", "extra-risk-test"]) }
describe("approval run extra risk CLI", () => {
test("filters the fetched page, preserves upstream totals and aligns bridge to matches", async () => {
const response = await cli("list", "--has-extra-risk", "--limit", "100", "--includeBridge")
expect(response.exitCode).toBe(0)
const data = JSON.parse(response.stdout)
expect(data).toMatchObject({ scanned: 6, matched: 2, unknown: 2, total: 1000 })
expect(data.records.map((record: { id: string }) => record.id)).toEqual(["warning", "error"])
expect(data.records[0]).toMatchObject({
otherFindingCount: 2, extraRiskCount: 1, hasExtraRisk: true, extraFindingsStatus: "known",
extraRisks: [{ title: "主体差异", description: "付款主体与销方不同", level: "warning" }]
})
expect(data.bridge).toHaveLength(2)
expect(requests).toHaveLength(1)
const url = new URL(requests[0]!.url)
expect(url.searchParams.get("limit")).toBe("100")
expect(url.searchParams.has("hasExtraRisk")).toBe(false)
expect(requests.every(request => request.method === "GET")).toBe(true)
})
test("limit and offset apply before filtering without fetching more pages", async () => {
const response = await cli("search", "--has-extra-risk", "--limit", "2", "--offset", "2")
expect(response.exitCode).toBe(0)
expect(JSON.parse(response.stdout)).toMatchObject({ scanned: 2, matched: 0, unknown: 0, total: 1000, records: [] })
expect(requests).toHaveLength(1)
expect(new URL(requests[0]!.url).searchParams.get("offset")).toBe("2")
})
test("combines with human-result filtering and forwards time and status conditions", async () => {
const response = await cli("search", "--has-extra-risk", "--humanResult", "驳回", "--status", "completed", "--startDate", "2026-10-01", "--endDate", "2026-10-22")
expect(response.exitCode).toBe(0)
const data = JSON.parse(response.stdout)
expect(data).toMatchObject({ scanned: 6, matched: 1, unknown: 0 })
expect(data.records.map((record: { id: string }) => record.id)).toEqual(["warning"])
const params = new URL(requests[0]!.url).searchParams
expect(params.get("status[0]")).toBe("completed")
expect(params.get("manualApprovalStatus[0]")).toBe("TERMINATED")
expect(params.get("startDate")).toBe(String(Date.parse("2026-10-01T00:00:00+08:00")))
expect(params.get("endDate")).toBe(String(Date.parse("2026-10-22T23:59:59.999+08:00")))
})
test("unfiltered lists preserve unknown and negative records with compact counts", async () => {
const response = await cli("list")
expect(response.exitCode).toBe(0)
const data = JSON.parse(response.stdout)
expect(data).toMatchObject({ scanned: 6, matched: 6, total: 1000 })
expect(data).not.toHaveProperty("unknown")
expect(data.records[2]).toMatchObject({ otherFindingCount: 1, extraRiskCount: 0, hasExtraRisk: false })
expect(data.records[3]).toMatchObject({ otherFindingCount: 0, extraRiskCount: 0, hasExtraRisk: false })
expect(data.records[4]).toMatchObject({ extraFindingsStatus: "unknown", otherFindingCount: null, extraRiskCount: null, hasExtraRisk: null })
expect(data.records[0]).not.toHaveProperty("extraRisks")
})
test("result and detail summaries expose extra risk counts without replacing existing counts", async () => {
const result = await cli("result", "warning", "--summary")
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({ decision: "APPROVE", extraRiskCount: 1, otherFindingCount: 2, hasExtraRisk: true })
const detail = await cli("get", "warning", "--summary")
expect(detail.exitCode).toBe(0)
expect(JSON.parse(detail.stdout).aiResult).toMatchObject({ extraRiskCount: 1, hasExtraRisk: true })
})
test("supports the camelCase alias and explicit false without filtering", async () => {
const filtered = await cli("list", "--hasExtraRisk")
expect(filtered.exitCode).toBe(0)
expect(JSON.parse(filtered.stdout).matched).toBe(2)
const unfiltered = await cli("list", "--has-extra-risk=false")
expect(unfiltered.exitCode).toBe(0)
expect(JSON.parse(unfiltered.stdout).matched).toBe(6)
})
})
+1
View File
@@ -125,6 +125,7 @@ export async function handleApprovalRunsCommand(
sourceDocumentSN: stringOption(args.options.sourceDocumentSN),
sourceDocumentId: stringOption(args.options.sourceDocumentId),
humanResult: stringOption(args.options.humanResult),
hasExtraRisk: booleanOption(args.options["has-extra-risk"]) ?? booleanOption(args.options.hasExtraRisk),
query: stringOption(args.options.query),
includeBridge: booleanOption(args.options.includeBridge)
},
+24
View File
@@ -62,6 +62,12 @@ describe("auth links", () => {
? input.toString()
: input.url;
const url = new URL(requestUrl);
if (url.pathname === "/api/v1/auth/me") {
return Response.json({ data: {
user: { id: "session-user", tenantId: "tenant", name: "当前Seal人员", isAdmin: true, permissions: ["*"] },
tenant: { id: "tenant", name: "原生 Seal 企业" }
} });
}
if (url.pathname === "/api/v1/delegation/create") {
return new Response(JSON.stringify({
data: {
@@ -86,10 +92,15 @@ describe("auth links", () => {
corpId: "native-corp",
corpName: "原生 Seal 企业",
staffId: "native-staff",
staffName: "当前Seal人员",
identityStatus: "resolved",
isAdmin: true,
permissions: ["*"],
link: "https://native.seal.test/delegation?token=delegation-token",
token: "delegation-token"
});
expect(parsed.url).toBeUndefined();
expect(result.stderr).not.toContain("未能核实");
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
});
@@ -163,6 +174,8 @@ describe("auth links", () => {
expiresInHours: 1
});
expect(floorResult.stderr).toContain("已自动向下取整为 1 小时 (1h)");
expect(JSON.parse(floorResult.stdout)).toMatchObject({ staffName: null, identityStatus: "unresolved", isAdmin: null, permissions: null });
expect(floorResult.stderr).toContain("未能核实实际登录人员姓名");
// Test reject exceeding 7 days (168 hours)
const invalidResult = await runCli(["auth", "link", "--corp", "native-seal", "--expire", "8d"]);
@@ -220,6 +233,12 @@ describe("auth links", () => {
{ status: 200, headers: { "content-type": "application/json" } }
);
}
if (url.pathname === "/api/openapi/v1/staffs/getStaffIds") {
return Response.json({ items: [{ id: "HOSE-CORP:STAFF-1", name: "当前合思人员", active: true, roles: [{ roleDefId: "HOSE-CORP:admin" }] }] });
}
if (url.pathname === "/api/openapi/v1/roleDefGroups") {
return Response.json({ items: [{ id: "system", name: "系统", roleDefs: [{ id: "HOSE-CORP:admin", name: "主管理员" }] }] });
}
return new Response(JSON.stringify({ error: `Unexpected request: ${url.pathname}` }), {
status: 404,
headers: { "content-type": "application/json" }
@@ -234,6 +253,9 @@ describe("auth links", () => {
corpId: "HOSE-CORP",
corpName: "合思测试企业",
staffId: "HOSE-CORP:STAFF-1",
staffName: "当前合思人员",
identityStatus: "resolved",
roleNames: ["主管理员"],
link: "https://app.ekuaibao.com/web/thirdparty.html?accessToken=provisional-token-xyz",
token: "provisional-token-xyz"
});
@@ -315,6 +337,8 @@ describe("auth links", () => {
expireDate: 7200
});
expect(result2.stderr).toContain("已按 2 小时 (7200s) 自动换算");
expect(JSON.parse(result2.stdout)).toMatchObject({ staffName: null, identityStatus: "unresolved", roleNames: null });
expect(result2.stderr).toContain("未能核实实际登录人员姓名");
});
test("runs auth check and hidden aliases (status, diagnose, test)", async () => {
+8 -4
View File
@@ -12,6 +12,7 @@ import { CliError, validationError, usageError } from "../../core/errors.js";
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import { createDelegation, getMe } from "../../domains/seal/api.js";
import { resolveHoseLinkIdentity, resolveSealLinkIdentity, summarizeSealLinkIdentity } from "../../domains/seal/enterprise/assist-identity.js";
import {
booleanOption,
parseDelegationExpireHours,
@@ -59,6 +60,7 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
const delegation = await createDelegation(client, { note, expiresInHours });
printJson({
...summarizeSealLinkIdentity(me.user),
tenant: {
id: me.tenant.id,
name: me.tenant.name,
@@ -115,14 +117,15 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
console.error(`👉 提示: 企业「${corp.name}」源类型为 Seal 原生测试环境,已自动为您生成委托免登直达链接。`);
}
const delegationRecord = delegation as Record<string, unknown>;
const staffName = "staffName" in corp.source && typeof corp.source.staffName === "string" ? corp.source.staffName : undefined;
const expiresAt = formatBeijingIso(Date.now() + expiresInHours * 3600 * 1000);
const identity = await resolveSealLinkIdentity(client);
if (identity.identityStatus === "unresolved") console.error("提示:链接已生成,但未能核实实际登录人员姓名;请勿将 staffId 当作姓名或推断管理员身份。");
printJson({
id: delegationRecord.id,
corpId: corp.source.corpId ?? corp.id,
corpName: corp.name,
staffId: corp.source.staffId,
...(staffName ? { staffName } : {}),
...identity,
link: delegationRecord.link,
expiresAt,
token: delegationRecord.token
@@ -138,13 +141,14 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
booleanOption(args.options.refresh) === true ||
booleanOption(args.options.f) === true;
const provisional = await getHoseProvisionalAuthLink(corp, expiresIn, { force });
const staffName = "staffName" in corp.source && typeof corp.source.staffName === "string" ? corp.source.staffName : undefined;
const expiresAt = formatBeijingIso(Date.now() + expiresIn * 1000);
const identity = await resolveHoseLinkIdentity(corp);
if (identity.identityStatus === "unresolved") console.error("提示:链接已生成,但未能核实实际登录人员姓名;请勿将 staffId 当作姓名或推断管理员身份。");
printJson({
corpId: corp.source.corpId ?? corp.id,
corpName: corp.name,
staffId: corp.source.staffId,
...(staffName ? { staffName } : {}),
...identity,
link: provisional.url,
expiresAt,
token: provisional.token
+2
View File
@@ -80,6 +80,8 @@ describe("corps link onboarding", () => {
expect(result.isError).toBe(false);
expect(JSON.parse(result.stdout)).toMatchObject({
staffName: "Support User",
identityStatus: "resolved",
tenant: {
corpId: "acme-01",
tenantSlug: "acme-01"
+8 -3
View File
@@ -515,7 +515,12 @@ export const HELP_REGISTRY: AreaHelp[] = [
name: "list",
aliases: ["search"],
summary: "Search approval records by keyword, dates, or decision status",
usage: ["seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]"]
usage: ["seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--has-extra-risk] [--limit 20] [--includeBridge true] [--corp <corpId>]"],
options: [
{ flag: "--has-extra-risk", description: "Filter the fetched page to records with warning/error in result.otherFindings; info is excluded. Includes extraRisks with titles, levels and descriptions." },
{ flag: "--limit <n>", description: "Records to scan before local filtering (default 50, maximum 100); no automatic pagination to fill matches" },
{ flag: "--offset <n>", description: "Offset in the upstream result set before local filtering" }
]
},
{
name: "pick",
@@ -1032,7 +1037,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
{ flag: "--from-link <url>", description: "直接由合思协助链接换取 Seal 委托直达链接" }
],
description:
"生成访问当前企业 Seal AI 智能审核后台 (https://<tenant>.sealai.cc/delegate) 的免密直达链接。主体作用于 Seal 审核后台。"
"生成访问当前企业 Seal AI 智能审核后台 (https://<tenant>.sealai.cc/delegate) 的免密直达链接。返回实际会话人员 staffName、identityStatus、isAdmin 和 permissions;姓名查询失败时明确标记为未核实。主体作用于 Seal 审核后台。"
},
{
name: "link list",
@@ -1054,7 +1059,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
{ flag: "--force, --refresh, -f", description: "强制向合思 OpenAPI 申请全新临时凭证" }
],
description:
"专用于合思 (Hose) 来源企业。向合思申请临时 ticket,生成直达外部合思/易快报主站 (https://app.ekuaibao.com/web/thirdparty.html) 的免密登录链接。若需生成 Seal 自身的审核后台访问链接,请使用 'seal-use auth link'。"
"专用于合思 (Hose) 来源企业。向合思申请临时 ticket,生成直达外部合思/易快报主站 (https://app.ekuaibao.com/web/thirdparty.html) 的免密登录链接。自动查询绑定员工的 staffName、identityStatus 和 roleNames;未能核实的姓名或角色明确标记为未知。若需生成 Seal 自身的审核后台访问链接,请使用 'seal-use auth link'。"
},
{
name: "hose-openapi-token",
+1 -1
View File
@@ -29,7 +29,7 @@ export const BOOLEAN_FLAGS = new Set([
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "glossary", "has-input", "has-output", "help",
"hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"has-extra-risk", "hasExtraRisk", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow", "no-glossary",
"no-wait", "noWait", "outbound", "overwrite", "plain", "publish", "quiet",
"r", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
@@ -0,0 +1,54 @@
import { describe, expect, test } from "bun:test"
import { summarizeExtraFindings } from "./extra-findings.js"
describe("extra findings", () => {
test("counts warning/error separately from info and ignores rule-bound findings", () => {
const summary = summarizeExtraFindings({
id: "run-1",
result: {
decision: "APPROVE",
rulesResult: [{ id: "rule-1", findings: [{ level: "error" }] }],
otherFindings: [
{ title: "说明", description: "仅作说明", level: "info" },
{ title: "待核实", description: "凭证主体不同", level: "warning", location: { scope: "FORM", refId: "" } },
{ title: "异常", description: "金额不符", level: "error" }
]
}
}, true)
expect(summary).toEqual({
extraFindingsStatus: "known", otherFindingCount: 3, extraRiskCount: 2, hasExtraRisk: true,
extraRisks: [
{ title: "待核实", description: "凭证主体不同", level: "warning" },
{ title: "异常", description: "金额不符", level: "error" }
]
})
})
test("empty arrays and info-only findings are known negatives regardless of decision", () => {
for (const otherFindings of [[], [{ title: "说明", description: "无需处理", level: "info" }]]) {
expect(summarizeExtraFindings({ id: "run", result: { decision: "REJECT", otherFindings } }, true)).toEqual({
extraFindingsStatus: "known", otherFindingCount: otherFindings.length,
extraRiskCount: 0, hasExtraRisk: false, extraRisks: []
})
}
})
test("missing, unsupported and partially malformed results remain unknown", () => {
for (const result of [
undefined, null, "{}", [], {}, { riskPoints: ["风险"] },
{ otherFindings: null }, { otherFindings: {} }, { otherFindings: [null] },
{ otherFindings: [{ title: "标题", description: "内容", level: "critical" }] },
{ otherFindings: [{ level: "warning" }] },
{ otherFindings: [{ title: "标题", description: "内容", level: "warning" }, "bad"] }
]) {
expect(summarizeExtraFindings({ id: "run", result }, true)).toEqual({
extraFindingsStatus: "unknown", otherFindingCount: null,
extraRiskCount: null, hasExtraRisk: null, extraRisks: null
})
}
})
test("default summaries omit risk detail", () => {
expect(summarizeExtraFindings({ id: "run", result: { otherFindings: [] } })).not.toHaveProperty("extraRisks")
})
})
@@ -0,0 +1,46 @@
import { z } from "zod"
import type { ApprovalRun } from "../types.js"
const extraFindingSchema = z.object({
title: z.string(),
description: z.string(),
level: z.enum(["info", "warning", "error"])
})
const extraFindingsSchema = z.array(extraFindingSchema)
export type ExtraRisk = z.infer<typeof extraFindingSchema>
export type ExtraFindingsSummary = {
extraFindingsStatus: "known" | "unknown";
otherFindingCount: number | null;
extraRiskCount: number | null;
hasExtraRisk: boolean | null;
extraRisks?: ExtraRisk[] | null;
}
/** Only otherFindings classifies rule-independent discoveries; missing data is not a negative. */
export function summarizeExtraFindings(record: ApprovalRun, includeRisks = false): ExtraFindingsSummary {
const result = record.result
const raw = result && typeof result === "object" && !Array.isArray(result)
? (result as Record<string, unknown>).otherFindings
: undefined
const parsed = extraFindingsSchema.safeParse(raw)
if (!parsed.success) {
return {
extraFindingsStatus: "unknown",
otherFindingCount: null,
extraRiskCount: null,
hasExtraRisk: null,
...(includeRisks ? { extraRisks: null } : {})
}
}
const risks = parsed.data.filter(finding => finding.level === "warning" || finding.level === "error")
return {
extraFindingsStatus: "known",
otherFindingCount: parsed.data.length,
extraRiskCount: risks.length,
hasExtraRisk: risks.length > 0,
...(includeRisks ? { extraRisks: risks } : {})
}
}
+13 -2
View File
@@ -6,6 +6,7 @@ import { ensureHoseCloseApiToken } from "../../../core/auth/hose.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs/export.js";
import { summarizeExtraFindings } from "../approval-runs/extra-findings.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
@@ -64,6 +65,7 @@ export const approvalRunsCapabilities = [
sourceDocumentSN: z.string().optional(),
sourceDocumentId: z.string().optional(),
humanResult: z.string().optional().describe("按人工审批结果做本地包含匹配,如 驳回、通过、reject"),
hasExtraRisk: z.boolean().optional().describe("读取当前页后筛选 otherFindings 含 warning/error 的记录;limit 是扫描条数,缺失或异常结果计入 unknown"),
query: z.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配"),
includeBridge: z.boolean().optional().describe("是否返回完整 bridge 数组;默认 false,避免长输出")
}),
@@ -82,6 +84,7 @@ export const approvalRunsCapabilities = [
sourceDocumentSN?: string;
sourceDocumentId?: string;
humanResult?: string;
hasExtraRisk?: boolean;
query?: string;
includeBridge?: boolean;
}
@@ -93,13 +96,21 @@ export const approvalRunsCapabilities = [
endDate: normalizeTimestamp(params.endDate, true),
search: query
}));
const records = await prepareApprovalRuns(client, data.records, {
const prepared = await prepareApprovalRuns(client, data.records, {
humanResult: params.humanResult
});
const analyzed = prepared.map(record => ({ record, findings: summarizeExtraFindings(record, params.hasExtraRisk === true) }));
const selected = params.hasExtraRisk
? analyzed.filter(({ findings }) => findings.hasExtraRisk === true)
: analyzed;
const records = selected.map(({ record }) => record);
return {
...data,
records: records.map(summarizeApprovalRun),
scanned: data.records.length,
matched: records.length,
...(params.hasExtraRisk ? { unknown: analyzed.filter(({ findings }) => findings.extraFindingsStatus === "unknown").length } : {}),
records: selected.map(({ record, findings }) => ({ ...summarizeApprovalRun(record), ...findings })),
...(params.includeBridge ? { bridge: summarizeRunBridge(records) } : {})
};
}
+4 -1
View File
@@ -24,6 +24,7 @@ import type {
WebhookIntegration
} from "../types.js";
import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
import { summarizeExtraFindings, type ExtraFindingsSummary } from "../approval-runs/extra-findings.js";
import type { LocalRuleItem } from "../rules/local.js";
import { loadRuleMappingSnapshot } from "../rules/mapping.js";
import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js";
@@ -55,7 +56,7 @@ export function getConfiguredSealBaseUrl(corp: CorpConfig): string {
return corp.source.sealUrl;
}
export type ApprovalRunSummary = {
export type ApprovalRunSummary = ExtraFindingsSummary & {
id: string;
tenantId?: string;
agentId?: string;
@@ -500,6 +501,7 @@ export function summarizeApprovalRun(record: ApprovalRun): ApprovalRunSummary {
humanResultPath: humanResult?.path,
aiDecision: ai.decision,
aiSummary: ai.summary,
...summarizeExtraFindings(record),
createdAt: record.createdAt,
updatedAt: record.updatedAt
};
@@ -596,6 +598,7 @@ export function summarizeApprovalRunDetail(record: ApprovalRun) {
export function summarizeApprovalRunResult(record: ApprovalRun) {
const result = asRecord(record.result);
return {
...summarizeExtraFindings(record),
recordId: record.id,
sourceDocumentSN: record.sourceDocumentSN,
sourceDocumentId: record.sourceDocumentId,
@@ -0,0 +1,109 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
import { mkdtempSync, rmSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import type { KyInstance } from "ky"
import { CorpConfigSchema } from "../../../core/config/types.js"
import { resolveHoseLinkIdentity, resolveSealLinkIdentity } from "./assist-identity.js"
const originalFetch = globalThis.fetch
const originalStore = process.env.SEAL_USE_TOKEN_STORE
let dir: string
let requests: Array<{ path: string; body?: unknown }>
let staffItems: unknown[]
let roleResponseFails: boolean
let staffResponseFails: boolean
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "seal-assist-identity-"))
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
requests = []
staffItems = [{ id: "CORP:STAFF", name: "实际合思员工", roles: [{ roleDefId: "CORP:admin" }] }]
roleResponseFails = false
staffResponseFails = false
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const request = new Request(input, init)
const path = new URL(request.url).pathname
const body = request.method === "POST" ? await request.json() : undefined
requests.push({ path, body })
if (path === "/api/openapi/v1/auth/getAccessToken") return Response.json({ value: { accessToken: "test-openapi", expireTime: 7200 } })
if (path === "/api/openapi/v1/staffs/getStaffIds") {
return staffResponseFails ? Response.json({ error: "unavailable" }, { status: 403 }) : Response.json({ items: staffItems })
}
if (path === "/api/openapi/v1/roleDefGroups") {
return roleResponseFails ? Response.json({ error: "unavailable" }, { status: 403 }) : Response.json({ items: [
{ id: "roles", name: "系统角色", roleDefs: [{ id: "CORP:admin", name: "主管理员" }] }
] })
}
throw new Error(`Unexpected identity request: ${path}`)
}) as typeof fetch
})
afterEach(() => {
globalThis.fetch = originalFetch
if (originalStore === undefined) delete process.env.SEAL_USE_TOKEN_STORE
else process.env.SEAL_USE_TOKEN_STORE = originalStore
rmSync(dir, { recursive: true, force: true })
})
function hoseCorp(staffId = "STAFF") {
return CorpConfigSchema.parse({
id: "identity-test", name: "Fixture", seal: {},
source: { type: "hose", corpId: "CORP", staffId, domain: "https://hose.example.test", appKey: "key", appSecurity: "secret" }
})
}
describe("assistance link identity", () => {
test("resolves the exact Hose employee and verified role, without unrelated staff or link requests", async () => {
const identity = await resolveHoseLinkIdentity(hoseCorp())
expect(identity).toEqual({ staffName: "实际合思员工", identityStatus: "resolved", roleNames: ["主管理员"] })
expect(requests.find(request => request.path.endsWith("getStaffIds"))?.body).toEqual({ type: "STAFFID", conditionIds: ["CORP:STAFF"] })
expect(requests.map(request => request.path)).toEqual([
"/api/openapi/v1/auth/getAccessToken", "/api/openapi/v1/staffs/getStaffIds", "/api/openapi/v1/roleDefGroups"
])
})
test("canonicalizes bare and qualified staff IDs but rejects other companies and ambiguous matches", async () => {
staffItems = [{ id: "STAFF", name: "短ID员工", roles: [] }]
expect(await resolveHoseLinkIdentity(hoseCorp("CORP:STAFF"))).toMatchObject({ staffName: "短ID员工", roleNames: [] })
for (const items of [
[{ id: "OTHER:STAFF", name: "其他企业员工" }],
[{ id: "CORP:OTHER", name: "其他管理员" }],
[{ id: "STAFF", name: "甲" }, { id: "CORP:STAFF", name: "乙" }],
[{ id: "STAFF", name: " " }]
]) {
staffItems = items
expect(await resolveHoseLinkIdentity(hoseCorp())).toEqual({ staffName: null, identityStatus: "unresolved", roleNames: null })
}
})
test("role lookup failure and unknown role IDs preserve a verified name without inventing permissions", async () => {
roleResponseFails = true
expect(await resolveHoseLinkIdentity(hoseCorp())).toEqual({ staffName: "实际合思员工", identityStatus: "resolved", roleNames: null })
roleResponseFails = false
staffItems = [{ id: "STAFF", name: "员工", roles: [{ roleDefId: "not-visible" }] }]
expect(await resolveHoseLinkIdentity(hoseCorp())).toEqual({ staffName: "员工", identityStatus: "resolved", roleNames: null })
})
test("missing staff visibility is explicitly unresolved", async () => {
staffResponseFails = true
expect(await resolveHoseLinkIdentity(hoseCorp())).toEqual({ staffName: null, identityStatus: "unresolved", roleNames: null })
})
test("Seal identity comes from the actual session and includes its own permission scope", async () => {
const client = { get: () => ({ json: async () => ({ data: {
user: { id: "seal-user", tenantId: "tenant", name: "Seal实际人员", isAdmin: true, permissions: ["*"] },
tenant: { id: "tenant", name: "企业" }
} }) }) } as unknown as KyInstance
expect(await resolveSealLinkIdentity(client)).toEqual({
staffName: "Seal实际人员", identityStatus: "resolved", isAdmin: true, permissions: ["*"]
})
})
test("Seal identity failure returns unknown values, not a guessed employee or administrator", async () => {
const client = { get: () => { throw new Error("private upstream details") } } as unknown as KyInstance
expect(await resolveSealLinkIdentity(client)).toEqual({
staffName: null, identityStatus: "unresolved", isAdmin: null, permissions: null
})
})
})
@@ -0,0 +1,64 @@
import type { KyInstance } from "ky"
import { ensureHoseOpenapiToken, fetchHoseRoleDefGroups, fetchHoseStaffDetails } from "../../../core/auth/hose.js"
import type { CorpConfig } from "../../../core/config/types.js"
import { getMe } from "../api.js"
import type { MeData } from "../types.js"
type LinkIdentity = {
staffName: string | null;
identityStatus: "resolved" | "unresolved";
}
/** Use the actual Seal session user, which may differ from the configured Hose employee. */
export function summarizeSealLinkIdentity(user: MeData["user"]) {
const staffName = user.name.trim() || null
return {
staffName,
identityStatus: staffName ? "resolved" as const : "unresolved" as const,
isAdmin: user.isAdmin,
permissions: user.permissions
}
}
export async function resolveSealLinkIdentity(client: KyInstance) {
try {
return summarizeSealLinkIdentity((await getMe(client)).user)
} catch {
// Identity enrichment must not discard an otherwise valid assistance link.
return { staffName: null, identityStatus: "unresolved" as const, isAdmin: null, permissions: null }
}
}
export async function resolveHoseLinkIdentity(corp: CorpConfig): Promise<LinkIdentity & { roleNames: string[] | null }> {
const unresolved = { staffName: null, identityStatus: "unresolved" as const, roleNames: null }
if (corp.source.type !== "hose") return unresolved
const source = corp.source
const canonicalId = (id: string) => id.includes(":") ? id : `${source.corpId}:${id}`
const targetId = canonicalId(source.staffId)
try {
const token = await ensureHoseOpenapiToken(corp)
const staffs = await fetchHoseStaffDetails(source.domain, token, [targetId])
const matches = staffs.filter(staff => typeof staff.id === "string" && canonicalId(staff.id) === targetId)
const staff = matches.length === 1 ? matches[0] : undefined
if (!staff || typeof staff.name !== "string" || !staff.name.trim()) return unresolved
let roleNames: string[] | null = null
if (Array.isArray(staff.roles)) {
if (staff.roles.length === 0) roleNames = []
else {
try {
const roles = (await fetchHoseRoleDefGroups(source.domain, token)).flatMap(group => group.roleDefs)
const names = staff.roles.map(role => roles.find(item => item.id === role.roleDefId)?.name)
if (names.every((name): name is string => typeof name === "string" && name.trim().length > 0)) {
roleNames = [...new Set(names)]
}
} catch {
// Missing role visibility does not make a verified employee name unknown.
}
}
}
return { staffName: staff.name.trim(), identityStatus: "resolved", roleNames }
} catch {
return unresolved
}
}