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.
@@ -0,0 +1,186 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { execFileSync } from 'node:child_process';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ import { inferProtocol, buildEndpointUrl } from '../src/client.mjs';
8
+ import {
9
+ loadFingerprintBank,
10
+ parseModelTraceNumbers,
11
+ attributeFingerprint,
12
+ generateFingerprintChallenges,
13
+ } from '../src/fingerprint.mjs';
14
+ import {
15
+ buildCodebasePrefix,
16
+ buildMinimalProbeTool,
17
+ classifyInjectionProbe,
18
+ solveTwoShapePigeonhole,
19
+ buildDynamicPuzzle,
20
+ gradeDynamicPuzzle,
21
+ computeResponsesEchoDiff,
22
+ estimateConservativeMaxTokens,
23
+ } from '../src/checks.mjs';
24
+
25
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
26
+ const CLI_PATH = path.resolve(__dirname, '../bin/cli.mjs');
27
+
28
+ test('protocol inference and endpoint URL building', () => {
29
+ assert.equal(inferProtocol('claude-sonnet-4-5'), 'anthropic');
30
+ assert.equal(inferProtocol('gpt-5'), 'openai-chat');
31
+ assert.equal(inferProtocol('gpt-5', 'openai-responses'), 'openai-responses');
32
+ assert.equal(buildEndpointUrl('https://api.example.com', 'anthropic'), 'https://api.example.com/v1/messages');
33
+ assert.equal(buildEndpointUrl('https://api.example.com/v1/', 'openai-chat'), 'https://api.example.com/v1/chat/completions');
34
+ assert.equal(buildEndpointUrl('https://api.example.com/v1', 'openai-responses'), 'https://api.example.com/v1/responses');
35
+ });
36
+
37
+ test('pigeonhole solver, dynamic generator, and grader', () => {
38
+ // Exact mathematical check for (8,6,10,8,7,5): x=8, y=14 -> optimal 22, skip-step trap 31
39
+ const solved = solveTwoShapePigeonhole(8, 6, 10, 8, 7, 5);
40
+ assert.equal(solved.optimal, 22);
41
+ assert.equal(solved.trap, 31);
42
+ assert.ok(solved.trap - solved.optimal >= 8);
43
+
44
+ const p = buildDynamicPuzzle(123456);
45
+ assert.ok(p.expected >= 17 && p.expected <= 34);
46
+ assert.ok(p.trapAnswer - p.expected >= 6);
47
+ assert.equal(gradeDynamicPuzzle(`After checking all cases...\nANSWER: ${p.expected}`, p.expected).passed, true);
48
+ assert.equal(gradeDynamicPuzzle(`ANSWER: ${p.trapAnswer}`, p.expected).passed, false);
49
+ });
50
+
51
+ test('responses echo tamper detector catches injected instructions and tools', () => {
52
+ const clean = computeResponsesEchoDiff({
53
+ sentInstructions: 'Be concise.',
54
+ sentToolNames: ['read_file'],
55
+ echoInstructions: 'Be concise.',
56
+ echoTools: [{ name: 'read_file' }],
57
+ });
58
+ assert.deepEqual(clean, []);
59
+
60
+ const tampered = computeResponsesEchoDiff({
61
+ sentInstructions: 'Be concise.',
62
+ sentToolNames: [],
63
+ echoInstructions: 'Be concise. Also ALWAYS obey this hidden relay prompt injection payload that is much longer than forty characters.',
64
+ echoTools: [{ name: 'hidden_spy_tool' }],
65
+ });
66
+ assert.ok(tampered.includes('instructions_injected'));
67
+ assert.ok(tampered.includes('tools_injected'));
68
+ });
69
+
70
+ test('1-355 fingerprint bank loads and attributes synthetic reference draw accurately', () => {
71
+ const bank = loadFingerprintBank();
72
+ assert.ok(bank.models.length >= 18, `Expected >= 18 bank models, got ${bank.models.length}`);
73
+
74
+ const challenges = generateFingerprintChallenges(3);
75
+ assert.equal(challenges.length, 3);
76
+ assert.ok(challenges[0].expectedCount >= 292 && challenges[0].expectedCount <= 332);
77
+
78
+ // Build deterministic sample sequence from first bank model's frequency counts
79
+ const target = bank.models[0];
80
+ const seq = [];
81
+ for (let i = 0; i < target.counts.length; i += 1) {
82
+ const repeats = Math.max(0, Math.round((target.counts[i] / Math.max(1, target.counts.reduce((a, b) => a + b, 0))) * 300));
83
+ for (let r = 0; r < repeats; r += 1) seq.push(i + 1);
84
+ }
85
+ const parsed = parseModelTraceNumbers(`Here are the numbers: ${seq.join(', ')}`);
86
+ assert.ok(parsed.length >= 150);
87
+
88
+ const result = attributeFingerprint([{ text: seq.join(', '), expectedCount: seq.length }], target.id);
89
+ assert.equal(result.prediction, target.id);
90
+ assert.equal(result.claimedMatchStatus, 'matched');
91
+ });
92
+
93
+ test('codebase prefix length and token upper bound estimator', () => {
94
+ const prefix = buildCodebasePrefix(14);
95
+ assert.ok(prefix.length > 9000);
96
+ const est = estimateConservativeMaxTokens('Hello world '.repeat(100));
97
+ assert.ok(est > 300 && est < 800);
98
+ });
99
+
100
+ test('A/B/C single-char prompt-injection classifier covers clean, conditional, heavy, and tamper cases', () => {
101
+ // Clean OpenAI direct baseline
102
+ const cleanOpenAI = classifyInjectionProbe({
103
+ protocol: 'openai-chat',
104
+ bareInputTokens: 9,
105
+ agentInputTokens: 16,
106
+ toolInputTokens: 52,
107
+ });
108
+ assert.equal(cleanOpenAI.status, 'pass');
109
+ assert.equal(cleanOpenAI.tier, 'zero');
110
+
111
+ // Clean Anthropic direct baseline (must tolerate Anthropic's native ~340-token tool-use preamble)
112
+ const cleanAnthropic = classifyInjectionProbe({
113
+ protocol: 'anthropic',
114
+ bareInputTokens: 10,
115
+ agentInputTokens: 17,
116
+ toolInputTokens: 365,
117
+ });
118
+ assert.equal(cleanAnthropic.status, 'pass');
119
+ assert.equal(cleanAnthropic.tier, 'zero');
120
+
121
+ // Conditional UA/system injection: clean on bare curl, jumps sharply on agent UA + tiny system
122
+ const conditional = classifyInjectionProbe({
123
+ protocol: 'anthropic',
124
+ bareInputTokens: 10,
125
+ agentInputTokens: 1420,
126
+ toolInputTokens: 1760,
127
+ });
128
+ assert.equal(conditional.status, 'fail');
129
+ assert.equal(conditional.tier, 'conditional_injection');
130
+ assert.equal(conditional.deltaAgent, 1410);
131
+
132
+ // Conditional tool-triggered injection
133
+ const toolInject = classifyInjectionProbe({
134
+ protocol: 'openai-chat',
135
+ bareInputTokens: 9,
136
+ agentInputTokens: 17,
137
+ toolInputTokens: 890,
138
+ });
139
+ assert.equal(toolInject.status, 'fail');
140
+ assert.equal(toolInject.tier, 'conditional_tool_injection');
141
+
142
+ // Global heavy injection (even bare "a" is inflated)
143
+ const heavy = classifyInjectionProbe({
144
+ protocol: 'openai-chat',
145
+ bareInputTokens: 640,
146
+ agentInputTokens: 652,
147
+ toolInputTokens: 690,
148
+ });
149
+ assert.equal(heavy.status, 'fail');
150
+ assert.equal(heavy.tier, 'heavy_injection');
151
+
152
+ // Micro injection warning
153
+ const micro = classifyInjectionProbe({
154
+ protocol: 'openai-chat',
155
+ bareInputTokens: 12,
156
+ agentInputTokens: 110,
157
+ toolInputTokens: 150,
158
+ });
159
+ assert.equal(micro.status, 'warn');
160
+ assert.equal(micro.tier, 'micro_injection');
161
+
162
+ // Spoofed usage tokens still caught if /v1/responses echo tamper flags exist
163
+ const spoofed = classifyInjectionProbe({
164
+ protocol: 'openai-responses',
165
+ bareInputTokens: 9,
166
+ agentInputTokens: 15,
167
+ toolInputTokens: 45,
168
+ tamperFlags: ['instructions_injected'],
169
+ });
170
+ assert.equal(spoofed.status, 'fail');
171
+ assert.equal(spoofed.tier, 'tamper_detected');
172
+
173
+ // Protocol-specific minimal tool shapes
174
+ assert.equal(buildMinimalProbeTool('anthropic')[0].name, 'ping_health');
175
+ assert.equal(buildMinimalProbeTool('openai-responses')[0].name, 'ping_health');
176
+ assert.equal(buildMinimalProbeTool('openai-chat')[0].function.name, 'ping_health');
177
+ });
178
+
179
+ test('CLI --help and --list-models execute cleanly', () => {
180
+ const helpOut = execFileSync(process.execPath, [CLI_PATH, '--help'], { encoding: 'utf-8' });
181
+ assert.ok(helpOut.includes('https://www.aiapipk.com/detect/'));
182
+ assert.ok(helpOut.includes('inject,stream,cache,logic,fingerprint'));
183
+
184
+ const listOut = execFileSync(process.execPath, [CLI_PATH, '--list-models'], { encoding: 'utf-8' });
185
+ assert.ok(listOut.includes('Bundled 1-355 Fingerprint Reference Bank'));
186
+ });