gongxiangp2/apps/detail-agent-pi/test/native-bridge-auth.test.mjs

50 lines
2.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { EventEmitter } from 'node:events';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { PassThrough } from 'node:stream';
import { test } from 'node:test';
import { Native98kBroker } from '../src/native-bridge.mjs';
import { cleanup } from './cleanup.mjs';
test('98k 401 preserves the bound authority until a host auth_revoked error arrives', async t => {
const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-native-bridge-auth-'));
t.after(() => cleanup(profile));
const child = new EventEmitter();
for (const stream of ['stdin', 'stdout', 'stderr']) child[stream] = new PassThrough();
child.stdin.once('finish', () => child.emit('close', 0));
const emit = frame => child.stdout.write(JSON.stringify(frame) + '\n');
const routeError = '98k上游线路鉴权异常(HTTP 401),个人Key与素材库登录均有效,请稍后重试或切换模型';
let requests = 0;
child.stdin.on('data', () => {
if (++requests === 1) {
emit({type:'headers', status:401, headers:{}});
emit({type:'error', error:routeError});
} else {
emit({type:'error', error:'授权已失效', category:'auth_revoked', dispatched:false});
}
});
const config = { binary:'fixture', profile, project:randomUUID(), scope:'account-scope' };
const revoked = [];
const broker = new Native98kBroker({ ...config, spawnProcess:() => child });
broker.bind({ ...config, onAuthorizationLost:error => revoked.push(error.category) });
const fetchModel = () => broker.round().fetch('https://api.vip98k.com/v1/chat/completions', {method:'POST', body:'{}'});
try {
const response = await fetchModel();
assert.equal(response.status, 401);
await assert.rejects(response.text(), {message:routeError, category:'failed'});
assert.deepEqual(revoked, []);
await assert.rejects(fetchModel(), {category:'auth_revoked'});
await assert.rejects(fetchModel(), {category:'auth_revoked'});
assert.equal(requests, 2);
assert.deepEqual(revoked, ['auth_revoked']);
} finally {
await broker.close();
child.stdout.end();
child.stderr.end();
}
});