bailinghub 0.6.1 → 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 +9 -5
- package/README.md +8 -5
- 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 +14 -1
- package/docs/CHANGELOG.md +14 -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 +6 -0
- package/docs/README.md +6 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +3 -0
- package/docs/RELEASE_NOTES_NEXT.md +3 -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 +1 -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 +1 -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 +1 -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
package/src/routes/agent-auth.ts
CHANGED
|
@@ -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
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
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
|
+
});
|
|
@@ -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
|
+
});
|