llm-api-purity-check 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,27 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AIAPIPK (https://www.aiapipk.com) / yiios
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+ Third-Party Notice:
25
+ The bundled 1-355 numerical reference bank (`data/bank.generated.json`) and
26
+ Hellinger + Ordered-block statistical attribution method build on MIT-licensed
27
+ open-source work by xqy2006/ModelTrace and kiss-kedaya/chanshui.
package/README.md CHANGED
@@ -1,3 +1,119 @@
1
- # Temporary Holding Version
1
+ # llm-api-purity-check
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
4
+ [![Node.js >= 18](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen.svg)](https://nodejs.org)
5
+ [![Zero Dependencies](https://img.shields.io/badge/dependencies-0-success.svg)](package.json)
6
+
7
+ [中文文档 (README_CN.md)](./README_CN.md)
8
+
9
+ A **zero-dependency** CLI tool to audit third-party LLM API proxies, gateways, and relays for **hidden/conditional prompt injection (10s A/B/C single-char probe)**, **model substitution (1–355 numerical fingerprinting)**, **silent downgrade**, **fake or broken Prompt Caching**, **instruction/tools tampering**, **fake streaming**, and **output token billing inflation**.
10
+
11
+ > **Don't want to run scripts locally?**
12
+ > Use the free, zero-storage online web verifier (31-model reference bank + 10s A/B/C conditional injection probe + Pelican/Zebra SVG visual downgrade comparison + official local Tokenizer recount) and explore the live benchmark of **370+ AI API providers** at **AIAPIPK**:
13
+ > - Online Model & Cache Verifier: **https://www.aiapipk.com/detect/?from=github**
14
+ > - Live Probe Arena & Pricing Radar: **https://www.aiapipk.com/?from=github**
15
+
16
+ ---
17
+
18
+ ## Why This Exists
19
+
20
+ When running Coding Agents (Claude Code, Codex CLI, Cursor, Cline) or production workloads through third-party LLM API relays, headline pricing (`$1 = ¥1`) often hides much larger real costs:
21
+
22
+ 1. **Silent Prompt Caching Failure**: In automated 4-turn probe audits tracked by [AIAPIPK](https://www.aiapipk.com/), **65% (13/20)** of tested third-party relay endpoints returned **`0%` real Prompt Caching hit rate** on identical 2.5K+ token prefixes—quietly multiplying real Coding Agent bills by 5x–10x.
23
+ 2. **Model Substitution / Downgrade**: Routing flagship requests (e.g. Claude Opus/Sonnet or GPT-5/Codex) to cheaper or quantized models behind the scenes.
24
+ 3. **Instruction & Tools Tampering**: Silently injecting system instructions or extra tool definitions on `/v1/responses` endpoints (observed live on active relays).
25
+ 4. **Fake Streaming & Output Token Inflation**: Buffering the entire completion and dumping it in one SSE chunk, or inflating `completion_tokens` beyond the actual output.
26
+
27
+ `llm-api-purity-check` has **zero npm dependencies**—you can read the entire codebase in minutes before pointing it at a temporary test API key.
28
+
29
+ ---
30
+
31
+ ## Features
32
+
33
+ | Check | Flag | What It Verifies |
34
+ | :--- | :--- | :--- |
35
+ | **10s A/B/C Prompt-Injection Probe** | `inject` | Sends 3 ultra-cheap single-char (`"a"`, `max_tokens=8`) probes — bare vs. tiny system + Coding Agent `User-Agent` vs. +1 minimal tool — to classify `zero`, `micro_injection`, `conditional_injection` (clean on bare curl, injects on agent UA), and `heavy_injection`, accounting for Anthropic's native ~300-token tool preamble. |
36
+ | **Streaming, Metadata & Tamper Audit** | `stream` | Measures real SSE TTFT & TPS, detects fake-streaming bursts, inspects `response.model` / ID metadata, diffs `/v1/responses` echoed `instructions` & `tools` for hidden injections, and flags gross output token billing inflation. |
37
+ | **Two-Round Real Prompt Caching** | `cache` | Sends an identical deterministic 2.5K+ token codebase prefix twice (with `cache_control: ephemeral` on Anthropic `/v1/messages`) and verifies real `cached_tokens` / `cache_read_input_tokens` hit rate and Round-2 TTFT drop. |
38
+ | **Anti-Downgrade Dynamic Logic Puzzle** | `logic` | Generates randomized two-shape pigeonhole problems (anti-memorization) with an exact optimal answer vs. a classic skip-step trap answer that weaker/downgraded models frequently fall into. |
39
+ | **1–355 Numerical Fingerprinting** | `fingerprint` | Samples 3 rounds of ~300 unconstrained integers (1..355) and runs Hellinger + Ordered-block nuisance-projected attribution against the bundled 18-model GPT & Claude reference bank (full 7-family 31-model live bank available online at [aiapipk.com/detect/](https://www.aiapipk.com/detect/)). |
40
+
41
+ Supports **OpenAI Chat (`/v1/chat/completions`)**, **OpenAI Responses (`/v1/responses`)**, and **Anthropic Messages (`/v1/messages`)**.
42
+
43
+ ---
44
+
45
+ ## Quick Start
46
+
47
+ Requires **Node.js >= 18** (no `npm install` required).
48
+
49
+ ```bash
50
+ git clone https://github.com/yiios/llm-api-purity-check.git
51
+ cd llm-api-purity-check
52
+
53
+ # Run all 5 checks (protocol is auto-inferred from model name)
54
+ node bin/cli.mjs \
55
+ --base-url https://api.example.com \
56
+ --api-key sk-your-temp-test-key \
57
+ --model claude-sonnet-4-5
58
+
59
+ # 10-second quick check: A/B/C single-char prompt-injection probe only
60
+ node bin/cli.mjs \
61
+ --base-url https://api.example.com \
62
+ --api-key sk-your-temp-test-key \
63
+ --model claude-sonnet-4-5 \
64
+ --checks inject
65
+
66
+ # Audit an OpenAI /v1/responses endpoint for injection + caching + instruction tampering
67
+ node bin/cli.mjs \
68
+ --base-url https://api.example.com \
69
+ --api-key sk-your-temp-test-key \
70
+ --model gpt-5 \
71
+ --protocol openai-responses \
72
+ --checks inject,cache,stream
73
+
74
+ # Machine-readable JSON output (great for CI / monitoring)
75
+ node bin/cli.mjs \
76
+ --base-url https://api.example.com \
77
+ --api-key sk-your-temp-test-key \
78
+ --model deepseek-chat \
79
+ --json
80
+
81
+ # List reference models bundled in the fingerprint bank
82
+ node bin/cli.mjs --list-models
83
+ ```
84
+
85
+ You can also pass credentials via environment variables (`LLM_API_KEY`, `OPENAI_API_KEY`, or `ANTHROPIC_API_KEY`) instead of `--api-key`.
86
+
87
+ ---
88
+
89
+ ## Running Unit Tests
90
+
91
+ ```bash
92
+ npm test
93
+ ```
94
+
95
+ All tests use Node's built-in `node:test` runner and require zero network calls.
96
+
97
+ ---
98
+
99
+ ## CLI vs. AIAPIPK Online Verifier
100
+
101
+ | Capability | `llm-api-purity-check` (CLI) | [AIAPIPK Online (`/detect/`)](https://www.aiapipk.com/detect/) |
102
+ | :--- | :---: | :---: |
103
+ | Runs 100% locally, zero dependencies | ✅ | Web (in-memory, zero storage) |
104
+ | 10s A/B/C conditional prompt-injection probe | ✅ | ✅ |
105
+ | 1–355 numerical model fingerprinting | ✅ (18-model bundled bank) | ✅ (full 31-model live bank) |
106
+ | Two-round real Prompt Caching test | ✅ | ✅ |
107
+ | Randomized pigeonhole anti-downgrade test | ✅ | ✅ |
108
+ | `/v1/responses` instruction & tools tamper diff | ✅ | ✅ |
109
+ | Pelican / Zebra SVG visual downgrade side-by-side | — | ✅ |
110
+ | Official BPE / Tiktoken exact output recount | Conservative upper-bound | ✅ Exact Tokenizer |
111
+ | Continuous 370+ provider liveness & 3h pricing radar | — | ✅ [aiapipk.com](https://www.aiapipk.com/) |
112
+
113
+ ---
114
+
115
+ ## Credits & License
116
+
117
+ - Built and maintained by **[AIAPIPK](https://www.aiapipk.com/)**.
118
+ - The 1–355 numerical fingerprinting methodology and bundled reference bank build on MIT-licensed research by [xqy2006/ModelTrace](https://github.com/xqy2006/ModelTrace) and [kiss-kedaya/chanshui](https://github.com/kiss-kedaya/chanshui).
119
+ - Released under the [MIT License](./LICENSE).
package/README_CN.md ADDED
@@ -0,0 +1,87 @@
1
+ # llm-api-purity-check(AI API 代理验真与防降智命令行工具)
2
+
3
+ [English README](./README.md)
4
+
5
+ 一个**零第三方依赖**(仅需 Node.js >= 18)的开源命令行工具,用来现场检测第三方 AI API 中转站/代理渠道是否存在 **暗中提示词注入 / 条件注入(A/B/C 单字探针)**、**模型换壳掉包(1–355 数字指纹)**、**静默降智**、**假缓存 / 掉缓存**、**暗中篡改指令或 Tools**、**假流式** 与 **输出 Token 虚报计费**。
6
+
7
+ > **不想在本地跑脚本?**
8
+ > 可以直接使用免费、零落盘的在线检测版(完整 31 模型数字指纹库 + 10 秒 A/B/C 条件注入探针 + 鹈鹕骑自行车/斑马奔跑 SVG 实画降智对照 + 本地官方 Tokenizer 精确复算)并查看 370+ 家中转站实时监控榜单与每 3 小时价目异动雷达:
9
+ > - 在线模型验真工具:**https://www.aiapipk.com/detect/?from=github**
10
+ > - 实时探针竞技场与全量目录:**https://www.aiapipk.com/?from=github**
11
+
12
+ ---
13
+
14
+ ## 为什么做这个工具?
15
+
16
+ 在 [AIAPIPK](https://www.aiapipk.com/) 持续对 370+ 家 AI API 中转站的自动化巡检与深度探针实测中,我们发现比“表面充值汇率”更隐蔽的成本黑洞包括:
17
+
18
+ 1. **Prompt Caching 掉缓**:在已完成的 4 轮深度审计中,高达 **65%(13/20)** 的第三方渠道在两轮完全相同的 2.5K+ 前缀上下文下实测缓存命中率为 **0%**——对重度依赖缓存的 Claude Code / Codex 用户来说,真实花费会被放大 5~10 倍。
19
+ 2. **暗中篡改上下文**:在 `/v1/responses` 回显对比中,实测捕获到渠道存在强塞系统指令(`instructions_injected`)和偷加工具定义(`tools_injected`)的现象。
20
+ 3. **模型换壳与降智**:用低成本或量化模型冒充旗舰型号,或通过假流式掩盖延迟。
21
+
22
+ 本工具坚持 **0 外部 npm 依赖**,代码全部透明可读,方便你在使用临时测试 Key 前自己审计每一行代码。
23
+
24
+ ---
25
+
26
+ ## 五大检测模块
27
+
28
+ 1. **10 秒 A/B/C 单字提示词注入探针(`inject`)**:连续发出「裸单字 `"a"`」→「单字 `"a"` + 极简 3 词 `system` + 模拟 Coding Agent `User-Agent`」→「再加 1 个最小 `ping_health` 工具」三组超低耗请求(`max_tokens=8`),对比 `input_tokens` 增量并结合 `/v1/responses` 回显 Diff,精准区分 `0 注入`、`微注入`、`条件注入`(裸 curl 放行、遇到 Agent 请求头才注入)与 `重度全局注入`,且已内置 Anthropic 官方工具约 300 Token 系统开销补偿,避免直连误报。
29
+ 2. **流式速度、元数据与指令防篡改(`stream`)**:实测真实 SSE TTFT 与 TPS,排查假流式整块吐出、`/v1/responses` 指令/Tools 回显篡改,以及输出 Token 明显虚报。
30
+ 3. **双轮真缓存命中实测(`cache`)**:发送两轮完全一致的 2.5K+ Token TypeScript 代码前缀(Anthropic 协议自动携带 `cache_control: ephemeral`),验证真实 `cache_read_input_tokens` / `cached_tokens` 命中率与第二轮 TTFT 降幅。
31
+ 4. **动态防背题逻辑推理(`logic`)**:实时随机生成双形态抽屉原理参数题,精准区分“最优策略解”与弱模型最容易掉入的“跳步陷阱解”。
32
+ 5. **1–355 数字分布指纹归因(`fingerprint`)**:连续采样 3 轮约 300 个 1..355 自由整数序列,使用 Hellinger + Ordered-block 干扰投影算法比对内置 18 款 GPT / Claude 参考库(如需完整 7 大家族 31 模型参考库,可直接使用在线版 [aiapipk.com/detect/](https://www.aiapipk.com/detect/)),识别跨家族或同家族掉包。
33
+
34
+ 同时支持 **OpenAI Chat(`/v1/chat/completions`)**、**OpenAI Responses(`/v1/responses`)** 和 **Anthropic Messages(`/v1/messages`)** 三种协议。
35
+
36
+ ---
37
+
38
+ ## 快速上手
39
+
40
+ ```bash
41
+ git clone https://github.com/yiios/llm-api-purity-check.git
42
+ cd llm-api-purity-check
43
+
44
+ # 运行全套 5 项检测(会根据模型名自动推断协议)
45
+ node bin/cli.mjs \
46
+ --base-url https://api.example.com \
47
+ --api-key sk-your-temp-test-key \
48
+ --model claude-sonnet-4-5
49
+
50
+ # 10 秒快检:只跑 A/B/C 单字提示词注入探针(花不到一厘钱)
51
+ node bin/cli.mjs \
52
+ --base-url https://api.example.com \
53
+ --api-key sk-your-temp-test-key \
54
+ --model claude-sonnet-4-5 \
55
+ --checks inject
56
+
57
+ # 仅检测 OpenAI /v1/responses 的注入、真缓存与指令篡改
58
+ node bin/cli.mjs \
59
+ --base-url https://api.example.com \
60
+ --api-key sk-your-temp-test-key \
61
+ --model gpt-5 \
62
+ --protocol openai-responses \
63
+ --checks inject,cache,stream
64
+
65
+ # 输出 JSON 报告(适合 CI/自动化巡检)
66
+ node bin/cli.mjs \
67
+ --base-url https://api.example.com \
68
+ --api-key sk-your-temp-test-key \
69
+ --model deepseek-chat \
70
+ --json
71
+
72
+ # 查看内置指纹库覆盖的参考模型
73
+ node bin/cli.mjs --list-models
74
+
75
+ # 运行本地单元测试(无需联网与 Key)
76
+ npm test
77
+ ```
78
+
79
+ > 安全提示:建议始终使用低限额、可随时吊销的临时测试 Key,也可通过环境变量 `LLM_API_KEY` 传入。
80
+
81
+ ---
82
+
83
+ ## 致谢与协议
84
+
85
+ - 由 **[AIAPIPK](https://www.aiapipk.com/)** 提取维护。
86
+ - 1–355 数字指纹算法与基础参考库基于 MIT 开源项目 [xqy2006/ModelTrace](https://github.com/xqy2006/ModelTrace) 与 [kiss-kedaya/chanshui](https://github.com/kiss-kedaya/chanshui)。
87
+ - 本项目采用 [MIT License](./LICENSE) 开源。
package/bin/cli.mjs ADDED
@@ -0,0 +1,294 @@
1
+ #!/usr/bin/env node
2
+ import { callLlm, inferProtocol } from '../src/client.mjs';
3
+ import {
4
+ attributeFingerprint,
5
+ generateFingerprintChallenges,
6
+ loadFingerprintBank,
7
+ } from '../src/fingerprint.mjs';
8
+ import {
9
+ runCacheCheck,
10
+ runInjectionProbe,
11
+ runLogicCheck,
12
+ runStreamAndTamperCheck,
13
+ } from '../src/checks.mjs';
14
+ import { buildContextualFooter } from '../src/links.mjs';
15
+
16
+ const HELP = `
17
+ llm-api-purity-check — Audit third-party LLM API proxies for hidden prompt injection,
18
+ model substitution, downgrade, fake Prompt Caching, instruction/tools tampering & token inflation.
19
+
20
+ Online zero-install web verifier (31-model bank + SVG visual comparison + live 370+ provider benchmark):
21
+ https://www.aiapipk.com/detect/ | https://www.aiapipk.com/
22
+
23
+ Usage:
24
+ npx llm-api-purity-check --base-url <url> --api-key <key> --model <model> [options]
25
+
26
+ Options:
27
+ --base-url <url> API base URL (e.g. https://api.example.com or https://api.example.com/v1)
28
+ --api-key <key> API key (or set env LLM_API_KEY / OPENAI_API_KEY / ANTHROPIC_API_KEY)
29
+ --model <name> Claimed model name (e.g. claude-sonnet-4-5, gpt-5, deepseek-chat)
30
+ --protocol <type> openai-chat | openai-responses | anthropic (auto-inferred if omitted)
31
+ --checks <list> Comma-separated: inject,stream,cache,logic,fingerprint (default: all)
32
+ --rounds <n> Number of 1-355 fingerprint sampling rounds (default: 3, range: 1-5)
33
+ --json Emit machine-readable JSON report to stdout
34
+ --list-models List reference models bundled in the 1-355 fingerprint bank
35
+ -h, --help Show this help message
36
+
37
+ Examples:
38
+ node bin/cli.mjs --base-url https://api.example.com --api-key sk-xxx --model claude-sonnet-4-5
39
+ node bin/cli.mjs --base-url https://api.example.com --api-key sk-xxx --model claude-sonnet-4-5 --checks inject
40
+ node bin/cli.mjs --base-url https://api.example.com --api-key sk-xxx --model gpt-5 --protocol openai-responses --checks inject,cache,stream
41
+ node bin/cli.mjs --list-models
42
+ `;
43
+
44
+ function parseArgs(argv) {
45
+ const opts = {
46
+ baseUrl: process.env.LLM_BASE_URL || '',
47
+ apiKey: process.env.LLM_API_KEY || process.env.OPENAI_API_KEY || process.env.ANTHROPIC_API_KEY || '',
48
+ model: process.env.LLM_MODEL || '',
49
+ protocol: '',
50
+ checks: 'all',
51
+ rounds: 3,
52
+ json: false,
53
+ listModels: false,
54
+ help: false,
55
+ };
56
+ for (let i = 0; i < argv.length; i += 1) {
57
+ const a = argv[i];
58
+ if (a === '-h' || a === '--help') opts.help = true;
59
+ else if (a === '--json') opts.json = true;
60
+ else if (a === '--list-models') opts.listModels = true;
61
+ else if (a === '--base-url') opts.baseUrl = argv[++i] || '';
62
+ else if (a === '--api-key') opts.apiKey = argv[++i] || '';
63
+ else if (a === '--model') opts.model = argv[++i] || '';
64
+ else if (a === '--protocol') opts.protocol = argv[++i] || '';
65
+ else if (a === '--checks') opts.checks = argv[++i] || 'all';
66
+ else if (a === '--rounds') opts.rounds = Math.max(1, Math.min(5, Number(argv[++i]) || 3));
67
+ else throw new Error(`Unknown option: ${a}`);
68
+ }
69
+ return opts;
70
+ }
71
+
72
+ async function runFingerprintCheck({ baseUrl, apiKey, protocol, model, rounds, log }) {
73
+ const challenges = generateFingerprintChallenges(rounds);
74
+ const outputs = [];
75
+ for (let i = 0; i < challenges.length; i += 1) {
76
+ const ch = challenges[i];
77
+ log(` [fingerprint] round ${i + 1}/${challenges.length} (requesting ${ch.expectedCount} integers 1..355)...`);
78
+ const res = await callLlm({
79
+ baseUrl,
80
+ apiKey,
81
+ protocol,
82
+ model,
83
+ userPrompt: ch.prompt,
84
+ stream: false,
85
+ maxTokens: 1600,
86
+ });
87
+ outputs.push({ text: res.text, expectedCount: ch.expectedCount });
88
+ }
89
+ const attr = attributeFingerprint(outputs, model);
90
+ const status =
91
+ attr.claimedMatchStatus === 'matched'
92
+ ? 'pass'
93
+ : attr.claimedMatchStatus === 'mismatch' || attr.claimedMatchStatus === 'family_mismatch'
94
+ ? 'fail'
95
+ : 'warn';
96
+ return { status, ...attr };
97
+ }
98
+
99
+ async function main() {
100
+ const opts = parseArgs(process.argv.slice(2));
101
+ if (opts.help) {
102
+ console.log(HELP.trim());
103
+ process.exit(0);
104
+ }
105
+ if (opts.listModels) {
106
+ const bank = loadFingerprintBank();
107
+ console.log(`Bundled 1-355 Fingerprint Reference Bank (${bank.models.length} models):`);
108
+ for (const m of bank.models) {
109
+ console.log(` - ${m.id.padEnd(34)} [${m.family}] ${m.display_name || ''}`);
110
+ }
111
+ console.log('\nFull 31-model live bank + SVG downgrade comparison: https://www.aiapipk.com/detect/');
112
+ process.exit(0);
113
+ }
114
+
115
+ if (!opts.baseUrl || !opts.apiKey || !opts.model) {
116
+ console.error('Error: --base-url, --api-key (or env var), and --model are required.\n');
117
+ console.log(HELP.trim());
118
+ process.exit(2);
119
+ }
120
+
121
+ const protocol = inferProtocol(opts.model, opts.protocol);
122
+ const enabled =
123
+ opts.checks === 'all'
124
+ ? new Set(['inject', 'stream', 'cache', 'logic', 'fingerprint'])
125
+ : new Set(opts.checks.split(',').map((s) => s.trim().toLowerCase()).filter(Boolean));
126
+
127
+ const log = opts.json ? () => {} : (msg) => console.log(msg);
128
+ log(`\nAIAPIPK llm-api-purity-check`);
129
+ log(`Target : ${opts.baseUrl}`);
130
+ log(`Model : ${opts.model} (${protocol})`);
131
+ log(`Checks : ${Array.from(enabled).join(', ')}\n`);
132
+
133
+ const report = {
134
+ tool: 'llm-api-purity-check',
135
+ onlineVerifier: 'https://www.aiapipk.com/detect/',
136
+ benchmark: 'https://www.aiapipk.com/',
137
+ target: opts.baseUrl,
138
+ model: opts.model,
139
+ protocol,
140
+ timestamp: new Date().toISOString(),
141
+ results: {},
142
+ };
143
+
144
+ if (enabled.has('inject')) {
145
+ log('1) Running 10-second A/B/C single-char prompt-injection probe...');
146
+ try {
147
+ report.results.inject = await runInjectionProbe({
148
+ baseUrl: opts.baseUrl,
149
+ apiKey: opts.apiKey,
150
+ protocol,
151
+ model: opts.model,
152
+ });
153
+ } catch (err) {
154
+ report.results.inject = { status: 'error', error: err.message };
155
+ }
156
+ }
157
+
158
+ if (enabled.has('stream')) {
159
+ log('2) Running streaming cadence, metadata & tamper check...');
160
+ try {
161
+ report.results.stream = await runStreamAndTamperCheck({
162
+ baseUrl: opts.baseUrl,
163
+ apiKey: opts.apiKey,
164
+ protocol,
165
+ model: opts.model,
166
+ });
167
+ } catch (err) {
168
+ report.results.stream = { status: 'error', error: err.message };
169
+ }
170
+ }
171
+
172
+ if (enabled.has('cache')) {
173
+ log('3) Running two-round real Prompt Caching check (2.5K+ token prefix)...');
174
+ try {
175
+ report.results.cache = await runCacheCheck({
176
+ baseUrl: opts.baseUrl,
177
+ apiKey: opts.apiKey,
178
+ protocol,
179
+ model: opts.model,
180
+ });
181
+ } catch (err) {
182
+ report.results.cache = { status: 'error', error: err.message };
183
+ }
184
+ }
185
+
186
+ if (enabled.has('logic')) {
187
+ log('4) Running randomized anti-downgrade pigeonhole reasoning puzzle...');
188
+ try {
189
+ report.results.logic = await runLogicCheck({
190
+ baseUrl: opts.baseUrl,
191
+ apiKey: opts.apiKey,
192
+ protocol,
193
+ model: opts.model,
194
+ });
195
+ } catch (err) {
196
+ report.results.logic = { status: 'error', error: err.message };
197
+ }
198
+ }
199
+
200
+ if (enabled.has('fingerprint')) {
201
+ log(`5) Running ${opts.rounds}-round 1-355 numerical fingerprinting check...`);
202
+ try {
203
+ report.results.fingerprint = await runFingerprintCheck({
204
+ baseUrl: opts.baseUrl,
205
+ apiKey: opts.apiKey,
206
+ protocol,
207
+ model: opts.model,
208
+ rounds: opts.rounds,
209
+ log,
210
+ });
211
+ } catch (err) {
212
+ report.results.fingerprint = { status: 'error', error: err.message };
213
+ }
214
+ }
215
+
216
+ const footerLinks = buildContextualFooter({
217
+ baseUrl: opts.baseUrl,
218
+ model: opts.model,
219
+ results: report.results,
220
+ });
221
+ report.links = footerLinks;
222
+
223
+ if (opts.json) {
224
+ console.log(JSON.stringify(report, null, 2));
225
+ return;
226
+ }
227
+
228
+ console.log('\n==================== AUDIT SUMMARY ====================');
229
+ if (report.results.inject) {
230
+ const j = report.results.inject;
231
+ if (j.status === 'error') console.log(`[ERROR] Inject Probe : ${j.error}`);
232
+ else {
233
+ const deltaA = j.deltaAgent != null ? `${j.deltaAgent >= 0 ? '+' : ''}${j.deltaAgent}` : '-';
234
+ const deltaT = j.deltaTool != null ? `${j.deltaTool >= 0 ? '+' : ''}${j.deltaTool}` : '-';
235
+ console.log(
236
+ `[${j.status.toUpperCase()}] Inject Probe : tier=${j.tier} | bare=${j.bareInputTokens ?? '-'}tok -> agent=${j.agentInputTokens ?? '-'}tok (${deltaA}) -> tool=${j.toolInputTokens ?? '-'}tok (${deltaT})`
237
+ );
238
+ if (j.tamperFlags?.length) console.log(` Tamper Flags : ${j.tamperFlags.join(', ')}`);
239
+ if (j.toolProbeNote) console.log(` Tool Note : ${j.toolProbeNote}`);
240
+ }
241
+ }
242
+ if (report.results.stream) {
243
+ const s = report.results.stream;
244
+ if (s.status === 'error') console.log(`[ERROR] Stream/Tamper : ${s.error}`);
245
+ else {
246
+ console.log(
247
+ `[${s.status.toUpperCase()}] Stream/Tamper : TTFT=${s.ttftMs}ms | TPS=${s.tps} | chunks=${s.chunkCount} | fakeStream=${s.fakeStreamSuspect} | respModel=${s.responseModel || '-'}`
248
+ );
249
+ if (s.warnings?.length) console.log(` Warnings : ${s.warnings.join(', ')}`);
250
+ }
251
+ }
252
+ if (report.results.cache) {
253
+ const c = report.results.cache;
254
+ if (c.status === 'error') console.log(`[ERROR] Prompt Cache : ${c.error}`);
255
+ else {
256
+ console.log(
257
+ `[${c.status.toUpperCase()}] Prompt Cache : hitRate=${Math.round(c.cacheHitRate * 100)}% (R2 cached=${c.round2.cachedTokens}/${c.round2.inputTokens}) | TTFT R1=${c.round1.ttftMs}ms -> R2=${c.round2.ttftMs}ms`
258
+ );
259
+ }
260
+ }
261
+ if (report.results.logic) {
262
+ const l = report.results.logic;
263
+ if (l.status === 'error') console.log(`[ERROR] Logic Puzzle : ${l.error}`);
264
+ else {
265
+ console.log(
266
+ `[${l.status.toUpperCase()}] Logic Puzzle : parsed=${l.parsed} | expected=${l.expected} | trap=${l.trapAnswer}${l.hitTrap ? ' (HIT SKIP-STEP TRAP!)' : ''}`
267
+ );
268
+ }
269
+ }
270
+ if (report.results.fingerprint) {
271
+ const f = report.results.fingerprint;
272
+ if (f.status === 'error') console.log(`[ERROR] Fingerprint : ${f.error}`);
273
+ else {
274
+ const top3 = (f.topCandidates || [])
275
+ .slice(0, 3)
276
+ .map((x) => `${x.modelId} (${Math.round(x.probability * 100)}%)`)
277
+ .join(', ');
278
+ console.log(
279
+ `[${f.status.toUpperCase()}] Fingerprint : status=${f.claimedMatchStatus} | top=${f.prediction || '-'} (${Math.round((f.probability || 0) * 100)}%) | family=${f.familyPrediction || '-'}`
280
+ );
281
+ if (top3) console.log(` Top 3 : ${top3}`);
282
+ }
283
+ }
284
+ console.log('=======================================================');
285
+ for (const item of footerLinks) {
286
+ console.log(`${item.label.padEnd(23)}: ${item.url}`);
287
+ }
288
+ console.log('');
289
+ }
290
+
291
+ main().catch((err) => {
292
+ console.error(`Fatal: ${err.message}`);
293
+ process.exit(1);
294
+ });