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.
Files changed (149) hide show
  1. package/README.en.md +11 -7
  2. package/README.md +10 -7
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/AGENT_AUTH_API.en.md +112 -1
  5. package/docs/AGENT_AUTH_API.md +99 -1
  6. package/docs/AGENT_CLIENT_QUICKSTART.en.md +32 -5
  7. package/docs/AGENT_CLIENT_QUICKSTART.md +27 -4
  8. package/docs/AGENT_CLIENT_RUNTIME_API.md +4 -1
  9. package/docs/AGENT_CONVERSATION_AUDIT.en.md +109 -4
  10. package/docs/AGENT_CONVERSATION_AUDIT.md +84 -3
  11. package/docs/AGENT_SUBJECT_DISPLAY.en.md +95 -0
  12. package/docs/AGENT_SUBJECT_DISPLAY.md +95 -0
  13. package/docs/AGENT_SYSTEM_INFO.en.md +99 -0
  14. package/docs/AGENT_SYSTEM_INFO.md +97 -0
  15. package/docs/CHANGELOG.en.md +25 -2
  16. package/docs/CHANGELOG.md +24 -1
  17. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  18. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  19. package/docs/LOCAL_AGENT_SETUP.en.md +116 -0
  20. package/docs/LOCAL_AGENT_SETUP.md +116 -0
  21. package/docs/README.en.md +8 -0
  22. package/docs/README.md +8 -0
  23. package/docs/RELEASE_NOTES_NEXT.en.md +3 -0
  24. package/docs/RELEASE_NOTES_NEXT.md +3 -0
  25. package/docs/RELEASE_NOTES_v0.6.0.en.md +4 -2
  26. package/docs/RELEASE_NOTES_v0.6.0.md +2 -0
  27. package/docs/RELEASE_NOTES_v0.6.1.en.md +53 -0
  28. package/docs/RELEASE_NOTES_v0.6.1.md +53 -0
  29. package/docs/RELEASE_NOTES_v0.7.0.en.md +116 -0
  30. package/docs/RELEASE_NOTES_v0.7.0.md +116 -0
  31. package/docs/SDK.en.md +31 -0
  32. package/docs/user-guide/conversations.en.md +4 -2
  33. package/docs/user-guide/conversations.md +4 -2
  34. package/package.json +1 -1
  35. package/schemas/config/route.schema.json +15 -2
  36. package/scripts/check-doc-links.mjs +2 -0
  37. package/scripts/check-image-tags.sh +1 -1
  38. package/scripts/check-release-consistency.test.mjs +2 -2
  39. package/scripts/install.sh +1 -1
  40. package/scripts/publish-images.sh +1 -1
  41. package/scripts/release-audit.mjs +2 -0
  42. package/scripts/sdk-agent-auth-lifecycle-check.mjs +178 -0
  43. package/scripts/sdk-runtime-test.mjs +5 -2
  44. package/scripts/verify-github-repo.mjs +2 -0
  45. package/sdk/php/README.md +29 -0
  46. package/sdk/php/src/AgentAuth.php +100 -4
  47. package/sdk/php/src/HubClient.php +2 -1
  48. package/sdk/php7/README.md +31 -0
  49. package/sdk/php7/src/AgentAuth.php +99 -4
  50. package/sdk/php7/src/HubClient.php +2 -1
  51. package/sql/058_agent_conversation_member_bindings.sql +9 -0
  52. package/sql/059_agent_subject_display.sql +5 -0
  53. package/sql/README.en.md +15 -0
  54. package/sql/README.md +25 -0
  55. package/src/app/agent-conversation-audit.ts +20 -0
  56. package/src/app/agent-system-info.ts +41 -0
  57. package/src/app/agent-tool-invocations.ts +16 -4
  58. package/src/core/config/agent-setup.ts +37 -0
  59. package/src/core/config/client-agent-setup.ts +25 -0
  60. package/src/core/config/config-schema.test.ts +11 -0
  61. package/src/core/config/route-config.test.ts +28 -0
  62. package/src/core/config/route-config.ts +43 -4
  63. package/src/core/contracts/agent-subject-display.test.ts +19 -0
  64. package/src/core/contracts/agent-subject-display.ts +36 -0
  65. package/src/core/contracts/types.ts +15 -0
  66. package/src/core/runtime/agent-conversation-audit.test.ts +19 -1
  67. package/src/core/runtime/agent-conversation-audit.ts +39 -0
  68. package/src/infrastructure/config/config-agent-auth-business-sessions.test.ts +120 -0
  69. package/src/infrastructure/config/config-agent-auth-lifecycle-race.test.ts +152 -0
  70. package/src/infrastructure/config/config-agent-auth-repository.test.ts +2 -0
  71. package/src/infrastructure/config/config-agent-auth-repository.ts +208 -18
  72. package/src/infrastructure/config/config-agent-conversation-audit-cross-binding.test.ts +120 -0
  73. package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +117 -23
  74. package/src/infrastructure/config/config-agent-subject-display.test.ts +103 -0
  75. package/src/infrastructure/config/config-client-repository.ts +21 -0
  76. package/src/infrastructure/config/config-route-agent-setup.test.ts +59 -0
  77. package/src/infrastructure/config/config-route-repository.ts +24 -0
  78. package/src/infrastructure/config/configstore.ts +7 -3
  79. package/src/infrastructure/schema/core-schema-migrator.test.ts +90 -0
  80. package/src/routes/admin-access.ts +37 -0
  81. package/src/routes/admin-agent-clients.ts +11 -0
  82. package/src/routes/admin-agent-setup.test.ts +130 -0
  83. package/src/routes/admin-agent-setup.ts +68 -0
  84. package/src/routes/admin-client-agent-setup.test.ts +93 -0
  85. package/src/routes/admin-dispatch-config.ts +2 -0
  86. package/src/routes/agent-api.ts +7 -0
  87. package/src/routes/agent-auth-lifecycle-http.test.ts +177 -0
  88. package/src/routes/agent-auth-lifecycle.test.ts +193 -0
  89. package/src/routes/agent-auth.test.ts +1 -1
  90. package/src/routes/agent-auth.ts +206 -16
  91. package/src/routes/agent-conversation-audit-cross-binding-http.test.ts +122 -0
  92. package/src/routes/agent-conversation-audit.ts +8 -2
  93. package/src/routes/agent-subject-display-http.test.ts +145 -0
  94. package/src/routes/agent-system-info.test.ts +132 -0
  95. package/src/test-support/agent-auth-business-query-fixture.ts +43 -0
  96. package/src/test-support/agent-auth-lifecycle-fixture.ts +288 -0
  97. package/src/test-support/agent-conversation-audit-fixture.ts +30 -6
  98. package/src/test-support/agent-conversation-audit-http-fixture.ts +84 -0
  99. package/web/connect/bailing-connect-php.tgz +0 -0
  100. package/web/connect/bailing-connect-php7.tgz +0 -0
  101. package/web/console/assets/{Accounts-Ca_VnSu9.js → Accounts-ChL9k-XA.js} +1 -1
  102. package/web/console/assets/AgentClients-Bs7UgVDj.js +1 -0
  103. package/web/console/assets/AgentClients-DkgPTEbq.css +1 -0
  104. package/web/console/assets/{Approvals-CMvPWacY.js → Approvals-Bs6FGbp2.js} +1 -1
  105. package/web/console/assets/{Audit-CIRqOCnL.js → Audit-4WWYhkFM.js} +1 -1
  106. package/web/console/assets/{BrandLockup-BrytmTTH.js → BrandLockup-D2GhCipL.js} +1 -1
  107. package/web/console/assets/{Channels-CApxH2TB.js → Channels-CmoGpiCJ.js} +1 -1
  108. package/web/console/assets/{ChatEntries-CJon3bWJ.js → ChatEntries-BFRMtwta.js} +1 -1
  109. package/web/console/assets/Clients-CSHIsaWU.css +1 -0
  110. package/web/console/assets/Clients-DGkkSXyA.js +3 -0
  111. package/web/console/assets/{Cost-BbhlQFP8.js → Cost-BmGt0MfS.js} +1 -1
  112. package/web/console/assets/{Credentials-kqr1W0K7.js → Credentials-CR-sYINT.js} +1 -1
  113. package/web/console/assets/{Diagnostics-Kljt9XTH.js → Diagnostics-DAPbKSJp.js} +1 -1
  114. package/web/console/assets/{Executors-DnsB-Xz4.js → Executors-CgpiT3o8.js} +1 -1
  115. package/web/console/assets/{Kb-DLZSAFWP.js → Kb-Cm9dVSQw.js} +1 -1
  116. package/web/console/assets/{Login-DiTjPWmN.js → Login-CyUcsTZ_.js} +1 -1
  117. package/web/console/assets/{Projects-CXcVCgCD.js → Projects-DldFPgWg.js} +1 -1
  118. package/web/console/assets/Routes-DkMIjMQA.css +1 -0
  119. package/web/console/assets/Routes-DubfjlBD.js +124 -0
  120. package/web/console/assets/Runs-1hxgkuR4.js +3 -0
  121. package/web/console/assets/Runs-CvGTV8I-.css +1 -0
  122. package/web/console/assets/{Setup-FqoCKmfZ.js → Setup-DBLOnI2_.js} +1 -1
  123. package/web/console/assets/{Shell-BEqpONiy.js → Shell-gJ5Vz_E7.js} +1 -1
  124. package/web/console/assets/{StorageBuckets-CkORbYXY.js → StorageBuckets-DkDW16tj.js} +1 -1
  125. package/web/console/assets/{SystemSettings-gTQAazu7.js → SystemSettings-cDkudo2y.js} +1 -1
  126. package/web/console/assets/{SystemStatus-DAmUUNqO.js → SystemStatus-DZd6s8OX.js} +1 -1
  127. package/web/console/assets/{Targets-CZmDcjsE.js → Targets-DYNGq1NU.js} +1 -1
  128. package/web/console/assets/{Tools-CIHInlHL.js → Tools-DpWM59vV.js} +1 -1
  129. package/web/console/assets/{index-BkLbd7Cc.js → index-DGqs28gI.js} +2 -2
  130. package/web/console/assets/{request-r7GHVJzw.js → request-B7MLvOqo.js} +1 -1
  131. package/web/console/assets/{schema-BVn_hB7M.js → schema-CMuwjYdJ.js} +1 -1
  132. package/web/console/index.html +1 -1
  133. package/web-admin/scripts/subject-display-ui.mjs +78 -0
  134. package/web-admin/src/components/AgentSetupPanel.vue +262 -0
  135. package/web-admin/src/components/ClientConversations.vue +21 -4
  136. package/web-admin/src/components/conversation-audit.ts +20 -0
  137. package/web-admin/src/pages/AgentClients.vue +97 -23
  138. package/web-admin/src/pages/Clients.vue +4 -1
  139. package/web-admin/src/pages/Routes.vue +10 -1
  140. package/web-admin/tests/conversation-audit.fixture.mjs +13 -10
  141. package/web-admin/tests/conversation-audit.test.mjs +63 -1
  142. package/web/console/assets/AgentClients-BPIvlLYY.js +0 -1
  143. package/web/console/assets/AgentClients-DsWADpzr.css +0 -1
  144. package/web/console/assets/Clients-BSA1rlTB.js +0 -3
  145. package/web/console/assets/Clients-CNIVs7Qn.css +0 -1
  146. package/web/console/assets/Routes-CXGl9SMM.css +0 -1
  147. package/web/console/assets/Routes-DN9_d9Po.js +0 -124
  148. package/web/console/assets/Runs-Cwbe6thL.js +0 -3
  149. package/web/console/assets/Runs-D8UmjP5G.css +0 -1
@@ -0,0 +1,193 @@
1
+ import assert from 'node:assert/strict';
2
+ import { Readable } from 'node:stream';
3
+ import type { IncomingMessage, ServerResponse } from 'node:http';
4
+ import test from 'node:test';
5
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
6
+ import { handleAgentAuthHttpFor } from './agent-auth';
7
+
8
+ const authorizationId = '11111111-1111-4111-8111-111111111111';
9
+ const sessionId = '22222222-2222-4222-8222-222222222222';
10
+ const createdAt = '2026-09-09T01:00:00.000Z';
11
+ const expiry = '2026-10-09T01:00:00.000Z';
12
+
13
+ class Response {
14
+ statusCode = 0;
15
+ headers: Record<string, unknown> = {};
16
+ body = '';
17
+ setHeader(key: string, value: unknown): void { this.headers[key.toLowerCase()] = value; }
18
+ writeHead(code: number, headers: Record<string, unknown> = {}): void { this.statusCode = code; Object.assign(this.headers, headers); }
19
+ end(value: string): void { this.body = value; }
20
+ json(): any { return JSON.parse(this.body); }
21
+ }
22
+
23
+ function fixture() {
24
+ const client = { app_id: 'example-business', name: 'Business', enabled: true, token: 'fixture-business-token' };
25
+ const other = { app_id: 'other-business', name: 'Other', enabled: true, token: 'fixture-other-token' };
26
+ const session: any = {
27
+ session_id: sessionId, authorization_id: authorizationId, client_app_id: client.app_id,
28
+ device_label: 'Example device', principal: { id: 'operator', tenant: 'tenant-A', roles: ['admin'], private_key: 'nested-secret' },
29
+ on_behalf_of: 'tenant-A:operator', allowed_routes: ['orders'], state: 'active',
30
+ created_at: createdAt, access_expires_at: createdAt, refresh_expires_at: expiry,
31
+ access_token: 'access-secret', refresh_token: 'refresh-secret', access_token_hash: 'hash-secret', refresh_token_hash: 'hash-secret-2',
32
+ };
33
+ const authorization: any = {
34
+ authorization_id: authorizationId, client_app_id: client.app_id, status: 'consumed', session_id: sessionId,
35
+ device_label: 'Example device', requested_routes: ['orders'], expires_at: createdAt,
36
+ redirect_uri: 'http://127.0.0.1:12345/callback', code_hash: 'code-secret', state: 'state-secret', code_challenge: 'challenge-secret',
37
+ };
38
+ const calls: any[] = [];
39
+ const repository: any = {
40
+ async getAuthorization(id: string) { return id === authorizationId ? authorization : null; },
41
+ async getBusinessSession(app: string, id: string) { calls.push(['get', app, id]); return app === client.app_id && id === sessionId ? session : null; },
42
+ async listBusinessSessions(input: any) { calls.push(['list', input]); return { list: input.clientAppId === client.app_id ? [session] : [], nextCursor: undefined }; },
43
+ async revokeAuthorization(input: any) {
44
+ calls.push(['revoke', input]);
45
+ return input.clientAppId === client.app_id && input.authorizationId === authorizationId
46
+ ? { ok: true, authorization, sessionId } : { ok: false, reason: 'wrong_client' };
47
+ },
48
+ };
49
+ const store: any = {
50
+ agentAuth: repository,
51
+ clients: { async getByToken(token: string) { return token === client.token ? client : token === other.token ? other : null; } },
52
+ };
53
+ async function call(path: string, method = 'GET', body?: unknown, token: string | null = client.token) {
54
+ const req = Readable.from(body === undefined ? [] : [Buffer.from(JSON.stringify(body))]) as unknown as IncomingMessage;
55
+ req.method = method;
56
+ req.headers = token ? { authorization: `Bearer ${token}` } : {};
57
+ const res = new Response();
58
+ assert.equal(await handleAgentAuthHttpFor({ configStore: store as ConfigStoreContract }, req, res as unknown as ServerResponse, new URL(path, 'https://hub.example.com')), true);
59
+ assert.equal(res.headers['cache-control'], 'no-store');
60
+ return res;
61
+ }
62
+ return { client, other, session, authorization, calls, repository, store, call };
63
+ }
64
+
65
+ test('business session list uses Client bearer only and projects nested metadata without credentials', async () => {
66
+ const f = fixture();
67
+ for (const token of [null, 'bha_' + 'x'.repeat(43), 'admin-token', 'unknown']) {
68
+ assert.equal((await f.call('/agent-auth/v1/sessions', 'GET', undefined, token)).statusCode, 401);
69
+ }
70
+ assert.equal((await f.call('/agent-auth/v1/sessions?token=fixture-business-token', 'GET', undefined, null)).statusCode, 401);
71
+ assert.equal(f.calls.length, 0);
72
+ const result = await f.call('/agent-auth/v1/sessions');
73
+ assert.equal(result.statusCode, 200);
74
+ assert.equal(result.json().next_cursor, null);
75
+ assert.deepEqual(result.json().list[0], {
76
+ session_id: sessionId, authorization_id: authorizationId, client_app_id: f.client.app_id,
77
+ device_label: 'Example device', principal: { id: 'operator', tenant: 'tenant-A', roles: ['admin'] },
78
+ on_behalf_of: 'tenant-A:operator', allowed_routes: ['orders'], state: 'active', created_at: createdAt, expires_at: expiry,
79
+ subject_display: null, subject_display_status: 'missing',
80
+ });
81
+ assert.doesNotMatch(result.body, /secret|token_hash|refresh_token|access_token/);
82
+ assert.equal((await f.call('/agent-auth/v1/sessions', 'GET', undefined, f.other.token)).json().list.length, 0);
83
+ f.client.enabled = false;
84
+ assert.equal((await f.call('/agent-auth/v1/sessions')).statusCode, 401);
85
+ });
86
+
87
+ test('business list filters are exact AND inputs, including a tenant-only scope and explicit no-tenant principal', async () => {
88
+ const f = fixture();
89
+ const query = new URLSearchParams({ authorization_id: authorizationId, on_behalf_of: 'tenant-A:operator', principal_id: 'operator', tenant: 'tenant-A', state: 'revoked', limit: '7' });
90
+ assert.equal((await f.call(`/agent-auth/v1/sessions?${query}`)).statusCode, 200);
91
+ assert.deepEqual(f.calls[0][1], {
92
+ clientAppId: 'example-business', authorizationId, onBehalfOf: 'tenant-A:operator', principalId: 'operator', tenant: 'tenant-A', state: 'revoked', limit: 7, cursor: undefined,
93
+ });
94
+ assert.equal((await f.call('/agent-auth/v1/sessions?tenant=tenant-A')).statusCode, 200);
95
+ assert.equal(f.calls[1][1].tenant, 'tenant-A');
96
+ assert.equal((await f.call('/agent-auth/v1/sessions?principal_id=operator&tenant=')).statusCode, 200);
97
+ assert.equal(f.calls[2][1].tenant, '');
98
+ });
99
+
100
+ test('business session list rejects duplicate, unknown, overbroad and malformed filters before repository access', async () => {
101
+ const f = fixture();
102
+ const queries = [
103
+ 'client_app_id=other-business', 'token=secret', 'tenant=A&tenant=B', 'state=all', 'principal_id=operator',
104
+ 'authorization_id=bad', 'authorization_id=', 'on_behalf_of=', 'principal_id=&tenant=A', 'tenant=%20A',
105
+ 'tenant=%00A', 'limit=0', 'limit=101', 'limit=1.5', 'limit=01', 'limit=', 'cursor=', 'cursor=%%%25',
106
+ `tenant=${'x'.repeat(129)}`, `on_behalf_of=${'x'.repeat(192)}`, `cursor=${'a'.repeat(2049)}`,
107
+ ];
108
+ for (const query of queries) assert.equal((await f.call(`/agent-auth/v1/sessions?${query}`)).statusCode, 400, query);
109
+ assert.equal(f.calls.length, 0);
110
+ });
111
+
112
+ test('pagination cursor binds the authenticated client and every filter while allowing a different page size', async () => {
113
+ const f = fixture();
114
+ f.repository.listBusinessSessions = async (input: any) => {
115
+ f.calls.push(['list', input]);
116
+ return { list: [f.session], nextCursor: { createdAt, sessionId } };
117
+ };
118
+ const query = new URLSearchParams({ authorization_id: authorizationId, on_behalf_of: 'tenant-A:operator', principal_id: 'operator', tenant: 'tenant-A', state: 'active', limit: '1' });
119
+ const first = await f.call(`/agent-auth/v1/sessions?${query}`);
120
+ assert.equal(first.statusCode, 200);
121
+ const cursor = first.json().next_cursor;
122
+ query.set('cursor', cursor); query.set('limit', '2');
123
+ assert.equal((await f.call(`/agent-auth/v1/sessions?${query}`)).statusCode, 200);
124
+ assert.deepEqual(f.calls[1][1].cursor, { createdAt, sessionId });
125
+ assert.equal((await f.call(`/agent-auth/v1/sessions?${query}`, 'GET', undefined, f.other.token)).statusCode, 400);
126
+ for (const key of ['authorization_id', 'on_behalf_of', 'principal_id', 'tenant', 'state']) {
127
+ const changed = new URLSearchParams(query); changed.delete(key);
128
+ assert.equal((await f.call(`/agent-auth/v1/sessions?${changed}`)).statusCode, 400, key);
129
+ }
130
+ const malformed = JSON.parse(Buffer.from(cursor, 'base64url').toString());
131
+ for (const extra of [{ created_at: '2026-02-30T01:00:00.000Z' }, { session_id: 'other' }, { v: 2 }, { injected: true }]) {
132
+ const changed = new URLSearchParams(query);
133
+ changed.set('cursor', Buffer.from(JSON.stringify({ ...malformed, ...extra })).toString('base64url'));
134
+ assert.equal((await f.call(`/agent-auth/v1/sessions?${changed}`)).statusCode, 400);
135
+ }
136
+ assert.equal(f.calls.length, 2);
137
+ });
138
+
139
+ test('consumed authorization exposes only linked own-session metadata; authorization expiry is separate', async () => {
140
+ const f = fixture();
141
+ const path = `/agent-auth/v1/authorizations/${authorizationId}`;
142
+ const result = await f.call(path);
143
+ assert.equal(result.statusCode, 200);
144
+ assert.equal(result.json().status, 'consumed');
145
+ assert.equal(result.json().expires_at, createdAt);
146
+ assert.deepEqual(result.json().session, { session_id: sessionId, state: 'active', expires_at: expiry, subject_display: null, subject_display_status: 'missing' });
147
+ assert.doesNotMatch(result.body, /secret|code_hash|challenge|redirect_uri|principal/);
148
+ f.session.state = 'revoked'; f.session.revoked_at = createdAt;
149
+ assert.equal((await f.call(path)).json().session.state, 'revoked');
150
+ assert.equal((await f.call(path, 'GET', undefined, f.other.token)).statusCode, 404);
151
+ f.repository.getBusinessSession = async () => null;
152
+ assert.equal((await f.call(path)).json().session, null);
153
+ f.authorization.status = 'pending';
154
+ assert.equal('session' in (await f.call(path)).json(), false);
155
+ });
156
+
157
+ test('authorization revocation passes authenticated identity, rejects unknown body and does not expose repository details', async () => {
158
+ const f = fixture(); const path = `/agent-auth/v1/authorizations/${authorizationId}/revoke`;
159
+ for (const body of [[], null, { client_app_id: 'other' }, { session_id: sessionId }]) {
160
+ assert.equal((await f.call(path, 'POST', body)).statusCode, 400);
161
+ }
162
+ assert.equal(f.calls.length, 0);
163
+ assert.equal((await f.call(path, 'POST', {})).statusCode, 200);
164
+ assert.deepEqual(f.calls[0][1], { authorizationId, clientAppId: 'example-business' });
165
+ assert.deepEqual((await f.call(path, 'POST', {})).json(), { authorization_id: authorizationId, revoked: true, session_id: sessionId });
166
+ assert.equal((await f.call(path, 'POST', {}, f.other.token)).statusCode, 404);
167
+ assert.equal((await f.call(path, 'POST', {}, null)).statusCode, 401);
168
+ assert.equal((await f.call(path)).statusCode, 405);
169
+ f.repository.revokeAuthorization = async () => { throw new Error('db-host credential-secret deadlock'); };
170
+ const failed = await f.call(path, 'POST', {});
171
+ assert.equal(failed.statusCode, 503);
172
+ assert.deepEqual(failed.json(), { error: 'agent_auth_lifecycle_unavailable' });
173
+ });
174
+
175
+ test('old hosts explicitly reject new operations while old context remains readable; repository failures never look empty or successful', async () => {
176
+ const f = fixture(); const context = `/agent-auth/v1/authorizations/${authorizationId}`;
177
+ delete f.repository.listBusinessSessions; delete f.repository.revokeAuthorization; delete f.repository.getBusinessSession;
178
+ assert.equal((await f.call('/agent-auth/v1/sessions')).statusCode, 503);
179
+ assert.equal((await f.call(`${context}/revoke`, 'POST', {})).statusCode, 503);
180
+ assert.equal((await f.call(context)).json().session, null);
181
+ f.repository.listBusinessSessions = async () => { throw new Error('query-secret'); };
182
+ const result = await f.call('/agent-auth/v1/sessions');
183
+ assert.equal(result.statusCode, 503); assert.doesNotMatch(result.body, /query-secret|list/);
184
+ f.repository.getAuthorization = async () => { throw new Error('context-secret'); };
185
+ assert.equal((await f.call(context)).statusCode, 503);
186
+ assert.equal((await f.call('/agent-auth/v1/sessions', 'POST', {})).statusCode, 405);
187
+ });
188
+
189
+ test('business HTTP projection fails closed if a custom repository returns another client session', async () => {
190
+ const f = fixture(); f.session.client_app_id = f.other.app_id;
191
+ assert.equal((await f.call('/agent-auth/v1/sessions')).statusCode, 503);
192
+ assert.equal((await f.call(`/agent-auth/v1/authorizations/${authorizationId}`)).statusCode, 503);
193
+ });
@@ -249,7 +249,7 @@ test('Agent Auth v1: context is redacted, PKCE binds client/redirect, query toke
249
249
  assert.equal(token.statusCode, 200);
250
250
  assert.equal(token.headers['cache-control'], 'no-store');
251
251
  assert.equal(token.headers['pragma'], 'no-cache');
252
- assert.deepEqual(Object.keys(token.json()).sort(), ['access_token', 'client_app_id', 'expires_in', 'refresh_expires_in', 'refresh_token', 'session_id', 'token_type'].sort());
252
+ assert.deepEqual(Object.keys(token.json()).sort(), ['access_token', 'client_app_id', 'expires_in', 'refresh_expires_in', 'refresh_token', 'session_id', 'token_type', 'subject_display', 'subject_display_status'].sort());
253
253
  const accessToken = String(token.json().access_token);
254
254
 
255
255
  const queryAccess = await call(store, 'GET', `/agent-auth/v1/session?token=${encodeURIComponent(accessToken)}`);
@@ -3,6 +3,7 @@ import type { IncomingMessage, ServerResponse } from 'node:http';
3
3
  import { namedRateLimitedFor } from '../app/auth';
4
4
  import { ipOf, readBody, send } from '../app/http';
5
5
  import type { AgentBusinessPrincipal, AgentSession, Client } from '../core/contracts/types';
6
+ import { agentSubjectDisplayView, validateAgentSubjectDisplay } from '../core/contracts/agent-subject-display';
6
7
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
7
8
 
8
9
  export const AGENT_AUTHORIZATION_TTL_SEC = 10 * 60;
@@ -16,6 +17,19 @@ const PKCE_VERIFIER_RE = /^[A-Za-z0-9._~-]{43,128}$/;
16
17
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
17
18
 
18
19
  type RecordValue = Record<string, unknown>;
20
+ type BusinessSession = AgentSession & {
21
+ state: 'active' | 'expired' | 'revoked';
22
+ authorization_id?: string;
23
+ last_seen_at?: string;
24
+ };
25
+ type SessionListFilters = {
26
+ authorizationId?: string;
27
+ onBehalfOf?: string;
28
+ principalId?: string;
29
+ tenant?: string;
30
+ state?: BusinessSession['state'];
31
+ };
32
+ type SessionCursor = { createdAt: string; sessionId: string };
19
33
 
20
34
  export interface AgentAuthHttpDeps {
21
35
  configStore: ConfigStoreContract | null;
@@ -144,6 +158,7 @@ function publicSession(session: AgentSession): RecordValue {
144
158
  session_id: session.session_id,
145
159
  client_app_id: session.client_app_id,
146
160
  device_label: session.device_label,
161
+ ...agentSubjectDisplayView(session.subject_display),
147
162
  principal: session.principal,
148
163
  on_behalf_of: session.on_behalf_of,
149
164
  allowed_routes: session.allowed_routes,
@@ -153,6 +168,107 @@ function publicSession(session: AgentSession): RecordValue {
153
168
  };
154
169
  }
155
170
 
171
+ /** Business metadata never includes credential material, including unknown nested fields. */
172
+ function businessSessionMetadata(session: BusinessSession): RecordValue {
173
+ const source = session.principal;
174
+ const principal = parsePrincipal({
175
+ id: source.id, tenant: source.tenant, roles: source.roles, audience: source.audience, channel: source.channel,
176
+ });
177
+ const allowedRoutes = stringList(session.allowed_routes);
178
+ if (!principal || !allowedRoutes || !UUID_RE.test(session.session_id) || !['active', 'expired', 'revoked'].includes(session.state)) {
179
+ throw new Error('Invalid business session metadata');
180
+ }
181
+ return {
182
+ session_id: session.session_id,
183
+ ...(session.authorization_id ? { authorization_id: session.authorization_id } : {}),
184
+ client_app_id: session.client_app_id,
185
+ device_label: session.device_label,
186
+ ...agentSubjectDisplayView(session.subject_display),
187
+ principal,
188
+ on_behalf_of: session.on_behalf_of,
189
+ allowed_routes: allowedRoutes,
190
+ state: session.state,
191
+ created_at: session.created_at,
192
+ expires_at: session.refresh_expires_at,
193
+ ...(session.last_seen_at ? { last_seen_at: session.last_seen_at } : {}),
194
+ ...(session.revoked_at ? { revoked_at: session.revoked_at } : {}),
195
+ };
196
+ }
197
+
198
+ function sessionCursorBinding(clientAppId: string, filters: SessionListFilters): string {
199
+ // This digest binds pagination to public filters; it is not a credential or authorization grant.
200
+ return createHash('sha256').update(JSON.stringify([
201
+ clientAppId, filters.authorizationId ?? null, filters.onBehalfOf ?? null,
202
+ filters.principalId ?? null, filters.tenant ?? null, filters.state ?? null,
203
+ ])).digest('hex');
204
+ }
205
+
206
+ function parseSessionList(url: URL, clientAppId: string): { filters: SessionListFilters; limit: number; cursor?: SessionCursor; binding: string } | null {
207
+ const params = url.searchParams;
208
+ const fields = ['authorization_id', 'on_behalf_of', 'principal_id', 'tenant', 'state', 'limit', 'cursor'];
209
+ for (const key of params.keys()) if (!fields.includes(key) || params.getAll(key).length !== 1) return null;
210
+ const filters: SessionListFilters = {};
211
+ if (params.has('authorization_id')) {
212
+ const value = params.get('authorization_id')!;
213
+ if (!UUID_RE.test(value)) return null;
214
+ filters.authorizationId = value.toLowerCase();
215
+ }
216
+ for (const [key, property, max] of [
217
+ ['on_behalf_of', 'onBehalfOf', 191], ['principal_id', 'principalId', 128], ['tenant', 'tenant', 128],
218
+ ] as const) {
219
+ if (!params.has(key)) continue;
220
+ const value = params.get(key)!;
221
+ if ((key !== 'tenant' && !value) || value.length > max || value !== value.trim() || /[\u0000-\u001f\u007f]/.test(value)) return null;
222
+ filters[property] = value;
223
+ }
224
+ if (filters.principalId !== undefined && filters.tenant === undefined) return null;
225
+ if (params.has('state')) {
226
+ const state = params.get('state')!;
227
+ if (state !== 'active' && state !== 'expired' && state !== 'revoked') return null;
228
+ filters.state = state;
229
+ }
230
+ const rawLimit = params.get('limit') ?? '20';
231
+ if (!/^[1-9][0-9]{0,2}$/.test(rawLimit) || Number(rawLimit) > 100) return null;
232
+ const binding = sessionCursorBinding(clientAppId, filters);
233
+ let cursor: SessionCursor | undefined;
234
+ if (params.has('cursor')) {
235
+ const raw = params.get('cursor')!;
236
+ if (!raw || raw.length > 2048 || !/^[A-Za-z0-9_-]+$/.test(raw)) return null;
237
+ try {
238
+ const bytes = Buffer.from(raw, 'base64url');
239
+ if (bytes.toString('base64url') !== raw) return null;
240
+ const value = record(JSON.parse(bytes.toString('utf8')));
241
+ if (!value || !allowedFields(value, ['v', 'binding', 'created_at', 'session_id']) || value['v'] !== 1 || value['binding'] !== binding ||
242
+ typeof value['created_at'] !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value['created_at']) ||
243
+ new Date(value['created_at']).toISOString() !== value['created_at'] || typeof value['session_id'] !== 'string' || !UUID_RE.test(value['session_id'])) return null;
244
+ cursor = { createdAt: value['created_at'], sessionId: value['session_id'].toLowerCase() };
245
+ } catch { return null; }
246
+ }
247
+ return { filters, limit: Number(rawLimit), ...(cursor ? { cursor } : {}), binding };
248
+ }
249
+
250
+ async function businessListSessions(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL): Promise<void> {
251
+ try {
252
+ const repository = deps.configStore?.agentAuth;
253
+ if (!repository) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
254
+ const client = await businessClient(deps, req, url);
255
+ if (!client) { send(res, 401, { error: 'unauthorized' }); return; }
256
+ const input = parseSessionList(url, client.app_id);
257
+ if (!input) { send(res, 400, { error: 'invalid_request' }); return; }
258
+ if (typeof repository.listBusinessSessions !== 'function') { send(res, 503, { error: 'agent_auth_lifecycle_unavailable' }); return; }
259
+ const result = await repository.listBusinessSessions({ clientAppId: client.app_id, ...input.filters, limit: input.limit, cursor: input.cursor });
260
+ if (result.list.length > input.limit || result.list.some((session) => session.client_app_id !== client.app_id)) {
261
+ throw new Error('Invalid business session scope');
262
+ }
263
+ send(res, 200, {
264
+ list: result.list.map(businessSessionMetadata),
265
+ next_cursor: result.nextCursor ? Buffer.from(JSON.stringify({
266
+ v: 1, binding: input.binding, created_at: result.nextCursor.createdAt, session_id: result.nextCursor.sessionId,
267
+ })).toString('base64url') : null,
268
+ });
269
+ } catch { send(res, 503, { error: 'agent_auth_lifecycle_unavailable' }); }
270
+ }
271
+
156
272
  async function createAuthorization(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
157
273
  if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
158
274
  const body = record(await readBody(req).catch(() => null));
@@ -194,20 +310,50 @@ async function createAuthorization(deps: AgentAuthHttpDeps, req: IncomingMessage
194
310
  }
195
311
 
196
312
  async function authorizationContext(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL, authorizationId: string): Promise<void> {
197
- if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
198
- const client = await businessClient(deps, req, url);
199
- if (!client) { send(res, 401, { error: 'unauthorized' }); return; }
200
- const item = await deps.configStore.agentAuth.getAuthorization(authorizationId);
201
- if (!item || item.client_app_id !== client.app_id) { send(res, 404, { error: 'not_found' }); return; }
202
- const status = item.status === 'pending' && Date.parse(item.expires_at) <= Date.now() ? 'expired' : item.status;
203
- send(res, 200, {
204
- authorization_id: item.authorization_id,
205
- client: { app_id: client.app_id, name: client.name },
206
- device: { name: item.device_label },
207
- requested_routes: item.requested_routes,
208
- status,
209
- expires_at: item.expires_at,
210
- });
313
+ try {
314
+ if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
315
+ const client = await businessClient(deps, req, url);
316
+ if (!client) { send(res, 401, { error: 'unauthorized' }); return; }
317
+ const item = await deps.configStore.agentAuth.getAuthorization(authorizationId);
318
+ if (!item || item.client_app_id !== client.app_id) { send(res, 404, { error: 'not_found' }); return; }
319
+ const status = item.status === 'pending' && Date.parse(item.expires_at) <= Date.now() ? 'expired' : item.status;
320
+ let session: RecordValue | null = null;
321
+ if (item.status === 'consumed' && item.session_id && typeof deps.configStore.agentAuth.getBusinessSession === 'function') {
322
+ const linked = await deps.configStore.agentAuth.getBusinessSession(client.app_id, item.session_id);
323
+ if (linked) {
324
+ if (linked.client_app_id !== client.app_id || linked.session_id !== item.session_id) throw new Error('Invalid business session scope');
325
+ const metadata = businessSessionMetadata(linked);
326
+ session = { session_id: linked.session_id, state: metadata['state'], expires_at: metadata['expires_at'],
327
+ ...agentSubjectDisplayView(linked.subject_display),
328
+ ...(linked.revoked_at ? { revoked_at: linked.revoked_at } : {}) };
329
+ }
330
+ }
331
+ send(res, 200, {
332
+ authorization_id: item.authorization_id,
333
+ client: { app_id: client.app_id, name: client.name },
334
+ device: { name: item.device_label },
335
+ requested_routes: item.requested_routes,
336
+ status,
337
+ expires_at: item.expires_at,
338
+ ...(item.status === 'consumed' ? { session } : {}),
339
+ });
340
+ } catch { send(res, 503, { error: 'agent_auth_lifecycle_unavailable' }); }
341
+ }
342
+
343
+ async function businessRevokeAuthorization(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL, authorizationId: string): Promise<void> {
344
+ try {
345
+ const repository = deps.configStore?.agentAuth;
346
+ if (!repository) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
347
+ const client = await businessClient(deps, req, url);
348
+ if (!client) { send(res, 401, { error: 'unauthorized' }); return; }
349
+ const body = record(await readBody(req, 4096).catch(() => null));
350
+ if (!body || !allowedFields(body, [])) { send(res, 400, { error: 'invalid_request' }); return; }
351
+ if (typeof repository.revokeAuthorization !== 'function') { send(res, 503, { error: 'agent_auth_lifecycle_unavailable' }); return; }
352
+ const result = await repository.revokeAuthorization({ authorizationId, clientAppId: client.app_id });
353
+ if (!result.ok) { send(res, 404, { error: 'not_found' }); return; }
354
+ if (result.authorization.authorization_id !== authorizationId || result.authorization.client_app_id !== client.app_id) throw new Error('Invalid authorization scope');
355
+ send(res, 200, { authorization_id: authorizationId, revoked: true, ...(result.sessionId ? { session_id: result.sessionId } : {}) });
356
+ } catch { send(res, 503, { error: 'agent_auth_lifecycle_unavailable' }); }
211
357
  }
212
358
 
213
359
  async function approveAuthorization(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL, authorizationId: string): Promise<void> {
@@ -215,7 +361,12 @@ async function approveAuthorization(deps: AgentAuthHttpDeps, req: IncomingMessag
215
361
  const client = await businessClient(deps, req, url);
216
362
  if (!client) { send(res, 401, { error: 'unauthorized' }); return; }
217
363
  const body = record(await readBody(req).catch(() => null));
218
- if (!body || !allowedFields(body, ['principal', 'on_behalf_of', 'allowed_routes'])) { send(res, 400, { error: 'invalid_request' }); return; }
364
+ if (!body || !allowedFields(body, ['principal', 'on_behalf_of', 'allowed_routes', 'subject_display'])) { send(res, 400, { error: 'invalid_request' }); return; }
365
+ const display = validateAgentSubjectDisplay(body['subject_display']);
366
+ if (!display.ok) { send(res, 400, { error: 'invalid_request' }); return; }
367
+ if (display.value && typeof deps.configStore.agentAuth.updateSubjectDisplay !== 'function') {
368
+ send(res, 503, { error: 'subject_display_unavailable' }); return;
369
+ }
219
370
  const principal = parsePrincipal(body['principal']);
220
371
  const onBehalfOf = typeof body['on_behalf_of'] === 'string' ? body['on_behalf_of'].trim() : '';
221
372
  const allowedRoutes = stringList(body['allowed_routes']);
@@ -230,6 +381,7 @@ async function approveAuthorization(deps: AgentAuthHttpDeps, req: IncomingMessag
230
381
  authorizationId,
231
382
  clientAppId: client.app_id,
232
383
  principal: { ...principal },
384
+ subjectDisplay: display.value,
233
385
  onBehalfOf,
234
386
  allowedRoutes,
235
387
  codeHash: tokenHash(code),
@@ -265,6 +417,7 @@ function tokenResponse(session: AgentSession, accessToken: string, refreshToken:
265
417
  refresh_expires_in: Math.max(0, Math.floor((Date.parse(session.refresh_expires_at) - Date.now()) / 1000)),
266
418
  session_id: session.session_id,
267
419
  client_app_id: session.client_app_id,
420
+ ...agentSubjectDisplayView(session.subject_display),
268
421
  };
269
422
  }
270
423
 
@@ -368,6 +521,29 @@ async function businessRevokeSession(deps: AgentAuthHttpDeps, req: IncomingMessa
368
521
  send(res, 200, { revoked: true });
369
522
  }
370
523
 
524
+ async function businessUpdateSubjectDisplay(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL, sessionId: string): Promise<void> {
525
+ const repository = deps.configStore?.agentAuth;
526
+ if (!repository) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
527
+ const client = await businessClient(deps, req, url);
528
+ if (!client) { send(res, 401, { error: 'unauthorized' }); return; }
529
+ const body = record(await readBody(req, 4096).catch(() => null));
530
+ if (!body || Object.keys(body).length !== 1 || !Object.hasOwn(body, 'subject_display')) {
531
+ send(res, 400, { error: 'invalid_request' }); return;
532
+ }
533
+ const display = validateAgentSubjectDisplay(body['subject_display']);
534
+ if (!display.ok) { send(res, 400, { error: 'invalid_request' }); return; }
535
+ if (typeof repository.updateSubjectDisplay !== 'function') { send(res, 503, { error: 'subject_display_unavailable' }); return; }
536
+ try {
537
+ const result = await repository.updateSubjectDisplay({ clientAppId: client.app_id, sessionId, subjectDisplay: display.value });
538
+ if (!result.ok) {
539
+ send(res, result.reason === 'not_found' ? 404 : 409, { error: result.reason === 'not_found' ? 'not_found' : 'session_inactive' });
540
+ return;
541
+ }
542
+ if (result.session.client_app_id !== client.app_id || result.session.session_id !== sessionId) throw new Error('Invalid subject display binding.');
543
+ send(res, 200, businessSessionMetadata(result.session));
544
+ } catch { send(res, 503, { error: 'subject_display_unavailable' }); }
545
+ }
546
+
371
547
  /** Returns true when the request belongs to the dedicated Agent Auth surface. */
372
548
  export async function handleAgentAuthHttpFor(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> {
373
549
  const method = req.method ?? 'GET';
@@ -376,7 +552,7 @@ export async function handleAgentAuthHttpFor(deps: AgentAuthHttpDeps, req: Incom
376
552
  res.setHeader('cache-control', 'no-store');
377
553
  if (path === '/agent-auth/v1/token') res.setHeader('pragma', 'no-cache');
378
554
  if (method === 'POST' && path === '/agent-auth/v1/authorizations') { await createAuthorization(deps, req, res); return true; }
379
- const authorizationMatch = path.match(/^\/agent-auth\/v1\/authorizations\/([0-9a-f-]{36})(?:\/(approve|deny))?$/i);
555
+ const authorizationMatch = path.match(/^\/agent-auth\/v1\/authorizations\/([0-9a-f-]{36})(?:\/(approve|deny|revoke))?$/i);
380
556
  if (authorizationMatch) {
381
557
  const id = authorizationMatch[1]!;
382
558
  const action = authorizationMatch[2];
@@ -384,10 +560,24 @@ export async function handleAgentAuthHttpFor(deps: AgentAuthHttpDeps, req: Incom
384
560
  if (method === 'GET' && !action) { await authorizationContext(deps, req, res, url, id); return true; }
385
561
  if (method === 'POST' && action === 'approve') { await approveAuthorization(deps, req, res, url, id); return true; }
386
562
  if (method === 'POST' && action === 'deny') { await denyAuthorization(deps, req, res, url, id); return true; }
563
+ if (method === 'POST' && action === 'revoke') { await businessRevokeAuthorization(deps, req, res, url, id.toLowerCase()); return true; }
387
564
  send(res, 405, { error: 'method_not_allowed' }); return true;
388
565
  }
389
566
  if (method === 'POST' && path === '/agent-auth/v1/token') { await exchangeToken(deps, req, res); return true; }
390
567
  if (method === 'GET' && path === '/agent-auth/v1/session') { await readSession(deps, req, res, url); return true; }
568
+ if (path === '/agent-auth/v1/sessions') {
569
+ if (method === 'GET') await businessListSessions(deps, req, res, url);
570
+ else send(res, 405, { error: 'method_not_allowed' });
571
+ return true;
572
+ }
573
+ const displayMatch = path.match(/^\/agent-auth\/v1\/sessions\/([0-9a-f-]{36})\/subject-display$/i);
574
+ if (displayMatch) {
575
+ const sessionId = displayMatch[1]!.toLowerCase();
576
+ if (!UUID_RE.test(sessionId)) { send(res, 404, { error: 'not_found' }); return true; }
577
+ if (method === 'PUT') await businessUpdateSubjectDisplay(deps, req, res, url, sessionId);
578
+ else send(res, 405, { error: 'method_not_allowed' });
579
+ return true;
580
+ }
391
581
  if (method === 'POST' && path === '/agent-auth/v1/revoke') { await revokeSession(deps, req, res, url); return true; }
392
582
  const revokeMatch = method === 'POST' ? path.match(/^\/agent-auth\/v1\/sessions\/([0-9a-f-]{36})\/revoke$/i) : null;
393
583
  if (revokeMatch) { await businessRevokeSession(deps, req, res, url, revokeMatch[1]!); return true; }
@@ -0,0 +1,122 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { conversationAuditHttpFixture } from '../test-support/agent-conversation-audit-http-fixture';
4
+ import { AUDIT_SESSION_A, AUDIT_SESSION_B, AUDIT_SESSION_C, AUDIT_RUN_A, AUDIT_RUN_B } from '../test-support/agent-conversation-audit-fixture';
5
+
6
+ const BASE = '/agent-api/v1/conversation-audits';
7
+ const events = { events: [
8
+ { event_id: 'start', sequence: 1, client_turn_id: 'turn-1', kind: 'turn_start' },
9
+ { event_id: 'user', sequence: 2, client_turn_id: 'turn-1', kind: 'user_message', content: 'Compare the CRM and ERP accounts. Keep their execution identities separate.' },
10
+ { event_id: 'crm', sequence: 3, client_turn_id: 'turn-1', kind: 'run_link', run_id: AUDIT_RUN_A, member_session_id: AUDIT_SESSION_A },
11
+ { event_id: 'erp', sequence: 4, client_turn_id: 'turn-1', kind: 'run_link', run_id: AUDIT_RUN_B, member_session_id: AUDIT_SESSION_B },
12
+ { event_id: 'answer', sequence: 5, client_turn_id: 'turn-1', kind: 'assistant_message', content: '完整可见答复:CRM 与 ERP 的结果在原授权执行记录中核对。' },
13
+ { event_id: 'end', sequence: 6, client_turn_id: 'turn-1', kind: 'turn_end', status: 'completed' },
14
+ ] };
15
+
16
+ test('loopback HTTP preserves a non-first writer, cross-App/route proofs, body permissions and ACK idempotency', async (t) => {
17
+ const fx = await conversationAuditHttpFixture({ crossBinding: true });
18
+ t.after(() => fx.close());
19
+ const a = fx.tokens.get(AUDIT_SESSION_A)!;
20
+ const b = fx.tokens.get(AUDIT_SESSION_B)!;
21
+ const capabilities = await fx.api('GET', `${BASE}/capabilities`, undefined, b);
22
+ assert.deepEqual(capabilities.body, { schema: 'bailing.agent-conversation-audit-capabilities.v1', cross_binding_members: true, member_bindings: 'session-client-route.v1' });
23
+ assert.equal(capabilities.headers.get('cache-control'), 'no-store');
24
+ assert.equal((await fx.api('GET', `${BASE}/capabilities`, undefined, null)).status, 401);
25
+ const created = await fx.api('POST', BASE, fx.crossInput(), b);
26
+ assert.equal(created.status, 200);
27
+ const id = created.body.conversation_id;
28
+ assert.equal(created.body.client_app_id, 'example-erp', 'writer is the bearer member, not lexicographically first A');
29
+ assert.equal(created.body.route_key, 'inventory');
30
+ assert.equal(fx.archives.get(id)!.creator_session_id, AUDIT_SESSION_B);
31
+ assert.equal((await fx.api('POST', `${BASE}/${id}/events`, events, b)).body.error, 'conversation_audit_not_ready');
32
+ assert.equal((await fx.api('POST', `${BASE}/${id}/confirm`, { session_id: AUDIT_SESSION_A }, b)).status, 400);
33
+ assert.equal((await fx.api('POST', `${BASE}/${id}/confirm`, {}, fx.tokens.get(AUDIT_SESSION_C)!)).status, 404);
34
+ assert.equal((await fx.api('POST', `${BASE}/${id}/confirm`, {}, a)).body.state, 'ready');
35
+ assert.equal((await fx.api('POST', `${BASE}/${id}/events`, events, a)).status, 404, 'a member cannot impersonate the writer');
36
+ const ack = await fx.api('POST', `${BASE}/${id}/events`, events, b);
37
+ assert.equal(ack.status, 200);
38
+ assert.deepEqual((await fx.api('POST', `${BASE}/${id}/events`, events, b)).body, ack.body);
39
+ assert.equal(fx.events.size, 6);
40
+ for (const token of [a, fx.deniedAdminToken]) {
41
+ const denied = await fx.api('GET', `/admin/api/conversation-audits/${id}`, undefined, token);
42
+ assert.equal(denied.status, 403);
43
+ assert.doesNotMatch(denied.text, /完整可见答复|Compare the CRM/);
44
+ }
45
+ assert.equal((await fx.api('GET', `${BASE}/${id}`, undefined, b)).status, 404);
46
+ const first = await fx.api('GET', `/admin/api/conversation-audits/${id}?limit=3`, undefined, fx.adminToken);
47
+ const second = await fx.api('GET', `/admin/api/conversation-audits/${id}?limit=3&after_sequence=${first.body.next_after_sequence}`, undefined, fx.adminToken);
48
+ assert.equal(first.body.has_more, true);
49
+ assert.equal(second.body.has_more, false);
50
+ assert.equal(second.headers.get('cache-control'), 'no-store');
51
+ assert.deepEqual(first.body.members.map((member: any) => [member.session_id, member.client_app_id, member.route_key]), [
52
+ [AUDIT_SESSION_A, 'example-business', 'orders'], [AUDIT_SESSION_B, 'example-erp', 'inventory'],
53
+ ]);
54
+ const received = [...first.body.events, ...second.body.events];
55
+ assert.equal(received[1].content, events.events[1]!.content);
56
+ assert.equal(received[4].content, events.events[4]!.content);
57
+ assert.deepEqual(received.filter((event: any) => event.kind === 'run_link').map((event: any) => [event.run_id, event.thread_id]), [[AUDIT_RUN_A, 101], [AUDIT_RUN_B, 102]]);
58
+ assert.deepEqual(await fx.repo.findRunLinkForAdmin(AUDIT_RUN_A), { conversation_audit_id: id, client_turn_id: 'turn-1' });
59
+ assert.equal(first.body.conversation.message_count, 2);
60
+ assert.equal(first.body.conversation.turn_count, 1);
61
+ fx.sessions.get(AUDIT_SESSION_A)!.revoked_at = '2026-01-01T00:00:00Z';
62
+ assert.equal((await fx.api('POST', `${BASE}/${id}/events`, events, b)).status, 403, 'even an ACK retry must revalidate all members');
63
+ assert.equal(fx.events.size, 6);
64
+ assert.equal(fx.requests.some((request) => request.path.includes('/tools/')), false);
65
+ });
66
+
67
+ test('loopback HTTP rejects forged App/route and cross-member run links before storing any text', async (t) => {
68
+ const fx = await conversationAuditHttpFixture({ crossBinding: true });
69
+ t.after(() => fx.close());
70
+ for (const patch of [{ client_app_id: 'example-business' }, { route: 'orders' }]) {
71
+ const input = fx.crossInput({ members: fx.crossInput().members.map((member) => member.session_id === AUDIT_SESSION_B ? { ...member, ...patch } : member) });
72
+ assert.equal((await fx.api('POST', BASE, input)).status, 403);
73
+ assert.equal(fx.archives.size, 0);
74
+ }
75
+ const id = (await fx.api('POST', BASE, fx.crossInput())).body.conversation_id;
76
+ await fx.api('POST', `${BASE}/${id}/confirm`, {}, fx.tokens.get(AUDIT_SESSION_B)!);
77
+ const forged = structuredClone(events);
78
+ forged.events[3]!.member_session_id = AUDIT_SESSION_A;
79
+ assert.equal((await fx.api('POST', `${BASE}/${id}/events`, forged)).status, 409);
80
+ assert.equal(fx.events.size, 0);
81
+ });
82
+
83
+ for (const options of [{ schemaReady: false }, { legacyHost: true }]) {
84
+ test(`loopback HTTP advertises no cross binding for ${options.legacyHost ? 'old Host adapter' : 'pre-058 schema'} while v1 continues`, async (t) => {
85
+ const fx = await conversationAuditHttpFixture(options);
86
+ t.after(() => fx.close());
87
+ assert.equal((await fx.api('GET', `${BASE}/capabilities`)).body.cross_binding_members, false);
88
+ const rejected = await fx.api('POST', BASE, fx.crossInput());
89
+ assert.equal(rejected.status, 503);
90
+ assert.equal(rejected.body.error, 'conversation_audit_cross_binding_unavailable');
91
+ assert.equal(fx.archives.size, 0);
92
+ const created = await fx.api('POST', BASE, fx.input());
93
+ assert.equal(created.body.schema, 'bailing.agent-conversation-audit.v1');
94
+ const id = created.body.conversation_id;
95
+ assert.equal((await fx.api('POST', `${BASE}/${id}/confirm`, {}, fx.tokens.get(AUDIT_SESSION_B)!)).body.state, 'ready');
96
+ assert.equal((await fx.api('POST', `${BASE}/${id}/events`, events)).status, 200);
97
+ const detail = await fx.api('GET', `/admin/api/conversation-audits/${id}`, undefined, fx.adminToken);
98
+ assert.equal(detail.body.events.length, 6);
99
+ assert.equal(Object.hasOwn(detail.body.members[0], 'client_app_id'), false);
100
+ });
101
+ }
102
+
103
+ test('capability discovery requires an explicit true Host result and does not disguise storage errors as support', async (t) => {
104
+ const fx = await conversationAuditHttpFixture();
105
+ t.after(() => fx.close());
106
+ fx.deps.configStore = { ...fx.store, agentConversationAudit: undefined };
107
+ assert.equal((await fx.api('GET', `${BASE}/capabilities`)).body.cross_binding_members, false);
108
+ fx.deps.configStore = fx.store;
109
+ const probe = fx.repo.supportsCrossBindingMembers;
110
+ for (const unsupported of [false, undefined, null, 'true', 1]) {
111
+ fx.repo.supportsCrossBindingMembers = async () => unsupported as boolean;
112
+ assert.equal((await fx.api('GET', `${BASE}/capabilities`)).body.cross_binding_members, false);
113
+ assert.equal((await fx.api('POST', BASE, fx.crossInput())).status, 503);
114
+ assert.equal(fx.archives.size, 0);
115
+ }
116
+ fx.repo.supportsCrossBindingMembers = async () => { throw new Error('SYNTHETIC_PRIVATE_STORAGE_DETAIL'); };
117
+ const failure = await fx.api('GET', `${BASE}/capabilities`);
118
+ assert.equal(failure.status, 503);
119
+ assert.equal(failure.body.error, 'conversation_audit_unavailable');
120
+ assert.doesNotMatch(failure.text, /PRIVATE_STORAGE/);
121
+ fx.repo.supportsCrossBindingMembers = probe;
122
+ });