326 lines
11 KiB
JavaScript
326 lines
11 KiB
JavaScript
'use strict';
|
|
const { test } = require('node:test'),
|
|
assert = require('node:assert/strict'),
|
|
fs = require('node:fs/promises'),
|
|
os = require('node:os'),
|
|
path = require('node:path');
|
|
async function fixture(t) {
|
|
const { Store } = require('../../src/modules/dashboard/store.cjs'),
|
|
{ AssistantStore } = require('../../src/modules/assistant/store.cjs'),
|
|
{ AssistantService } = require('../../src/modules/assistant/service.cjs'),
|
|
{ createDashboard } = require('../../src/app/dashboard.cjs');
|
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-workspace-http-')),
|
|
users = new Store(path.join(dir, 'users'));
|
|
users.bootstrap('admin', 'Test-password-123');
|
|
users.addUser({ username: 'member', role: 'operator', password: 'Test-password-123' }, 'admin');
|
|
const store = new AssistantStore(path.join(dir, 'assistant'));
|
|
let calls = 0,
|
|
checks = 0;
|
|
const connections = [
|
|
{ id: 'own', name: 'Member connection', owner: 'member', status: 'connected' },
|
|
{ id: 'foreign', name: 'Foreign connection', owner: 'someone', status: 'connected' },
|
|
];
|
|
const workspace = {
|
|
snapshot: () => ({ connections, exceptions: [] }),
|
|
getConnection: (id) => connections.find((c) => c.id === id),
|
|
};
|
|
const assistant = new AssistantService({
|
|
store,
|
|
workspace,
|
|
dashboard: users,
|
|
storage: {
|
|
store: {
|
|
servers: () => [
|
|
{ id: 'shared', name: 'Shared storage', state: { readable: true }, enabled: true },
|
|
],
|
|
archives: () => [],
|
|
},
|
|
check: () => {
|
|
checks++;
|
|
},
|
|
},
|
|
runtime: {
|
|
chat: async () => {
|
|
calls++;
|
|
return JSON.stringify({ reply: 'diagnosed', actions: [] });
|
|
},
|
|
},
|
|
});
|
|
const server = createDashboard({ store: users, assistant, outputDir: dir });
|
|
await new Promise((r) => server.listen(0, '127.0.0.1', r));
|
|
t.after(async () => {
|
|
server.closeAssistantStreams?.();
|
|
await assistant.stop();
|
|
server.closeAllConnections();
|
|
await new Promise((r) => server.close(r));
|
|
store.close();
|
|
await fs.rm(dir, { recursive: true, force: true });
|
|
});
|
|
const base = 'http://127.0.0.1:' + server.address().port;
|
|
const call = (route, body, cookie, extra = {}) =>
|
|
fetch(base + route, {
|
|
method: body === undefined ? 'GET' : 'POST',
|
|
headers: {
|
|
...(body === undefined ? {} : { Origin: base, 'Content-Type': 'application/json' }),
|
|
...(cookie ? { Cookie: cookie } : {}),
|
|
...extra,
|
|
},
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
});
|
|
const login = async (name) =>
|
|
(await call('/api/login', { username: name, password: 'Test-password-123' })).headers
|
|
.get('set-cookie')
|
|
.split(';')[0];
|
|
return {
|
|
store,
|
|
assistant,
|
|
server,
|
|
users,
|
|
call,
|
|
login,
|
|
base,
|
|
calls: () => calls,
|
|
checks: () => checks,
|
|
};
|
|
}
|
|
test('context reads authorized diagnostics without calling a model or live service', async (t) => {
|
|
const f = await fixture(t),
|
|
cookie = await f.login('member');
|
|
assert.equal((await f.call('/api/assistant/context')).status, 401);
|
|
const r = await f.call('/api/assistant/context', undefined, cookie);
|
|
assert.equal(r.status, 200);
|
|
const data = await r.json();
|
|
assert.deepEqual(
|
|
data.connections.map((c) => c.id),
|
|
['own'],
|
|
);
|
|
assert.ok(data.observedAt);
|
|
assert.equal(f.calls(), 0);
|
|
assert.equal(f.checks(), 0);
|
|
assert.doesNotMatch(JSON.stringify(data), /Foreign connection|password|apiKey/);
|
|
});
|
|
test("diagnosis and recovery cannot use another connection owner's export or archive", async (t) => {
|
|
const f = await fixture(t),
|
|
cookie = await f.login('member');
|
|
f.assistant.deps.dashboard = {
|
|
jobs: () => [
|
|
{ jobId: 'own-pdf', connectionId: 'own' },
|
|
{ jobId: 'other-pdf', connectionId: 'foreign' },
|
|
],
|
|
};
|
|
f.assistant.deps.storage.store.archives = () => [
|
|
{ id: 'mine', jobId: 'own-pdf', serverId: 'shared', status: 'error' },
|
|
{ id: 'secret', jobId: 'other-pdf', serverId: 'shared', status: 'error' },
|
|
];
|
|
const data = await (await f.call('/api/assistant/context', undefined, cookie)).json();
|
|
assert.deepEqual(
|
|
data.jobs.map((x) => x.jobId),
|
|
['own-pdf'],
|
|
);
|
|
assert.deepEqual(
|
|
data.archives.map((x) => x.id),
|
|
['mine'],
|
|
);
|
|
assert.throws(
|
|
() =>
|
|
require('../../src/modules/assistant/policy.cjs').checkAction(
|
|
{ kind: 'retry_archive', targetId: 'secret' },
|
|
f.assistant.deps,
|
|
{ username: 'member', role: 'operator' },
|
|
),
|
|
(e) => e.status === 403,
|
|
);
|
|
});
|
|
test('archive authorization is independent of diagnostic recent-list truncation', async (t) => {
|
|
const f = await fixture(t),
|
|
user = { username: 'member', role: 'operator' },
|
|
target = { id: 'older', jobId: 'old-job', serverId: 'shared', status: 'error' };
|
|
f.assistant.deps.dashboard = {
|
|
recentJobs: () => [],
|
|
job: (id) => (id === 'old-job' ? { jobId: id, connectionId: 'own' } : null),
|
|
};
|
|
f.assistant.deps.storage.store.archives = () => [
|
|
...Array.from({ length: 16 }, (_, i) => ({
|
|
id: 'new-' + i,
|
|
connectionId: 'own',
|
|
serverId: 'shared',
|
|
status: 'error',
|
|
})),
|
|
target,
|
|
];
|
|
assert.doesNotThrow(() =>
|
|
require('../../src/modules/assistant/policy.cjs').checkAction(
|
|
{ kind: 'retry_archive', targetId: 'older' },
|
|
f.assistant.deps,
|
|
user,
|
|
),
|
|
);
|
|
assert.deepEqual(
|
|
require('../../src/modules/assistant/diagnostic-context.cjs').validateDiagnostic(
|
|
{ command: 'archive', targetId: 'older' },
|
|
f.assistant.deps,
|
|
user,
|
|
),
|
|
{ command: 'archive', targetId: 'older' },
|
|
);
|
|
const cookie = await f.login('member'),
|
|
c = await (await f.call('/api/assistant/conversations', {}, cookie)).json();
|
|
let actual;
|
|
f.assistant.runtime.chat = async (input) => {
|
|
actual = input.context;
|
|
return JSON.stringify({ reply: 'diagnosed', actions: [] });
|
|
};
|
|
f.store.saveSettings({
|
|
...f.store.settings(),
|
|
enabled: true,
|
|
runtimePath: process.execPath,
|
|
apiBase: 'https://fixture.example/anthropic',
|
|
model: 'fixture',
|
|
apiKey: 'TEST_ONLY_KEY',
|
|
allowActions: false,
|
|
});
|
|
const sent = await f.call(
|
|
'/api/assistant/conversations/' + c.id + '/messages',
|
|
{ text: '分析旧归档', diagnostic: { command: 'archive', targetId: 'older' } },
|
|
cookie,
|
|
);
|
|
assert.equal(sent.status, 202);
|
|
const turn = await sent.json();
|
|
await f.assistant.running.get(turn.id)?.task;
|
|
assert.equal(actual.selectedTarget.id, 'older');
|
|
});
|
|
test('diagnostic command targets are validated at the API rather than trusted from display names', async (t) => {
|
|
const f = await fixture(t),
|
|
cookie = await f.login('member'),
|
|
created = await (await f.call('/api/assistant/conversations', {}, cookie)).json();
|
|
f.store.saveSettings({
|
|
...f.store.settings(),
|
|
enabled: true,
|
|
runtimePath: process.execPath,
|
|
apiBase: 'https://fixture.example/anthropic',
|
|
model: 'test',
|
|
apiKey: 'TEST_ONLY_KEY',
|
|
allowActions: false,
|
|
});
|
|
const route = '/api/assistant/conversations/' + created.id + '/messages';
|
|
assert.equal(
|
|
(
|
|
await f.call(
|
|
route,
|
|
{ text: 'analyze', diagnostic: { command: 'bpm', targetId: 'foreign' } },
|
|
cookie,
|
|
)
|
|
).status,
|
|
403,
|
|
);
|
|
assert.equal(
|
|
(await f.call(route, { text: 'analyze', diagnostic: { command: 'shell' } }, cookie)).status,
|
|
400,
|
|
);
|
|
const sent = await f.call(
|
|
route,
|
|
{
|
|
text: 'analyze',
|
|
diagnostic: { command: 'bpm', targetId: 'own' },
|
|
requestId: 'diagnostic-test',
|
|
},
|
|
cookie,
|
|
);
|
|
assert.equal(sent.status, 202);
|
|
const turn = await sent.json();
|
|
await f.assistant.running.get(turn.id)?.task;
|
|
assert.equal(f.calls(), 1);
|
|
});
|
|
test('durable event HTTP rejects cross-owner and invalid cursors and SSE can resume then close', async (t) => {
|
|
const f = await fixture(t),
|
|
cookie = await f.login('admin'),
|
|
other = await f.login('member'),
|
|
c = await (await f.call('/api/assistant/conversations', {}, cookie)).json();
|
|
const turn = f.store.beginTurn(
|
|
c.id,
|
|
f.users.users().find((u) => u.username === 'admin').id,
|
|
'sample',
|
|
);
|
|
f.store.updateTurn(turn.id, 'success', { reply: 'answer' });
|
|
const prefix = '/api/assistant/conversations/' + c.id;
|
|
assert.equal((await f.call(prefix + '/events?after=0', undefined, other)).status, 404);
|
|
for (const query of ['-1', '1.5', '999999', 'bad'])
|
|
assert.equal((await f.call(prefix + '/events?after=' + query, undefined, cookie)).status, 400);
|
|
const response = await f.call(prefix + '/events?after=0', undefined, cookie);
|
|
assert.equal(response.status, 200);
|
|
const replay = await response.json();
|
|
assert.ok(replay.events.length >= 2);
|
|
const stream = await f.call(prefix + '/stream?after=0', undefined, cookie, {
|
|
'Last-Event-ID': String(replay.events[0].seq),
|
|
});
|
|
assert.equal(stream.status, 200);
|
|
assert.match(stream.headers.get('content-type'), /text\/event-stream/);
|
|
assert.equal(stream.headers.get('x-accel-buffering'), 'no');
|
|
const reader = stream.body.getReader(),
|
|
first = await reader.read();
|
|
assert.match(new TextDecoder().decode(first.value), /assistant_event/);
|
|
await reader.cancel();
|
|
const state = await (await f.call(prefix, undefined, cookie)).json();
|
|
assert.equal(state.eventCursor, replay.nextCursor);
|
|
});
|
|
test('SSE refuses excess streams and releases resources on shutdown', async (t) => {
|
|
const f = await fixture(t),
|
|
cookie = await f.login('admin'),
|
|
c = await (await f.call('/api/assistant/conversations', {}, cookie)).json(),
|
|
route = '/api/assistant/conversations/' + c.id + '/stream?after=0';
|
|
const a = await f.call(route, undefined, cookie),
|
|
b = await f.call(route, undefined, cookie);
|
|
assert.equal(a.status, 200);
|
|
assert.equal(b.status, 200);
|
|
assert.equal((await f.call(route, undefined, cookie)).status, 429);
|
|
f.server.closeAssistantStreams();
|
|
await a.body.cancel();
|
|
await b.body.cancel();
|
|
});
|
|
test(
|
|
'an open SSE stream terminates after its login cookie is revoked',
|
|
{ timeout: 30000 },
|
|
async (t) => {
|
|
const f = await fixture(t),
|
|
cookie = await f.login('admin'),
|
|
c = await (await f.call('/api/assistant/conversations', {}, cookie)).json();
|
|
const response = await f.call(
|
|
'/api/assistant/conversations/' + c.id + '/stream?after=0',
|
|
undefined,
|
|
cookie,
|
|
),
|
|
reader = response.body.getReader();
|
|
await f.call('/api/logout', {}, cookie);
|
|
let text = '';
|
|
while (true) {
|
|
const part = await reader.read();
|
|
if (part.done) break;
|
|
text += new TextDecoder().decode(part.value);
|
|
}
|
|
assert.match(text, /auth_required/);
|
|
},
|
|
);
|
|
test('title search reaches beyond the visible page and remains owner scoped', async (t) => {
|
|
const f = await fixture(t),
|
|
cookie = await f.login('admin'),
|
|
owner = f.users.users().find((u) => u.username === 'admin').id,
|
|
other = f.users.users().find((u) => u.username === 'member').id;
|
|
for (let i = 0; i < 27; i++) {
|
|
const c = f.store.create(owner);
|
|
f.store.beginTurn(c.id, owner, i === 0 ? 'UNIQUE_OLDER_TITLE' : 'Ordinary ' + i);
|
|
}
|
|
const foreign = f.store.create(other);
|
|
f.store.beginTurn(foreign.id, other, 'UNIQUE_OLDER_TITLE');
|
|
const response = await f.call(
|
|
'/api/assistant/conversations?scope=active&page=1&pageSize=25&query=unique_older_title',
|
|
undefined,
|
|
cookie,
|
|
);
|
|
assert.equal(response.status, 200);
|
|
const result = await response.json();
|
|
assert.equal(result.total, 1);
|
|
assert.equal(result.items[0].title, 'UNIQUE_OLDER_TITLE');
|
|
assert.notEqual(result.items[0].id, foreign.id);
|
|
assert.equal(result.search.truncated, false);
|
|
});
|