bailinghub 0.6.0 → 0.7.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/README.en.md +11 -7
- package/README.md +10 -7
- package/docker-compose.images.yml +2 -2
- package/docs/AGENT_AUTH_API.en.md +112 -1
- package/docs/AGENT_AUTH_API.md +99 -1
- package/docs/AGENT_CLIENT_QUICKSTART.en.md +32 -5
- package/docs/AGENT_CLIENT_QUICKSTART.md +27 -4
- package/docs/AGENT_CLIENT_RUNTIME_API.md +4 -1
- package/docs/AGENT_CONVERSATION_AUDIT.en.md +109 -4
- package/docs/AGENT_CONVERSATION_AUDIT.md +84 -3
- package/docs/AGENT_SUBJECT_DISPLAY.en.md +95 -0
- package/docs/AGENT_SUBJECT_DISPLAY.md +95 -0
- package/docs/AGENT_SYSTEM_INFO.en.md +99 -0
- package/docs/AGENT_SYSTEM_INFO.md +97 -0
- package/docs/CHANGELOG.en.md +25 -2
- package/docs/CHANGELOG.md +24 -1
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/LOCAL_AGENT_SETUP.en.md +116 -0
- package/docs/LOCAL_AGENT_SETUP.md +116 -0
- package/docs/README.en.md +8 -0
- package/docs/README.md +8 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +3 -0
- package/docs/RELEASE_NOTES_NEXT.md +3 -0
- package/docs/RELEASE_NOTES_v0.6.0.en.md +4 -2
- package/docs/RELEASE_NOTES_v0.6.0.md +2 -0
- package/docs/RELEASE_NOTES_v0.6.1.en.md +53 -0
- package/docs/RELEASE_NOTES_v0.6.1.md +53 -0
- package/docs/RELEASE_NOTES_v0.7.0.en.md +116 -0
- package/docs/RELEASE_NOTES_v0.7.0.md +116 -0
- package/docs/SDK.en.md +31 -0
- package/docs/user-guide/conversations.en.md +4 -2
- package/docs/user-guide/conversations.md +4 -2
- package/package.json +1 -1
- package/schemas/config/route.schema.json +15 -2
- package/scripts/check-doc-links.mjs +2 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/install.sh +1 -1
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +2 -0
- package/scripts/sdk-agent-auth-lifecycle-check.mjs +178 -0
- package/scripts/sdk-runtime-test.mjs +5 -2
- package/scripts/verify-github-repo.mjs +2 -0
- package/sdk/php/README.md +29 -0
- package/sdk/php/src/AgentAuth.php +100 -4
- package/sdk/php/src/HubClient.php +2 -1
- package/sdk/php7/README.md +31 -0
- package/sdk/php7/src/AgentAuth.php +99 -4
- package/sdk/php7/src/HubClient.php +2 -1
- package/sql/058_agent_conversation_member_bindings.sql +9 -0
- package/sql/059_agent_subject_display.sql +5 -0
- package/sql/README.en.md +15 -0
- package/sql/README.md +25 -0
- package/src/app/agent-conversation-audit.ts +20 -0
- package/src/app/agent-system-info.ts +41 -0
- package/src/app/agent-tool-invocations.ts +16 -4
- package/src/core/config/agent-setup.ts +37 -0
- package/src/core/config/client-agent-setup.ts +25 -0
- package/src/core/config/config-schema.test.ts +11 -0
- package/src/core/config/route-config.test.ts +28 -0
- package/src/core/config/route-config.ts +43 -4
- package/src/core/contracts/agent-subject-display.test.ts +19 -0
- package/src/core/contracts/agent-subject-display.ts +36 -0
- package/src/core/contracts/types.ts +15 -0
- package/src/core/runtime/agent-conversation-audit.test.ts +19 -1
- package/src/core/runtime/agent-conversation-audit.ts +39 -0
- package/src/infrastructure/config/config-agent-auth-business-sessions.test.ts +120 -0
- package/src/infrastructure/config/config-agent-auth-lifecycle-race.test.ts +152 -0
- package/src/infrastructure/config/config-agent-auth-repository.test.ts +2 -0
- package/src/infrastructure/config/config-agent-auth-repository.ts +208 -18
- package/src/infrastructure/config/config-agent-conversation-audit-cross-binding.test.ts +120 -0
- package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +117 -23
- package/src/infrastructure/config/config-agent-subject-display.test.ts +103 -0
- package/src/infrastructure/config/config-client-repository.ts +21 -0
- package/src/infrastructure/config/config-route-agent-setup.test.ts +59 -0
- package/src/infrastructure/config/config-route-repository.ts +24 -0
- package/src/infrastructure/config/configstore.ts +7 -3
- package/src/infrastructure/schema/core-schema-migrator.test.ts +90 -0
- package/src/routes/admin-access.ts +37 -0
- package/src/routes/admin-agent-clients.ts +11 -0
- package/src/routes/admin-agent-setup.test.ts +130 -0
- package/src/routes/admin-agent-setup.ts +68 -0
- package/src/routes/admin-client-agent-setup.test.ts +93 -0
- package/src/routes/admin-dispatch-config.ts +2 -0
- package/src/routes/agent-api.ts +7 -0
- package/src/routes/agent-auth-lifecycle-http.test.ts +177 -0
- package/src/routes/agent-auth-lifecycle.test.ts +193 -0
- package/src/routes/agent-auth.test.ts +1 -1
- package/src/routes/agent-auth.ts +206 -16
- package/src/routes/agent-conversation-audit-cross-binding-http.test.ts +122 -0
- package/src/routes/agent-conversation-audit.ts +8 -2
- package/src/routes/agent-subject-display-http.test.ts +145 -0
- package/src/routes/agent-system-info.test.ts +132 -0
- package/src/test-support/agent-auth-business-query-fixture.ts +43 -0
- package/src/test-support/agent-auth-lifecycle-fixture.ts +288 -0
- package/src/test-support/agent-conversation-audit-fixture.ts +30 -6
- package/src/test-support/agent-conversation-audit-http-fixture.ts +84 -0
- package/web/connect/bailing-connect-php.tgz +0 -0
- package/web/connect/bailing-connect-php7.tgz +0 -0
- package/web/console/assets/{Accounts-Ca_VnSu9.js → Accounts-ChL9k-XA.js} +1 -1
- package/web/console/assets/AgentClients-Bs7UgVDj.js +1 -0
- package/web/console/assets/AgentClients-DkgPTEbq.css +1 -0
- package/web/console/assets/{Approvals-CMvPWacY.js → Approvals-Bs6FGbp2.js} +1 -1
- package/web/console/assets/{Audit-CIRqOCnL.js → Audit-4WWYhkFM.js} +1 -1
- package/web/console/assets/{BrandLockup-BrytmTTH.js → BrandLockup-D2GhCipL.js} +1 -1
- package/web/console/assets/{Channels-CApxH2TB.js → Channels-CmoGpiCJ.js} +1 -1
- package/web/console/assets/{ChatEntries-CJon3bWJ.js → ChatEntries-BFRMtwta.js} +1 -1
- package/web/console/assets/Clients-CSHIsaWU.css +1 -0
- package/web/console/assets/Clients-DGkkSXyA.js +3 -0
- package/web/console/assets/{Cost-BbhlQFP8.js → Cost-BmGt0MfS.js} +1 -1
- package/web/console/assets/{Credentials-kqr1W0K7.js → Credentials-CR-sYINT.js} +1 -1
- package/web/console/assets/{Diagnostics-Kljt9XTH.js → Diagnostics-DAPbKSJp.js} +1 -1
- package/web/console/assets/{Executors-DnsB-Xz4.js → Executors-CgpiT3o8.js} +1 -1
- package/web/console/assets/{Kb-DLZSAFWP.js → Kb-Cm9dVSQw.js} +1 -1
- package/web/console/assets/{Login-DiTjPWmN.js → Login-CyUcsTZ_.js} +1 -1
- package/web/console/assets/{Projects-CXcVCgCD.js → Projects-DldFPgWg.js} +1 -1
- package/web/console/assets/Routes-DkMIjMQA.css +1 -0
- package/web/console/assets/Routes-DubfjlBD.js +124 -0
- package/web/console/assets/Runs-1hxgkuR4.js +3 -0
- package/web/console/assets/Runs-CvGTV8I-.css +1 -0
- package/web/console/assets/{Setup-FqoCKmfZ.js → Setup-DBLOnI2_.js} +1 -1
- package/web/console/assets/{Shell-BEqpONiy.js → Shell-gJ5Vz_E7.js} +1 -1
- package/web/console/assets/{StorageBuckets-CkORbYXY.js → StorageBuckets-DkDW16tj.js} +1 -1
- package/web/console/assets/{SystemSettings-gTQAazu7.js → SystemSettings-cDkudo2y.js} +1 -1
- package/web/console/assets/{SystemStatus-DAmUUNqO.js → SystemStatus-DZd6s8OX.js} +1 -1
- package/web/console/assets/{Targets-CZmDcjsE.js → Targets-DYNGq1NU.js} +1 -1
- package/web/console/assets/{Tools-CIHInlHL.js → Tools-DpWM59vV.js} +1 -1
- package/web/console/assets/{index-BkLbd7Cc.js → index-DGqs28gI.js} +2 -2
- package/web/console/assets/{request-r7GHVJzw.js → request-B7MLvOqo.js} +1 -1
- package/web/console/assets/{schema-BVn_hB7M.js → schema-CMuwjYdJ.js} +1 -1
- package/web/console/index.html +1 -1
- package/web-admin/scripts/subject-display-ui.mjs +78 -0
- package/web-admin/src/components/AgentSetupPanel.vue +262 -0
- package/web-admin/src/components/ClientConversations.vue +21 -4
- package/web-admin/src/components/conversation-audit.ts +20 -0
- package/web-admin/src/pages/AgentClients.vue +97 -23
- package/web-admin/src/pages/Clients.vue +4 -1
- package/web-admin/src/pages/Routes.vue +10 -1
- package/web-admin/tests/conversation-audit.fixture.mjs +13 -10
- package/web-admin/tests/conversation-audit.test.mjs +63 -1
- package/web/console/assets/AgentClients-BPIvlLYY.js +0 -1
- package/web/console/assets/AgentClients-DsWADpzr.css +0 -1
- package/web/console/assets/Clients-BSA1rlTB.js +0 -3
- package/web/console/assets/Clients-CNIVs7Qn.css +0 -1
- package/web/console/assets/Routes-CXGl9SMM.css +0 -1
- package/web/console/assets/Routes-DN9_d9Po.js +0 -124
- package/web/console/assets/Runs-Cwbe6thL.js +0 -3
- package/web/console/assets/Runs-D8UmjP5G.css +0 -1
|
@@ -2,16 +2,22 @@ import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
|
2
2
|
import { PayloadTooLargeError, readBody, send } from '../app/http';
|
|
3
3
|
import type { AgentToolAuthContext } from '../app/agent-tool-invocations';
|
|
4
4
|
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
5
|
-
import { createConversationAuditFor, confirmConversationAuditFor, appendConversationAuditFor } from '../app/agent-conversation-audit';
|
|
5
|
+
import { createConversationAuditFor, confirmConversationAuditFor, appendConversationAuditFor, conversationAuditCapabilitiesFor } from '../app/agent-conversation-audit';
|
|
6
6
|
import { ConversationAuditError } from '../core/runtime/agent-conversation-audit';
|
|
7
7
|
|
|
8
|
-
/** Agent write-only
|
|
8
|
+
/** Agent write-only ledger; the sole GET exposes capability metadata, never text. */
|
|
9
9
|
export async function handleAgentConversationAuditFor(
|
|
10
10
|
store: ConfigStoreContract | null, auth: AgentToolAuthContext,
|
|
11
11
|
req: IncomingMessage, res: ServerResponse, path: string,
|
|
12
12
|
): Promise<boolean> {
|
|
13
13
|
const base = '/agent-api/v1/conversation-audits';
|
|
14
14
|
if (path !== base && !path.startsWith(`${base}/`)) return false;
|
|
15
|
+
res.setHeader('cache-control', 'no-store');
|
|
16
|
+
if (path === `${base}/capabilities` && req.method === 'GET') {
|
|
17
|
+
try { send(res, 200, await conversationAuditCapabilitiesFor(store)); }
|
|
18
|
+
catch { send(res, 503, { error: 'conversation_audit_unavailable' }); }
|
|
19
|
+
return true;
|
|
20
|
+
}
|
|
15
21
|
const member = path.match(/^\/agent-api\/v1\/conversation-audits\/([0-9a-f-]{36})\/(confirm|events)$/i);
|
|
16
22
|
if (req.method !== 'POST' || (path !== base && !member)) {
|
|
17
23
|
send(res, 404, { error: 'not_found' });
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
import test from 'node:test';
|
|
4
|
+
import type { Pool } from 'mysql2/promise';
|
|
5
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
6
|
+
import { AgentAuthRepository } from '../infrastructure/config/config-agent-auth-repository';
|
|
7
|
+
import { APP, AUTH, SESSION, LedgerFixture, REDIRECT } from '../test-support/agent-auth-lifecycle-fixture';
|
|
8
|
+
import { handleAgentAuthHttpFor, pkceChallenge } from './agent-auth';
|
|
9
|
+
|
|
10
|
+
async function fixture(t: test.TestContext) {
|
|
11
|
+
const ledger = new LedgerFixture();
|
|
12
|
+
// Match production mysql2 timezone:'Z' decoding instead of interpreting SQL
|
|
13
|
+
// DATETIME strings in the developer machine's local timezone.
|
|
14
|
+
function driverRows(result: any[]): any[] {
|
|
15
|
+
if (!Array.isArray(result[0])) return result;
|
|
16
|
+
return [result[0].map((row: Record<string, unknown>) => Object.fromEntries(Object.entries(row).map(([key, value]) => [key,
|
|
17
|
+
key.endsWith('_at') && typeof value === 'string' && /^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/.test(value)
|
|
18
|
+
? new Date(`${value.replace(' ', 'T')}Z`) : value,
|
|
19
|
+
]))), ...result.slice(1)];
|
|
20
|
+
}
|
|
21
|
+
const pool = {
|
|
22
|
+
async getConnection() {
|
|
23
|
+
const connection = await ledger.pool.getConnection();
|
|
24
|
+
return {
|
|
25
|
+
beginTransaction: connection.beginTransaction.bind(connection), commit: connection.commit.bind(connection),
|
|
26
|
+
rollback: connection.rollback.bind(connection), release: connection.release.bind(connection),
|
|
27
|
+
async query(sql: string, params: unknown[] = []) { return driverRows(await connection.query(sql, params)); },
|
|
28
|
+
};
|
|
29
|
+
},
|
|
30
|
+
async query(sql: string, params: unknown[] = []) { return driverRows(await ledger.pool.query(sql, params)); },
|
|
31
|
+
} as unknown as Pool;
|
|
32
|
+
const repository = new AgentAuthRepository(() => pool);
|
|
33
|
+
const verifier = 'v'.repeat(43);
|
|
34
|
+
ledger.rows.authorization.get(AUTH)!.code_challenge = pkceChallenge(verifier);
|
|
35
|
+
const client = { app_id: APP, name: 'Example Service', token: 'synthetic-business', enabled: true,
|
|
36
|
+
agent_authorize_url: 'https://business.example.com/authorize', allowed_routes: ['shop'] };
|
|
37
|
+
const other = { ...client, app_id: 'other-service', token: 'synthetic-other' };
|
|
38
|
+
const store = { agentAuth: repository, clients: {
|
|
39
|
+
getByToken: async (token: string) => token === client.token ? client : token === other.token ? other : null,
|
|
40
|
+
get: async (id: string) => id === client.app_id ? client : id === other.app_id ? other : null,
|
|
41
|
+
} } as unknown as ConfigStoreContract;
|
|
42
|
+
const server = createServer((req, res) => {
|
|
43
|
+
void handleAgentAuthHttpFor({ configStore: store }, req, res, new URL(req.url!, 'http://127.0.0.1'))
|
|
44
|
+
.catch(() => { res.statusCode = 500; res.end('{"error":"synthetic_test_error"}'); });
|
|
45
|
+
});
|
|
46
|
+
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
47
|
+
t.after(() => new Promise<void>((resolve, reject) => { server.closeAllConnections(); server.close((error) => error ? reject(error) : resolve()); }));
|
|
48
|
+
const address = server.address(); assert.ok(address && typeof address === 'object');
|
|
49
|
+
const origin = `http://127.0.0.1:${address.port}`;
|
|
50
|
+
async function call(method: string, path: string, body?: unknown, bearer?: string) {
|
|
51
|
+
const response = await fetch(`${origin}${path}`, { method,
|
|
52
|
+
headers: { 'content-type': 'application/json', ...(bearer ? { authorization: 'Bearer ' + bearer } : {}) },
|
|
53
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }) });
|
|
54
|
+
return { status: response.status, headers: response.headers, body: await response.json() as Record<string, any> };
|
|
55
|
+
}
|
|
56
|
+
const approval = { principal: { id: 'operator-a', tenant: 'account-a', roles: ['manager'] },
|
|
57
|
+
on_behalf_of: 'account-a:operator-a', allowed_routes: ['shop'] };
|
|
58
|
+
async function authorize(display?: unknown) {
|
|
59
|
+
const result = await call('POST', `/agent-auth/v1/authorizations/${AUTH}/approve`, {
|
|
60
|
+
...approval, ...(display === undefined ? {} : { subject_display: display }),
|
|
61
|
+
}, client.token);
|
|
62
|
+
assert.equal(result.status, 200);
|
|
63
|
+
const redirect = new URL(result.body.redirect_uri);
|
|
64
|
+
assert.deepEqual([...redirect.searchParams.keys()].sort(), ['code', 'state']);
|
|
65
|
+
const token = await call('POST', '/agent-auth/v1/token', { grant_type: 'authorization_code', client_app_id: APP,
|
|
66
|
+
code: redirect.searchParams.get('code'), redirect_uri: REDIRECT, code_verifier: verifier });
|
|
67
|
+
assert.equal(token.status, 200);
|
|
68
|
+
return token.body;
|
|
69
|
+
}
|
|
70
|
+
return { ledger, store, call, authorize, approval, client, other };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
test('HTTP approve -> exchange -> session -> in-place rename -> refresh carries only subject display', async (t) => {
|
|
74
|
+
const f = await fixture(t); const token = await f.authorize({ name: ' Workspace North ' });
|
|
75
|
+
assert.deepEqual(token.subject_display, { name: 'Workspace North' });
|
|
76
|
+
assert.equal(token.subject_display_status, 'provided');
|
|
77
|
+
const path = `/agent-auth/v1/sessions/${token.session_id}/subject-display`;
|
|
78
|
+
const before = await f.call('GET', '/agent-auth/v1/session', undefined, token.access_token);
|
|
79
|
+
assert.equal(before.status, 200); assert.equal(before.headers.get('cache-control'), 'no-store');
|
|
80
|
+
const renamed = await f.call('PUT', path, { subject_display: { name: 'Workspace East' } }, f.client.token);
|
|
81
|
+
assert.equal(renamed.status, 200); assert.equal(renamed.body.state, 'active');
|
|
82
|
+
assert.equal(renamed.body.authorization_id, AUTH);
|
|
83
|
+
for (const forbidden of ['access_token', 'refresh_token', 'access_token_hash', 'refresh_token_hash', 'token_hash', 'code']) {
|
|
84
|
+
assert.equal(forbidden in renamed.body, false);
|
|
85
|
+
}
|
|
86
|
+
const after = await f.call('GET', '/agent-auth/v1/session', undefined, token.access_token);
|
|
87
|
+
assert.deepEqual(after.body, { ...before.body, subject_display: { name: 'Workspace East' } });
|
|
88
|
+
const consumed = await f.call('GET', `/agent-auth/v1/authorizations/${AUTH}`, undefined, f.client.token);
|
|
89
|
+
assert.deepEqual(consumed.body.session.subject_display, { name: 'Workspace East' });
|
|
90
|
+
const refreshed = await f.call('POST', '/agent-auth/v1/token', { grant_type: 'refresh_token', client_app_id: APP, refresh_token: token.refresh_token });
|
|
91
|
+
assert.equal(refreshed.status, 200); assert.equal(refreshed.body.session_id, token.session_id);
|
|
92
|
+
assert.deepEqual(refreshed.body.subject_display, { name: 'Workspace East' });
|
|
93
|
+
assert.equal(f.ledger.rows.session.size, 1);
|
|
94
|
+
const clear = await f.call('PUT', path, { subject_display: null }, f.client.token);
|
|
95
|
+
assert.equal(clear.status, 200); assert.equal(clear.body.subject_display_status, 'missing');
|
|
96
|
+
assert.equal(clear.body.subject_display, null);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test('HTTP old unnamed authorization can be backfilled on the original Session', async (t) => {
|
|
100
|
+
const f = await fixture(t); const token = await f.authorize();
|
|
101
|
+
assert.equal(token.subject_display, null); assert.equal(token.subject_display_status, 'missing');
|
|
102
|
+
const before = await f.call('GET', '/agent-auth/v1/session', undefined, token.access_token);
|
|
103
|
+
const result = await f.call('PUT', `/agent-auth/v1/sessions/${token.session_id}/subject-display`, { subject_display: { name: 'Company A' } }, f.client.token);
|
|
104
|
+
assert.equal(result.status, 200);
|
|
105
|
+
const after = await f.call('GET', '/agent-auth/v1/session', undefined, token.access_token);
|
|
106
|
+
assert.deepEqual(after.body, { ...before.body, subject_display: { name: 'Company A' }, subject_display_status: 'provided' });
|
|
107
|
+
assert.equal(f.ledger.rows.session.size, 1); assert.equal(f.ledger.rows.token.size, 1);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test('HTTP display metadata rejects foreign clients, Agent bearers and identity mutations', async (t) => {
|
|
111
|
+
const f = await fixture(t); const token = await f.authorize({ name: 'Account A' });
|
|
112
|
+
const path = `/agent-auth/v1/sessions/${token.session_id}/subject-display`;
|
|
113
|
+
const body = { subject_display: { name: 'Other' } };
|
|
114
|
+
assert.equal((await f.call('PUT', path, body)).status, 401);
|
|
115
|
+
assert.equal((await f.call('PUT', path, body, token.access_token)).status, 401);
|
|
116
|
+
assert.equal((await f.call('PUT', path + '?token=' + f.client.token, body)).status, 401);
|
|
117
|
+
assert.equal((await f.call('PUT', path, body, f.other.token)).status, 404);
|
|
118
|
+
assert.equal((await f.call('POST', path, body, f.client.token)).status, 405);
|
|
119
|
+
assert.equal((await f.call('PUT', `/agent-auth/v1/sessions/${SESSION}/subject-display`, body, f.client.token)).status, 404);
|
|
120
|
+
for (const invalid of [{}, { ...body, principal: { id: 'other' } }, { ...body, allowed_routes: ['other'] },
|
|
121
|
+
{ subject_display: { name: 'A', token: 'synthetic' } }, { subject_display: { name: '\nAccount' } },
|
|
122
|
+
{ subject_display: { name: 'A\u0085B' } }, { subject_display: { name: 'A\u2028B' } }, { subject_display: { name: '\ud800' } },
|
|
123
|
+
{ subject_display: { name: '\udc00' } }, { subject_display: { name: '😀'.repeat(61) } }]) {
|
|
124
|
+
assert.equal((await f.call('PUT', path, invalid, f.client.token)).status, 400);
|
|
125
|
+
}
|
|
126
|
+
await f.ledger.repository.revokeSessionForClient(APP, token.session_id);
|
|
127
|
+
const revoked = await f.call('PUT', path, body, f.client.token);
|
|
128
|
+
assert.equal(revoked.status, 409); assert.equal(revoked.body.error, 'session_inactive');
|
|
129
|
+
assert.equal((await f.call('GET', '/agent-auth/v1/session', undefined, token.access_token)).status, 401);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test('HTTP approve validates optional display before writes; old Host explicitly rejects named approvals', async (t) => {
|
|
133
|
+
const f = await fixture(t); const path = `/agent-auth/v1/authorizations/${AUTH}/approve`;
|
|
134
|
+
for (const display of [{ name: '' }, { name: '\tA' }, { name: 'A'.repeat(121) }, { name: 'A', id: 'foreign' }, { name: ['A'] }]) {
|
|
135
|
+
assert.equal((await f.call('POST', path, { ...f.approval, subject_display: display }, f.client.token)).status, 400);
|
|
136
|
+
}
|
|
137
|
+
assert.equal(f.ledger.rows.authorization.get(AUTH)!.status, 'pending');
|
|
138
|
+
Object.defineProperty(f.store.agentAuth!, 'updateSubjectDisplay', { value: undefined });
|
|
139
|
+
const unsupported = await f.call('POST', path, { ...f.approval, subject_display: { name: 'A' } }, f.client.token);
|
|
140
|
+
assert.equal(unsupported.status, 503); assert.equal(unsupported.body.error, 'subject_display_unavailable');
|
|
141
|
+
assert.equal(f.ledger.rows.authorization.get(AUTH)!.status, 'pending');
|
|
142
|
+
const old = await f.authorize(); assert.equal(old.subject_display_status, 'missing');
|
|
143
|
+
const update = await f.call('PUT', `/agent-auth/v1/sessions/${old.session_id}/subject-display`, { subject_display: { name: 'A' } }, f.client.token);
|
|
144
|
+
assert.equal(update.status, 503); assert.equal(update.body.error, 'subject_display_unavailable');
|
|
145
|
+
});
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import { Readable } from 'node:stream';
|
|
4
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
5
|
+
import type { AgentSession, Client, Route } from '../core/contracts/types';
|
|
6
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
7
|
+
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
8
|
+
import type { ToolProxyDeps } from '../app/tool-proxy';
|
|
9
|
+
import { AgentToolApiError, listAgentToolsFor } from '../app/agent-tool-invocations';
|
|
10
|
+
import { handleAgentApiHttpFor } from './agent-api';
|
|
11
|
+
|
|
12
|
+
class Response {
|
|
13
|
+
statusCode = 0;
|
|
14
|
+
headers: Record<string, unknown> = {};
|
|
15
|
+
body = '';
|
|
16
|
+
setHeader(name: string, value: unknown) { this.headers[name] = value; }
|
|
17
|
+
writeHead(code: number, headers: Record<string, unknown> = {}) { this.statusCode = code; Object.assign(this.headers, headers); }
|
|
18
|
+
end(value = '') { this.body = String(value); }
|
|
19
|
+
json() { return JSON.parse(this.body); }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function fixture() {
|
|
23
|
+
const token = `bha_${'s'.repeat(43)}`;
|
|
24
|
+
const client: Client = {
|
|
25
|
+
app_id: 'helpdesk-client', name: 'Helpdesk Client', token: 'not-returned', enabled: true,
|
|
26
|
+
agent_authorize_url: 'https://helpdesk.example.com/authorize', allowed_routes: ['helpdesk'], allowed_channels: [], rate_limit_per_min: 0,
|
|
27
|
+
};
|
|
28
|
+
const session: AgentSession = {
|
|
29
|
+
session_id: '123e4567-e89b-42d3-a456-426614174000', client_app_id: client.app_id, device_label: 'Untrusted account label',
|
|
30
|
+
principal: { id: 'operator-1', tenant: 'tenant-a', roles: ['staff'] }, on_behalf_of: 'tenant-a:operator-1', allowed_routes: ['helpdesk'],
|
|
31
|
+
created_at: '2026-01-01T00:00:00.000Z', access_expires_at: '2099-01-01T00:00:00.000Z', refresh_expires_at: '2099-01-30T00:00:00.000Z',
|
|
32
|
+
};
|
|
33
|
+
const route: Route = {
|
|
34
|
+
route_key: 'helpdesk', name: 'Internal routing label', enabled: true, target: 'llm', target_config: { system_prompt: 'hidden rules', credential: 'hidden-credential' },
|
|
35
|
+
profile: 'general', session_policy: 'new', audience: { enabled: true, roles: ['staff'], clients: ['helpdesk-client'] },
|
|
36
|
+
agent_client: { enabled: true, instructions: 'hidden local rules', system_info: {
|
|
37
|
+
name: 'Helpdesk', summary: 'Manages customer support tickets.', domains: ['Ticket triage'], boundaries: ['Inventory changes belong to another system.'],
|
|
38
|
+
} },
|
|
39
|
+
tools: { sources: [{ provider: 'helpdesk-tools', allow: ['*'] }], agent_direct: { enabled: true } },
|
|
40
|
+
memory: { recent_messages: 12 }, knowledge: { kb_id: 'hidden-knowledge' },
|
|
41
|
+
};
|
|
42
|
+
let active = true;
|
|
43
|
+
const reads: string[] = [];
|
|
44
|
+
const unexpected = new Proxy({}, { get: (_object, property) => { throw new Error(`Unexpected service access: ${String(property)}`); } });
|
|
45
|
+
const configStore = {
|
|
46
|
+
agentAuth: { getSessionByAccessHash: async () => active ? session : null },
|
|
47
|
+
clients: { get: async () => client },
|
|
48
|
+
routes: { get: async (key: string) => { reads.push(key); return key === route.route_key ? route : null; }, list: () => { throw new Error('Must not enumerate routes'); } },
|
|
49
|
+
toolProviders: unexpected, conversations: unexpected, agentClientRuntime: unexpected,
|
|
50
|
+
} as unknown as ConfigStoreContract;
|
|
51
|
+
async function get(workspace = 'helpdesk', bearer = token) {
|
|
52
|
+
let bodyReads = 0;
|
|
53
|
+
const req = new Readable({ read() { bodyReads++; this.push(null); } }) as IncomingMessage;
|
|
54
|
+
req.method = 'GET'; req.headers = { authorization: `Bearer ${bearer}` };
|
|
55
|
+
const res = new Response();
|
|
56
|
+
await handleAgentApiHttpFor({
|
|
57
|
+
configStore, stateStore: unexpected as RuntimeStateStore, isPaused: () => false,
|
|
58
|
+
handleRun: async () => { throw new Error('Must not start run'); },
|
|
59
|
+
// Deliberately no toolProxyDeps: product descriptions do not load a tool runtime.
|
|
60
|
+
}, req, res as unknown as ServerResponse, new URL(`https://hub.example.com/agent-api/v1/workspaces/${workspace}/system-info`));
|
|
61
|
+
assert.equal(bodyReads, 0);
|
|
62
|
+
return res;
|
|
63
|
+
}
|
|
64
|
+
return { route, client, session, configStore, reads, get, revoke: () => { active = false; } };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
test('system-info reads only the selected binding before tools, body or business runs', async () => {
|
|
68
|
+
const f = fixture();
|
|
69
|
+
const res = await f.get();
|
|
70
|
+
assert.equal(res.statusCode, 200);
|
|
71
|
+
assert.equal(res.headers['cache-control'], 'no-store');
|
|
72
|
+
assert.deepEqual(res.json(), {
|
|
73
|
+
schema_version: 'bailing.agent-system-info.v1',
|
|
74
|
+
binding: { client_app_id: f.client.app_id, session_id: f.session.session_id, workspace: 'helpdesk' },
|
|
75
|
+
metadata_status: 'configured', revision: res.json().revision, system: f.route.agent_client!.system_info,
|
|
76
|
+
tool_status: 'not_loaded', availability: 'unknown',
|
|
77
|
+
});
|
|
78
|
+
assert.match(res.json().revision, /^[a-f0-9]{64}$/);
|
|
79
|
+
assert.deepEqual(f.reads, ['helpdesk']);
|
|
80
|
+
assert.doesNotMatch(res.body, /not-returned|hidden|Untrusted account label|Internal routing label/);
|
|
81
|
+
const same = await f.get();
|
|
82
|
+
assert.equal(same.json().revision, res.json().revision);
|
|
83
|
+
f.route.agent_client!.system_info!.summary = 'Supports ticket review and response drafts.';
|
|
84
|
+
assert.notEqual((await f.get()).json().revision, res.json().revision);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test('system-info remains readable with runtime/direct switches off, without enabling tools', async () => {
|
|
88
|
+
const f = fixture();
|
|
89
|
+
f.route.agent_client!.enabled = false;
|
|
90
|
+
let response = await f.get();
|
|
91
|
+
assert.equal(response.statusCode, 200);
|
|
92
|
+
assert.equal(response.json().metadata_status, 'configured');
|
|
93
|
+
assert.equal(response.json().unavailable_reason, 'agent_client_disabled');
|
|
94
|
+
f.route.agent_client!.enabled = true;
|
|
95
|
+
f.route.tools!.agent_direct = { enabled: false };
|
|
96
|
+
response = await f.get();
|
|
97
|
+
assert.equal(response.json().availability, 'unavailable');
|
|
98
|
+
assert.equal(response.json().unavailable_reason, 'agent_direct_disabled');
|
|
99
|
+
await assert.rejects(listAgentToolsFor({ configStore: f.configStore } as ToolProxyDeps, f, 'helpdesk'),
|
|
100
|
+
(error) => error instanceof AgentToolApiError && error.code === 'agent_direct_disabled');
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test('system-info missing or malformed metadata stays unknown rather than inventing identity', async () => {
|
|
104
|
+
const f = fixture();
|
|
105
|
+
delete f.route.agent_client!.system_info;
|
|
106
|
+
const res = await f.get();
|
|
107
|
+
assert.equal(res.statusCode, 200);
|
|
108
|
+
assert.equal(res.json().metadata_status, 'missing');
|
|
109
|
+
assert.equal(res.json().system, null);
|
|
110
|
+
assert.equal(res.json().revision, null);
|
|
111
|
+
f.route.agent_client!.system_info = { name: 'Helpdesk', summary: '', domains: [], boundaries: [] };
|
|
112
|
+
assert.equal((await f.get()).json().metadata_status, 'missing');
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test('system-info rejects unselected routes and wrong Client/Session/audience without metadata', async () => {
|
|
116
|
+
for (const mutation of ['client-route', 'session-route', 'client-binding', 'audience', 'revoked', 'disabled-route'] as const) {
|
|
117
|
+
const f = fixture();
|
|
118
|
+
if (mutation === 'client-route') f.client.allowed_routes = [];
|
|
119
|
+
if (mutation === 'session-route') f.session.allowed_routes = [];
|
|
120
|
+
if (mutation === 'client-binding') f.client.app_id = 'another-client';
|
|
121
|
+
if (mutation === 'audience') f.session.principal.roles = [];
|
|
122
|
+
if (mutation === 'revoked') f.revoke();
|
|
123
|
+
if (mutation === 'disabled-route') f.route.enabled = false;
|
|
124
|
+
const res = await f.get();
|
|
125
|
+
assert.equal(res.statusCode, mutation === 'revoked' ? 401 : mutation === 'disabled-route' ? 404 : 403, mutation);
|
|
126
|
+
assert.doesNotMatch(res.body, /Manages customer|Ticket triage/);
|
|
127
|
+
}
|
|
128
|
+
const f = fixture();
|
|
129
|
+
const res = await f.get('inventory');
|
|
130
|
+
assert.equal(res.statusCode, 403);
|
|
131
|
+
assert.deepEqual(f.reads, []);
|
|
132
|
+
});
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
|
|
3
|
+
type Row = Record<string, any>;
|
|
4
|
+
|
|
5
|
+
/** Narrow in-memory SELECT evaluator shared by repository and loopback HTTP tests. */
|
|
6
|
+
export function evaluateBusinessSessionQuery(sessions: Row[], authorizations: Row[], sql: string, params: unknown[]): any[] {
|
|
7
|
+
assert.match(sql, /FROM bz_agent_sessions s WHERE s\.client_app_id=\?/);
|
|
8
|
+
assert.doesNotMatch(sql, /SELECT s\.\*|access_token_hash|refresh_token/);
|
|
9
|
+
let index = 0;
|
|
10
|
+
let found: Row[] = sessions.map((row): Row => ({ ...row, principal_json: typeof row.principal_json === 'string' ? JSON.parse(row.principal_json) : row.principal_json })).filter((row) => row.client_app_id === params[index]);
|
|
11
|
+
index++;
|
|
12
|
+
if (sql.includes('AND s.session_id=?')) { const id = params[index++]; found = found.filter((row) => row.session_id === id); }
|
|
13
|
+
if (sql.includes('matched.authorization_id=?')) {
|
|
14
|
+
const id = params[index++];
|
|
15
|
+
found = found.filter((row) => authorizations.some((item) => item.authorization_id === id && item.session_id === row.session_id && item.client_app_id === row.client_app_id && item.status === 'consumed'));
|
|
16
|
+
}
|
|
17
|
+
if (sql.includes('BINARY s.on_behalf_of=BINARY ?')) { const subject = params[index++]; found = found.filter((row) => row.on_behalf_of === subject); }
|
|
18
|
+
if (sql.includes("BINARY JSON_UNQUOTE(JSON_EXTRACT(s.principal_json,'$.id'))=BINARY ?")) {
|
|
19
|
+
const id = params[index++]; found = found.filter((row) => row.principal_json.id === id);
|
|
20
|
+
}
|
|
21
|
+
if (sql.includes("JSON_EXTRACT(s.principal_json,'$.tenant')")) {
|
|
22
|
+
const tenant = params[index++]; found = found.filter((row) => (row.principal_json.tenant ?? '') === tenant);
|
|
23
|
+
}
|
|
24
|
+
if (sql.includes('s.revoked_at IS NULL AND s.refresh_expires_at>?')) {
|
|
25
|
+
const now = String(params[index++]); found = found.filter((row) => !row.revoked_at && row.refresh_expires_at > now);
|
|
26
|
+
} else if (sql.includes('s.revoked_at IS NULL AND s.refresh_expires_at<=?')) {
|
|
27
|
+
const now = String(params[index++]); found = found.filter((row) => !row.revoked_at && row.refresh_expires_at <= now);
|
|
28
|
+
} else if (sql.includes('s.revoked_at IS NOT NULL')) found = found.filter((row) => row.revoked_at);
|
|
29
|
+
if (sql.includes('(s.created_at<? OR (s.created_at=? AND s.session_id<?))')) {
|
|
30
|
+
const created = params[index++]; assert.equal(params[index++], created); const id = params[index++];
|
|
31
|
+
found = found.filter((row) => row.created_at < String(created) || (row.created_at === created && row.session_id < String(id)));
|
|
32
|
+
}
|
|
33
|
+
if (sql.includes('ORDER BY')) {
|
|
34
|
+
assert.match(sql, /ORDER BY s\.created_at DESC,s\.session_id DESC LIMIT \?$/);
|
|
35
|
+
found.sort((a, b) => b.created_at.localeCompare(a.created_at) || b.session_id.localeCompare(a.session_id));
|
|
36
|
+
found = found.slice(0, Number(params[index++]));
|
|
37
|
+
} else found = found.slice(0, 1);
|
|
38
|
+
assert.equal(index, params.length, 'every SQL placeholder has an explicitly consumed value');
|
|
39
|
+
return [found.map((row) => {
|
|
40
|
+
const links = authorizations.filter((item) => item.client_app_id === row.client_app_id && item.session_id === row.session_id && item.status === 'consumed');
|
|
41
|
+
return { ...structuredClone(row), cursor_created_at: `${row.created_at.replace(' ', 'T')}.000Z`, authorization_id: links.length === 1 ? links[0]!.authorization_id : null };
|
|
42
|
+
}), []];
|
|
43
|
+
}
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import type { Pool } from 'mysql2/promise';
|
|
3
|
+
import { AgentAuthRepository } from '../infrastructure/config/config-agent-auth-repository';
|
|
4
|
+
|
|
5
|
+
type Row = Record<string, any>;
|
|
6
|
+
type Table = 'authorization' | 'session' | 'token';
|
|
7
|
+
type Transaction = { id: number; writes: Map<string, Row>; locks: Set<string> };
|
|
8
|
+
|
|
9
|
+
function deferred() {
|
|
10
|
+
let resolve!: () => void;
|
|
11
|
+
const promise = new Promise<void>((done) => { resolve = done; });
|
|
12
|
+
return { promise, resolve };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const AUTH = '11111111-1111-4111-8111-111111111111';
|
|
16
|
+
export const SESSION = '22222222-2222-4222-8222-222222222222';
|
|
17
|
+
export const OTHER_SESSION = '33333333-3333-4333-8333-333333333333';
|
|
18
|
+
export const APP = 'synthetic-shop';
|
|
19
|
+
export const FUTURE = '2099-01-01T00:00:00.000Z';
|
|
20
|
+
export const REDIRECT = 'http://127.0.0.1:43111/callback';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Executes the real repository SQL against a narrow transactional test double.
|
|
24
|
+
* Writes are private until commit; row locks persist through commit/rollback.
|
|
25
|
+
* Locking reads re-read committed rows after waiting. Unknown SQL fails closed.
|
|
26
|
+
* This validates repository scheduling and rollback, not MySQL/InnoDB semantics.
|
|
27
|
+
*/
|
|
28
|
+
export class LedgerFixture {
|
|
29
|
+
readonly rows: Record<Table, Map<string, Row>> = {
|
|
30
|
+
authorization: new Map(), session: new Map(), token: new Map(),
|
|
31
|
+
};
|
|
32
|
+
private sequence = 0;
|
|
33
|
+
private owners = new Map<string, number>();
|
|
34
|
+
private changed = new Map<string, ReturnType<typeof deferred>[]>();
|
|
35
|
+
private blocked = new Map<string, ReturnType<typeof deferred>>();
|
|
36
|
+
private pauseLocks = new Map<string, { arrived: ReturnType<typeof deferred>; resume: ReturnType<typeof deferred> }>();
|
|
37
|
+
private failure?: { fragment: string; error: Error };
|
|
38
|
+
private failCommit = false;
|
|
39
|
+
readonly pool: Pool;
|
|
40
|
+
readonly repository: AgentAuthRepository;
|
|
41
|
+
|
|
42
|
+
constructor() {
|
|
43
|
+
this.rows.authorization.set(AUTH, {
|
|
44
|
+
authorization_id: AUTH, client_app_id: APP, redirect_uri: REDIRECT,
|
|
45
|
+
state_value: 'synthetic-state', requested_routes: '["shop"]', device_label: 'Synthetic device',
|
|
46
|
+
code_challenge: 'synthetic-challenge', status: 'pending', created_at: '2026-01-01 00:00:00',
|
|
47
|
+
expires_at: FUTURE, principal_json: null, allowed_routes: null, on_behalf_of: null,
|
|
48
|
+
code_hash: null, code_expires_at: null, session_id: null,
|
|
49
|
+
});
|
|
50
|
+
this.pool = {
|
|
51
|
+
getConnection: async () => {
|
|
52
|
+
const tx: Transaction = { id: ++this.sequence, writes: new Map(), locks: new Set() };
|
|
53
|
+
return {
|
|
54
|
+
beginTransaction: async () => {},
|
|
55
|
+
query: async (sql: string, params: unknown[] = []) => this.query(tx, sql, params),
|
|
56
|
+
commit: async () => {
|
|
57
|
+
if (this.failCommit) { this.failCommit = false; throw new Error('synthetic commit unavailable'); }
|
|
58
|
+
for (const [key, row] of tx.writes) {
|
|
59
|
+
const colon = key.indexOf(':');
|
|
60
|
+
this.rows[key.slice(0, colon) as Table].set(key.slice(colon + 1), structuredClone(row));
|
|
61
|
+
}
|
|
62
|
+
tx.writes.clear();
|
|
63
|
+
this.unlock(tx);
|
|
64
|
+
},
|
|
65
|
+
rollback: async () => { tx.writes.clear(); this.unlock(tx); },
|
|
66
|
+
release: () => { assert.equal(tx.locks.size, 0, 'connection must not release uncommitted locks'); },
|
|
67
|
+
};
|
|
68
|
+
},
|
|
69
|
+
query: async (sql: string, params: unknown[] = []) => this.query(null, sql, params),
|
|
70
|
+
} as unknown as Pool;
|
|
71
|
+
this.repository = new AgentAuthRepository(() => this.pool);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private all(table: Table, tx: Transaction | null): Row[] {
|
|
75
|
+
const rows = new Map(this.rows[table]);
|
|
76
|
+
for (const [key, row] of tx?.writes ?? []) if (key.startsWith(`${table}:`)) rows.set(key.slice(table.length + 1), row);
|
|
77
|
+
return [...rows.values()].map((row) => structuredClone(row));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
private row(table: Table, id: string, tx: Transaction | null): Row | undefined {
|
|
81
|
+
const value = tx?.writes.get(`${table}:${id}`) ?? this.rows[table].get(id);
|
|
82
|
+
return value ? structuredClone(value) : undefined;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
private async lock(tx: Transaction | null, key: string) {
|
|
86
|
+
assert.ok(tx, 'mutations/locking reads require a transaction');
|
|
87
|
+
while (this.owners.has(key) && this.owners.get(key) !== tx.id) {
|
|
88
|
+
this.blocked.get(key)?.resolve();
|
|
89
|
+
const wake = deferred();
|
|
90
|
+
const waiters = this.changed.get(key) ?? [];
|
|
91
|
+
waiters.push(wake);
|
|
92
|
+
this.changed.set(key, waiters);
|
|
93
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
94
|
+
try {
|
|
95
|
+
await Promise.race([wake.promise, new Promise<never>((_, reject) => {
|
|
96
|
+
timer = setTimeout(() => reject(new Error(`synthetic row-lock timeout: ${key}`)), 2000);
|
|
97
|
+
})]);
|
|
98
|
+
} finally { clearTimeout(timer); this.changed.set(key, (this.changed.get(key) ?? []).filter((item) => item !== wake)); }
|
|
99
|
+
}
|
|
100
|
+
this.owners.set(key, tx.id);
|
|
101
|
+
tx.locks.add(key);
|
|
102
|
+
const pause = this.pauseLocks.get(key);
|
|
103
|
+
if (pause) {
|
|
104
|
+
this.pauseLocks.delete(key);
|
|
105
|
+
pause.arrived.resolve();
|
|
106
|
+
await pause.resume.promise;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
private unlock(tx: Transaction) {
|
|
111
|
+
for (const key of tx.locks) {
|
|
112
|
+
this.owners.delete(key);
|
|
113
|
+
for (const waiter of this.changed.get(key) ?? []) waiter.resolve();
|
|
114
|
+
}
|
|
115
|
+
tx.locks.clear();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
holdNextLock(table: Table, id: string) {
|
|
119
|
+
const pause = { arrived: deferred(), resume: deferred() };
|
|
120
|
+
this.pauseLocks.set(`${table}:${id}`, pause);
|
|
121
|
+
return { arrived: pause.arrived.promise, release: () => pause.resume.resolve() };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
waitForBlocked(table: Table, id: string) {
|
|
125
|
+
const blocked = deferred();
|
|
126
|
+
this.blocked.set(`${table}:${id}`, blocked);
|
|
127
|
+
return blocked.promise;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
failNext(fragment: string) { this.failure = { fragment, error: new Error('synthetic storage unavailable') }; }
|
|
131
|
+
failNextCommit() { this.failCommit = true; }
|
|
132
|
+
|
|
133
|
+
private async save(tx: Transaction | null, table: Table, id: string, row: Row) {
|
|
134
|
+
await this.lock(tx, `${table}:${id}`);
|
|
135
|
+
tx!.writes.set(`${table}:${id}`, structuredClone(row));
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private async query(tx: Transaction | null, originalSql: string, params: unknown[]): Promise<any[]> {
|
|
139
|
+
const sql = originalSql.replace(/\s+/g, ' ').trim();
|
|
140
|
+
const p = params as any[];
|
|
141
|
+
if (this.failure && sql.includes(this.failure.fragment)) {
|
|
142
|
+
const error = this.failure.error; this.failure = undefined; throw error;
|
|
143
|
+
}
|
|
144
|
+
if (sql.startsWith('INSERT INTO bz_agent_authorizations ')) {
|
|
145
|
+
assert.equal(tx, null, 'authorization creation uses an autocommit insert');
|
|
146
|
+
assert.equal(this.rows.authorization.has(p[0]), false, 'duplicate authorization');
|
|
147
|
+
const names = ['authorization_id', 'client_app_id', 'redirect_uri', 'state_value', 'requested_routes', 'device_label', 'code_challenge', 'created_at', 'expires_at'];
|
|
148
|
+
this.rows.authorization.set(p[0], { ...Object.fromEntries(names.map((name, i) => [name, p[i]])), status: 'pending',
|
|
149
|
+
principal_json: null, allowed_routes: null, on_behalf_of: null, code_hash: null, code_expires_at: null, session_id: null });
|
|
150
|
+
return [{ affectedRows: 1 }];
|
|
151
|
+
}
|
|
152
|
+
if (sql.startsWith('SELECT * FROM bz_agent_authorizations WHERE')) {
|
|
153
|
+
const byCode = sql.includes('WHERE code_hash=?');
|
|
154
|
+
const locate = () => byCode ? this.all('authorization', tx).find((row) => row.code_hash === p[0]) : this.row('authorization', p[0], tx);
|
|
155
|
+
const initial = locate();
|
|
156
|
+
if (sql.endsWith('FOR UPDATE') && initial) await this.lock(tx, `authorization:${initial.authorization_id}`);
|
|
157
|
+
const row = locate();
|
|
158
|
+
return [row ? [row] : []];
|
|
159
|
+
}
|
|
160
|
+
if (sql.startsWith('SELECT ') && sql.includes('FROM bz_agent_sessions WHERE session_id=?')) {
|
|
161
|
+
if (sql.endsWith('FOR UPDATE')) await this.lock(tx, `session:${p[0]}`);
|
|
162
|
+
const row = this.row('session', p[0], tx);
|
|
163
|
+
return [row && (!sql.includes('AND client_app_id=?') || row.client_app_id === p[1]) ? [row] : []];
|
|
164
|
+
}
|
|
165
|
+
if (sql.startsWith('SELECT ') && sql.includes('FROM bz_agent_sessions s WHERE s.client_app_id=? AND s.session_id=? LIMIT 1')) {
|
|
166
|
+
const row = this.row('session', p[1], tx);
|
|
167
|
+
if (!row || row.client_app_id !== p[0]) return [[]];
|
|
168
|
+
const linked = this.all('authorization', tx).filter((a) => a.session_id === row.session_id && a.client_app_id === row.client_app_id && a.status === 'consumed');
|
|
169
|
+
return [[{ ...row, authorization_id: linked.length === 1 ? linked[0]!.authorization_id : null }]];
|
|
170
|
+
}
|
|
171
|
+
if (sql.startsWith('SELECT ') && sql.includes('FROM bz_agent_refresh_tokens WHERE token_hash=?')) {
|
|
172
|
+
if (sql.endsWith('FOR UPDATE')) await this.lock(tx, `token:${p[0]}`);
|
|
173
|
+
const row = this.row('token', p[0], tx);
|
|
174
|
+
return [row ? [row] : []];
|
|
175
|
+
}
|
|
176
|
+
if (sql.startsWith('SELECT * FROM bz_agent_sessions WHERE access_token_hash=?')) {
|
|
177
|
+
return [this.all('session', tx).filter((row) => row.access_token_hash === p[0] && !row.revoked_at &&
|
|
178
|
+
String(row.access_expires_at) >= p[1] && String(row.refresh_expires_at) >= p[2])];
|
|
179
|
+
}
|
|
180
|
+
if (sql.startsWith('UPDATE bz_agent_sessions SET last_seen_at=')) return [{ affectedRows: 1 }];
|
|
181
|
+
if (sql.startsWith("UPDATE bz_agent_authorizations SET status='approved'")) {
|
|
182
|
+
assert.equal(p.length, 8);
|
|
183
|
+
const row = this.row('authorization', p[7], tx);
|
|
184
|
+
if (!row || row.status !== 'pending') return [{ affectedRows: 0 }];
|
|
185
|
+
Object.assign(row, { status: 'approved', principal_json: p[0], on_behalf_of: p[1], allowed_routes: p[2], code_hash: p[3], code_expires_at: p[4], approved_at: p[5], subject_display: p[6] });
|
|
186
|
+
await this.save(tx, 'authorization', p[7], row);
|
|
187
|
+
return [{ affectedRows: 1 }];
|
|
188
|
+
}
|
|
189
|
+
if (sql.startsWith("UPDATE bz_agent_authorizations SET status='revoked'")) {
|
|
190
|
+
const row = this.row('authorization', p[0], tx)!;
|
|
191
|
+
Object.assign(row, { status: 'revoked', code_hash: null, code_expires_at: null });
|
|
192
|
+
await this.save(tx, 'authorization', p[0], row);
|
|
193
|
+
return [{ affectedRows: 1 }];
|
|
194
|
+
}
|
|
195
|
+
if (sql.startsWith("UPDATE bz_agent_authorizations SET status='consumed'")) {
|
|
196
|
+
const row = this.row('authorization', p[2], tx);
|
|
197
|
+
if (!row || row.status !== 'approved') return [{ affectedRows: 0 }];
|
|
198
|
+
Object.assign(row, { status: 'consumed', session_id: p[0], consumed_at: p[1] });
|
|
199
|
+
await this.save(tx, 'authorization', p[2], row);
|
|
200
|
+
return [{ affectedRows: 1 }];
|
|
201
|
+
}
|
|
202
|
+
if (sql.startsWith('INSERT INTO bz_agent_sessions ')) {
|
|
203
|
+
assert.equal(this.row('session', p[0], tx), undefined, 'duplicate session');
|
|
204
|
+
const names = ['session_id', 'client_app_id', 'device_label', 'principal_json', 'on_behalf_of', 'allowed_routes', 'access_token_hash', 'access_expires_at', 'refresh_expires_at', 'created_at', 'updated_at', 'subject_display'];
|
|
205
|
+
await this.save(tx, 'session', p[0], { ...Object.fromEntries(names.map((name, i) => [name, p[i]])), revoked_at: null });
|
|
206
|
+
return [{ affectedRows: 1 }];
|
|
207
|
+
}
|
|
208
|
+
if (sql.startsWith('INSERT INTO bz_agent_refresh_tokens ')) {
|
|
209
|
+
assert.equal(this.row('token', p[0], tx), undefined, 'duplicate refresh token');
|
|
210
|
+
await this.save(tx, 'token', p[0], { token_hash: p[0], session_id: p[1], status: 'active', created_at: p[2], expires_at: p[3], used_at: null });
|
|
211
|
+
return [{ affectedRows: 1 }];
|
|
212
|
+
}
|
|
213
|
+
if (sql.startsWith('UPDATE bz_agent_sessions SET revoked_at=')) {
|
|
214
|
+
const row = this.row('session', p[2], tx)!;
|
|
215
|
+
Object.assign(row, { revoked_at: row.revoked_at ?? p[0], updated_at: p[1] });
|
|
216
|
+
await this.save(tx, 'session', p[2], row);
|
|
217
|
+
return [{ affectedRows: 1 }];
|
|
218
|
+
}
|
|
219
|
+
if (sql.startsWith('UPDATE bz_agent_sessions SET access_token_hash=')) {
|
|
220
|
+
const row = this.row('session', p[3], tx);
|
|
221
|
+
if (!row || row.revoked_at) return [{ affectedRows: 0 }];
|
|
222
|
+
Object.assign(row, { access_token_hash: p[0], access_expires_at: p[1], updated_at: p[2] });
|
|
223
|
+
await this.save(tx, 'session', p[3], row);
|
|
224
|
+
return [{ affectedRows: 1 }];
|
|
225
|
+
}
|
|
226
|
+
if (sql === 'UPDATE bz_agent_sessions SET subject_display=?,updated_at=? WHERE session_id=? AND client_app_id=?') {
|
|
227
|
+
const row = this.row('session', p[2], tx);
|
|
228
|
+
if (!row || row.client_app_id !== p[3]) return [{ affectedRows: 0 }];
|
|
229
|
+
Object.assign(row, { subject_display: p[0], updated_at: p[1] });
|
|
230
|
+
await this.save(tx, 'session', p[2], row);
|
|
231
|
+
return [{ affectedRows: 1 }];
|
|
232
|
+
}
|
|
233
|
+
if (sql.startsWith("UPDATE bz_agent_refresh_tokens SET status='used'")) {
|
|
234
|
+
const row = this.row('token', p[1], tx);
|
|
235
|
+
if (!row || row.status !== 'active') return [{ affectedRows: 0 }];
|
|
236
|
+
Object.assign(row, { status: 'used', used_at: p[0] });
|
|
237
|
+
await this.save(tx, 'token', p[1], row);
|
|
238
|
+
return [{ affectedRows: 1 }];
|
|
239
|
+
}
|
|
240
|
+
if (sql.startsWith("UPDATE bz_agent_refresh_tokens SET status='revoked'") || sql.startsWith('UPDATE bz_agent_refresh_tokens SET status=CASE')) {
|
|
241
|
+
const replay = sql.includes('status=CASE');
|
|
242
|
+
const sessionId = p[replay ? 2 : 1];
|
|
243
|
+
let affectedRows = 0;
|
|
244
|
+
for (const row of this.all('token', tx)) {
|
|
245
|
+
if (row.session_id !== sessionId || !(replay ? ['active', 'used'] : ['active']).includes(row.status)) continue;
|
|
246
|
+
await this.lock(tx, `token:${row.token_hash}`);
|
|
247
|
+
const current = this.row('token', row.token_hash, tx)!;
|
|
248
|
+
current.status = replay && row.token_hash === p[0] ? 'replayed' : 'revoked';
|
|
249
|
+
current.used_at ??= p[replay ? 1 : 0];
|
|
250
|
+
await this.save(tx, 'token', row.token_hash, current);
|
|
251
|
+
affectedRows++;
|
|
252
|
+
}
|
|
253
|
+
return [{ affectedRows }];
|
|
254
|
+
}
|
|
255
|
+
throw new Error(`Unsupported lifecycle fixture SQL: ${sql}`);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async approve() {
|
|
259
|
+
const result = await this.repository.approveAuthorization({ authorizationId: AUTH, clientAppId: APP,
|
|
260
|
+
principal: { id: 'synthetic-owner', tenant: 'store-a', roles: ['manager'] }, onBehalfOf: 'store-a',
|
|
261
|
+
allowedRoutes: ['shop'], codeHash: 'synthetic-code-hash', codeExpiresAt: FUTURE });
|
|
262
|
+
assert.equal(result.ok, true);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
exchange() {
|
|
266
|
+
return this.repository.exchangeAuthorizationCode({ codeHash: 'synthetic-code-hash', clientAppId: APP,
|
|
267
|
+
redirectUri: REDIRECT, codeChallenge: 'synthetic-challenge', sessionId: SESSION,
|
|
268
|
+
accessTokenHash: 'access-original', refreshTokenHash: 'refresh-original', accessExpiresAt: FUTURE, refreshExpiresAt: FUTURE });
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
rotate() {
|
|
272
|
+
return this.repository.rotateRefreshToken({ refreshTokenHash: 'refresh-original', clientAppId: APP,
|
|
273
|
+
accessTokenHash: 'access-next', nextRefreshTokenHash: 'refresh-next', accessExpiresAt: FUTURE });
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
revoke() { return this.repository.revokeAuthorization({ authorizationId: AUTH, clientAppId: APP }); }
|
|
277
|
+
|
|
278
|
+
async assertNoCredentialsWork() {
|
|
279
|
+
assert.equal(await this.repository.getSessionByAccessHash('access-original'), null);
|
|
280
|
+
assert.equal(await this.repository.getSessionByAccessHash('access-next'), null);
|
|
281
|
+
for (const hash of ['refresh-original', 'refresh-next']) {
|
|
282
|
+
const result = await this.repository.rotateRefreshToken({ refreshTokenHash: hash, clientAppId: APP,
|
|
283
|
+
accessTokenHash: 'must-not-exist', nextRefreshTokenHash: `must-not-exist-${hash}`, accessExpiresAt: FUTURE });
|
|
284
|
+
assert.equal(result.ok, false, `${hash} cannot issue a new credential`);
|
|
285
|
+
}
|
|
286
|
+
assert.equal([...this.rows.token.values()].some((row) => row.status === 'active'), false);
|
|
287
|
+
}
|
|
288
|
+
}
|