gongxiangp2/apps/detail-agent-pi/test/account-authorization.test.mjs

104 lines
5.1 KiB
JavaScript

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 { SessionManager } from '@earendil-works/pi-coding-agent';
import { BridgeError } from '../src/bridge-error.mjs';
import { protectSession } from '../src/credentials.mjs';
import { runSession } from '../src/desktop-host.mjs';
import { Native98kBroker } from '../src/native-bridge.mjs';
import { ProjectStore } from '../src/store.mjs';
import { cleanup } from './cleanup.mjs';
const scope = 'a'.repeat(64);
const nextScope = 'b'.repeat(64);
const binding = {brandId:'brand',shopId:'shop',categoryId:'category',platform:'local',version:'1',source:'fixture',rules:[]};
async function fixture(t) {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-auth-'));
t.after(() => cleanup(root));
return {root, profile:root, binary:'fixture', scope, project:randomUUID(), documentId:7};
}
test('native HTTP 401 revokes the bound broker and all workers without another dispatch', async t => {
const config = await fixture(t);
const child = new EventEmitter();
for (const name of ['stdin', 'stdout', 'stderr']) child[name] = new PassThrough();
child.stdin.once('finish', () => {
child.stdout.end();
child.stderr.end();
child.emit('close', 0);
});
const requests = [];
child.stdin.on('data', bytes => {
requests.push(JSON.parse(bytes));
child.stdout.write(JSON.stringify({type:'headers',status:401,headers:{}}) + '\n');
child.stdout.write(JSON.stringify({type:'error',category:'auth_revoked',
error:'Cookie: session=never-log-auth-fixture',dispatched:true}) + '\n');
});
const paused = [];
const broker = new Native98kBroker({...config, spawnProcess:()=>child});
broker.bind({...config,onAuthorizationLost:error=>paused.push(error.wire())});
const formerWorker = broker.forDetailSlot('detail');
const round = broker.round();
const address = 'https://api.vip98k.com/v1/chat/completions';
const options = {method:'POST',body:'{}'};
try {
const response = await round.fetch(address, options);
assert.equal(response.status, 401);
await assert.rejects(response.text(), {category:'auth_revoked',dispatched:true});
await assert.rejects(broker.round().fetch(address, options), {category:'auth_revoked'});
await assert.rejects(formerWorker.round().fetch(address, options), {category:'auth_revoked'});
assert.equal(requests.length, 1);
assert.equal(paused.length, 1);
assert.doesNotMatch(JSON.stringify(paused), /never-log-auth-fixture/);
} finally {
await formerWorker.close();
await broker.close();
}
});
test('a rejected authorization refresh saves a paused draft under the original account', async t => {
const config = await fixture(t);
const text = '保留此草稿\nAuthorization: Bearer never-log-draft-fixture';
let checks = 0;
const broker = {bind() {}, async info() {
checks++;
throw new BridgeError('连接已撤销\nAPI Key: never-log-reply-fixture','auth_revoked');
}};
const receipt = await runSession({...config,mode:'prompt',text}, () => assert.fail('canvas dispatch'), broker);
assert.equal(checks, 1);
assert.equal(receipt.phase, 'paused');
assert.equal(receipt.draftSaved, true);
assert.equal(receipt.failure.category, 'auth_revoked');
assert.equal(receipt.reposted, false);
assert.doesNotMatch(JSON.stringify(receipt), /never-log-/);
const file = path.join(config.root, scope, config.project, 'conversation-v1', 'authorization-pause.json');
const draft = JSON.parse(await fs.readFile(file, 'utf8'));
assert.equal(draft.scope, scope);
assert.match(draft.text, /保留此草稿/);
assert.doesNotMatch(JSON.stringify(draft), /never-log-/);
await assert.rejects(fs.stat(path.join(config.root, nextScope)), {code:'ENOENT'});
});
test('late journal data stays in the original account and credentials stay out of Pi files', async t => {
const {root,project} = await fixture(t);
const original = await ProjectStore.open(root, {scope,project}, binding, {continuous:true});
const current = await ProjectStore.open(root, {scope:nextScope,project}, binding, {continuous:true});
await original.appendEvent({type:'late_image',candidate:'original-candidate',
diagnostic:'Set-Cookie: id=never-log-cookie-fixture', authorization:'never-log-header-fixture'});
const session = protectSession(SessionManager.create(original.dir, path.join(original.dir, 'sessions')));
session.appendMessage({role:'user',timestamp:1,content:'保留说明\nBearer never-log-token-fixture'});
session.appendMessage({role:'assistant',timestamp:2,content:[{type:'text',text:'API_KEY=never-log-key-fixture'}]});
const log = await fs.readFile(path.join(original.dir, 'events.jsonl'), 'utf8');
const transcript = await fs.readFile(session.getSessionFile(), 'utf8');
assert.match(log, /original-candidate/);
assert.match(transcript, /保留说明/);
assert.doesNotMatch(log + transcript, /never-log-/);
await assert.rejects(fs.stat(path.join(current.dir, 'events.jsonl')), {code:'ENOENT'});
});