bailinghub 0.6.1 → 0.8.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 +8 -7
- package/README.md +7 -7
- package/docker-compose.images.yml +2 -2
- package/docs/AGENT_AUTH_API.en.md +112 -1
- package/docs/AGENT_AUTH_API.md +99 -1
- package/docs/AGENT_CLIENT_QUICKSTART.en.md +32 -5
- package/docs/AGENT_CLIENT_QUICKSTART.md +27 -4
- package/docs/AGENT_CLIENT_RUNTIME_API.en.md +46 -0
- package/docs/AGENT_CLIENT_RUNTIME_API.md +38 -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/AGENT_TASK_CONTROL.en.md +25 -0
- package/docs/AGENT_TASK_CONTROL.md +94 -0
- package/docs/AGENT_TASK_CONTROL_FOUNDATION.md +134 -0
- package/docs/CHANGELOG.en.md +24 -1
- package/docs/CHANGELOG.md +24 -1
- package/docs/COMPATIBILITY.en.md +2 -0
- package/docs/CONTRACT.en.md +2 -0
- package/docs/CONTRACT.md +2 -0
- package/docs/GENERATED_ARTIFACTS.en.md +46 -0
- package/docs/GENERATED_ARTIFACTS.md +108 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/INVOCATION_RECEIPTS.md +111 -0
- package/docs/LOCAL_AGENT_SETUP.en.md +116 -0
- package/docs/LOCAL_AGENT_SETUP.md +116 -0
- package/docs/README.en.md +9 -0
- package/docs/README.md +9 -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/RELEASE_NOTES_v0.8.0.en.md +40 -0
- package/docs/RELEASE_NOTES_v0.8.0.md +62 -0
- package/docs/SDK.en.md +31 -0
- package/docs/TOOL_RATE_LIMITS.md +50 -0
- package/docs/UPGRADE_v0.8.0.en.md +71 -0
- package/docs/UPGRADE_v0.8.0.md +73 -0
- package/docs/user-guide/conversations.en.md +4 -2
- package/docs/user-guide/conversations.md +4 -2
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +2 -0
- package/package.json +1 -1
- package/schemas/config/route.schema.json +16 -2
- package/schemas/config/tool-provider.schema.json +2 -1
- package/scripts/check-doc-links.mjs +2 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/e2e-console.mjs +32 -2
- package/scripts/install.sh +1 -1
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +2 -0
- package/scripts/sdk-agent-auth-lifecycle-check.mjs +178 -0
- package/scripts/sdk-runtime-test.mjs +5 -2
- package/scripts/verify-github-repo.mjs +2 -0
- package/sdk/php/README.md +29 -0
- package/sdk/php/src/AgentAuth.php +100 -4
- package/sdk/php/src/HubClient.php +2 -1
- package/sdk/php7/README.md +31 -0
- package/sdk/php7/src/AgentAuth.php +99 -4
- package/sdk/php7/src/HubClient.php +2 -1
- package/sql/058_agent_conversation_member_bindings.sql +9 -0
- package/sql/059_agent_subject_display.sql +5 -0
- package/sql/060_agent_artifacts.sql +11 -0
- package/sql/061_tool_rate_limit_policies.sql +3 -0
- package/sql/062_agent_task_control.sql +92 -0
- package/sql/README.en.md +15 -0
- package/sql/README.md +25 -0
- package/src/adapters/storage/object-storage.ts +15 -3
- package/src/adapters/storage/oss-signature.test.ts +40 -0
- package/src/adapters/storage/oss-signature.ts +21 -0
- package/src/app/agent-artifacts.test.ts +165 -0
- package/src/app/agent-artifacts.ts +85 -0
- package/src/app/agent-client-runtime.test.ts +76 -1
- package/src/app/agent-client-runtime.ts +13 -0
- package/src/app/agent-conversation-audit.ts +20 -0
- package/src/app/agent-invocation-snapshot.ts +35 -0
- package/src/app/agent-system-info.ts +41 -0
- package/src/app/agent-task-control.ts +187 -0
- package/src/app/agent-task-runtime.ts +68 -0
- package/src/app/agent-tool-invocations.test.ts +329 -1
- package/src/app/agent-tool-invocations.ts +239 -14
- package/src/app/agent-tool-job.test.ts +11 -1
- package/src/app/agent-tool-job.ts +8 -1
- package/src/app/builtin-tools.ts +4 -0
- package/src/app/oss-edition.ts +1 -0
- package/src/app/tool-approvals.ts +4 -0
- package/src/app/tool-assembly.ts +5 -0
- package/src/core/config/agent-setup.ts +37 -0
- package/src/core/config/artifact-config.ts +15 -0
- package/src/core/config/client-agent-setup.ts +25 -0
- package/src/core/config/config-codec.ts +3 -1
- package/src/core/config/config-models.ts +11 -1
- 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 +44 -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/tool-rate-limits.test.ts +59 -0
- package/src/core/contracts/tool-rate-limits.ts +48 -0
- package/src/core/contracts/tools.ts +122 -43
- package/src/core/contracts/types.ts +18 -1
- package/src/core/runtime/agent-conversation-audit.test.ts +19 -1
- package/src/core/runtime/agent-conversation-audit.ts +39 -0
- package/src/core/runtime/agent-task-control.test.ts +114 -0
- package/src/core/runtime/agent-task-control.ts +227 -0
- package/src/infrastructure/config/config-agent-artifact-repository.ts +32 -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-client-runtime-repository.ts +7 -1
- 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-agent-task-control-journal-mysql.test.ts +315 -0
- package/src/infrastructure/config/config-agent-task-control-mysql.test.ts +331 -0
- package/src/infrastructure/config/config-agent-task-control-repository.ts +640 -0
- package/src/infrastructure/config/config-client-repository.ts +21 -0
- package/src/infrastructure/config/config-rate-limit-ledger.integration.test.ts +52 -0
- package/src/infrastructure/config/config-rate-limit-ledger.ts +48 -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/config-storage-bucket-repository.ts +2 -2
- package/src/infrastructure/config/config-tool-provider-repository.ts +4 -4
- package/src/infrastructure/config/configstore.ts +16 -4
- 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-agent-tasks.ts +32 -0
- package/src/routes/admin-client-agent-setup.test.ts +93 -0
- package/src/routes/admin-dispatch-config.ts +2 -0
- package/src/routes/admin-tool-providers.test.ts +22 -0
- package/src/routes/admin-tool-providers.ts +9 -1
- package/src/routes/admin.ts +3 -0
- package/src/routes/agent-api.test.ts +76 -0
- package/src/routes/agent-api.ts +49 -1
- package/src/routes/agent-artifacts.ts +29 -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/routes/agent-task-control-http-mysql.test.ts +246 -0
- package/src/routes/private.ts +1 -0
- package/src/routes/run.ts +2 -1
- 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/src/test-support/agent-task-control-mysql-fixture.ts +75 -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-BRCR3O0P.js} +1 -1
- package/web/console/assets/AgentClients-Bf7sUUs_.js +1 -0
- package/web/console/assets/AgentClients-i52AI6YV.css +1 -0
- package/web/console/assets/AgentTasks--bqL_QKg.js +2 -0
- package/web/console/assets/AgentTasks-C8ox3TyS.css +1 -0
- package/web/console/assets/{Approvals-CMvPWacY.js → Approvals-BIbZvInm.js} +1 -1
- package/web/console/assets/{Audit-CIRqOCnL.js → Audit-KyPSmBdZ.js} +1 -1
- package/web/console/assets/{BrandLockup-BrytmTTH.js → BrandLockup-Sv5DU2G6.js} +1 -1
- package/web/console/assets/{Channels-CApxH2TB.js → Channels-B9n4fbxg.js} +1 -1
- package/web/console/assets/{ChatEntries-CJon3bWJ.js → ChatEntries-xsOCUXi_.js} +1 -1
- package/web/console/assets/Clients-CI3DBDHf.js +3 -0
- package/web/console/assets/Clients-CSHIsaWU.css +1 -0
- package/web/console/assets/{Cost-BbhlQFP8.js → Cost-JgNXQPlN.js} +1 -1
- package/web/console/assets/{Credentials-kqr1W0K7.js → Credentials-B5UUUdt0.js} +1 -1
- package/web/console/assets/{Diagnostics-Kljt9XTH.js → Diagnostics-BMGciWQb.js} +1 -1
- package/web/console/assets/{Executors-DnsB-Xz4.js → Executors-CRbboOCZ.js} +1 -1
- package/web/console/assets/{Kb-DLZSAFWP.js → Kb-CgLNGjRp.js} +1 -1
- package/web/console/assets/{Login-DiTjPWmN.js → Login-C52JmXzx.js} +1 -1
- package/web/console/assets/{Projects-CXcVCgCD.js → Projects-CDOvHPVS.js} +1 -1
- package/web/console/assets/Routes-DkMIjMQA.css +1 -0
- package/web/console/assets/Routes-X9vHLpKW.js +124 -0
- package/web/console/assets/Runs-CvGTV8I-.css +1 -0
- package/web/console/assets/Runs-DYNDXsqk.js +3 -0
- package/web/console/assets/{Setup-FqoCKmfZ.js → Setup-B91P6i1x.js} +1 -1
- package/web/console/assets/Shell-Bj6C8Hgo.css +1 -0
- package/web/console/assets/Shell-BsRa7bQQ.js +1 -0
- package/web/console/assets/StorageBuckets-CVgpZRWY.css +1 -0
- package/web/console/assets/StorageBuckets-DkuDM0oX.js +1 -0
- package/web/console/assets/{SystemSettings-gTQAazu7.js → SystemSettings-B7Mqj3k1.js} +1 -1
- package/web/console/assets/{SystemStatus-DAmUUNqO.js → SystemStatus-Db93b6dc.js} +1 -1
- package/web/console/assets/{Targets-CZmDcjsE.js → Targets-CuuIYeZO.js} +1 -1
- package/web/console/assets/Tools-CHiqz9XZ.js +2 -0
- package/web/console/assets/Tools-DU8ei6sd.css +1 -0
- package/web/console/assets/index-UGvfF3Xr.js +2 -0
- package/web/console/assets/{request-r7GHVJzw.js → request-DeGya810.js} +1 -1
- package/web/console/assets/{schema-BVn_hB7M.js → schema-BqlqLw1R.js} +1 -1
- package/web/console/index.html +1 -1
- package/web-admin/scripts/agent-task-control-smoke.mjs +120 -0
- package/web-admin/scripts/subject-display-ui.mjs +78 -0
- package/web-admin/src/components/AgentSetupPanel.vue +275 -0
- package/web-admin/src/components/ClientConversations.vue +21 -4
- package/web-admin/src/components/ToolRateLimitEditor.vue +28 -0
- package/web-admin/src/components/conversation-audit.ts +20 -0
- package/web-admin/src/layout/Shell.vue +1 -1
- package/web-admin/src/pages/AgentClients.vue +99 -23
- package/web-admin/src/pages/AgentTasks.vue +281 -0
- package/web-admin/src/pages/Clients.vue +4 -1
- package/web-admin/src/pages/Routes.vue +10 -1
- package/web-admin/src/pages/StorageBuckets.vue +6 -6
- package/web-admin/src/pages/Tools.vue +53 -4
- package/web-admin/src/router.ts +2 -0
- 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/web/console/assets/Shell-BEqpONiy.js +0 -1
- package/web/console/assets/Shell-D9Uw-fsa.css +0 -1
- package/web/console/assets/StorageBuckets-CkORbYXY.js +0 -1
- package/web/console/assets/StorageBuckets-GnXnVvF0.css +0 -1
- package/web/console/assets/Tools-A20oaMaQ.css +0 -1
- package/web/console/assets/Tools-CIHInlHL.js +0 -2
- package/web/console/assets/index-BkLbd7Cc.js +0 -2
package/src/routes/agent-api.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
import { handleAgentArtifacts } from './agent-artifacts';
|
|
1
2
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
3
|
import { PayloadTooLargeError, readBody, send } from '../app/http';
|
|
3
4
|
import type { Principal } from '../app/auth';
|
|
4
5
|
import type { ToolProxyDeps } from '../app/tool-proxy';
|
|
5
6
|
import {
|
|
6
7
|
AgentToolApiError,
|
|
8
|
+
agentInvocationInspectionCapabilities,
|
|
9
|
+
inspectAgentToolInvocationFor,
|
|
7
10
|
invokeAgentToolFor,
|
|
8
11
|
listAgentToolsFor,
|
|
9
12
|
resumeAgentToolFor,
|
|
@@ -14,6 +17,9 @@ import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
|
14
17
|
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
15
18
|
import { authenticateAgentAccess } from './agent-auth';
|
|
16
19
|
import { handleAgentConversationAuditFor } from './agent-conversation-audit';
|
|
20
|
+
import { getAgentSystemInfoFor } from '../app/agent-system-info';
|
|
21
|
+
import { agentTaskCapabilitiesFor, inspectAgentTaskFor, assertAgentLegacyTaskAllowedFor, taskErrorStatus, publicAgentTaskError } from '../app/agent-task-control';
|
|
22
|
+
import { AgentTaskControlError } from '../core/runtime/agent-task-control';
|
|
17
23
|
import type { KbService } from '../services/kb';
|
|
18
24
|
import {
|
|
19
25
|
completeAgentRunFor,
|
|
@@ -32,6 +38,7 @@ export interface AgentApiHttpDeps {
|
|
|
32
38
|
/** 未注入时仅关闭新的无模型直调面,保持旧宿主的 Agent Auth / run 兼容。 */
|
|
33
39
|
toolProxyDeps?: ToolProxyDeps;
|
|
34
40
|
kbService?: KbService | null;
|
|
41
|
+
artifactRoot?: string;
|
|
35
42
|
}
|
|
36
43
|
|
|
37
44
|
// 64000 个 UTF-16 code units 在 JSON 中最坏可被转义为约 384 KB;512 KiB 还可容纳
|
|
@@ -54,6 +61,11 @@ function declaredFields(body: Record<string, unknown>, allowedFields: string[],
|
|
|
54
61
|
}
|
|
55
62
|
|
|
56
63
|
function sendAgentToolError(res: ServerResponse, error: unknown): void {
|
|
64
|
+
if (error instanceof AgentTaskControlError) {
|
|
65
|
+
const visible = publicAgentTaskError(error);
|
|
66
|
+
send(res, taskErrorStatus(visible), { error: visible.code, message: visible.message });
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
57
69
|
if (error instanceof AgentToolApiError) {
|
|
58
70
|
send(res, error.statusCode, { error: error.code, message: error.message });
|
|
59
71
|
return;
|
|
@@ -92,7 +104,26 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
|
|
|
92
104
|
if (!auth) { send(res, 401, { error: 'unauthorized' }); return true; }
|
|
93
105
|
const principal: Principal = { kind: 'agent', session: auth.session, client: auth.client };
|
|
94
106
|
const method = req.method ?? 'GET';
|
|
107
|
+
if (method === 'GET' && path === '/agent-api/v1/task-control/capabilities') {
|
|
108
|
+
try { send(res, 200, await agentTaskCapabilitiesFor(deps.configStore, auth, Boolean(deps.toolProxyDeps))); }
|
|
109
|
+
catch { send(res, 503, { error: 'TASK_UNAVAILABLE', message: 'Task control could not be verified.' }); }
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
const taskMatch = method === 'GET' ? path.match(/^\/agent-api\/v1\/tasks\/([0-9a-f-]{36})$/i) : null;
|
|
113
|
+
if (taskMatch) {
|
|
114
|
+
try { send(res, 200, await inspectAgentTaskFor(deps.configStore, auth, taskMatch[1]!,
|
|
115
|
+
url.searchParams.get('workspace') ?? '', url.searchParams.get('client_conversation_id') ?? '')); }
|
|
116
|
+
catch (error) { sendAgentToolError(res, error); }
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
if (await handleAgentArtifacts({ configStore: deps.configStore, root: deps.artifactRoot, isPaused: deps.isPaused }, auth, req, res, path)) return true;
|
|
95
120
|
if (await handleAgentConversationAuditFor(deps.configStore, auth, req, res, path)) return true;
|
|
121
|
+
const systemInfoMatch = method === 'GET' ? path.match(/^\/agent-api\/v1\/workspaces\/([a-z0-9][a-z0-9_-]{1,63})\/system-info$/) : null;
|
|
122
|
+
if (systemInfoMatch) {
|
|
123
|
+
try { send(res, 200, await getAgentSystemInfoFor(deps.configStore, auth, systemInfoMatch[1]!)); }
|
|
124
|
+
catch (error) { sendAgentToolError(res, error); }
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
96
127
|
const runtimeDeps = (): AgentClientRuntimeDeps | null => deps.toolProxyDeps
|
|
97
128
|
? { toolProxyDeps: deps.toolProxyDeps, kbService: deps.kbService ?? null, stateStore: deps.stateStore }
|
|
98
129
|
: null;
|
|
@@ -118,7 +149,7 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
|
|
|
118
149
|
if (deps.isPaused()) { send(res, 503, { error: 'hub_paused', status: 'paused' }); return true; }
|
|
119
150
|
const body = await readAgentToolBody(req, res, AGENT_RUNTIME_JSON_BODY_MAX_BYTES);
|
|
120
151
|
if (!body) return true;
|
|
121
|
-
if (!declaredFields(body, ['client_conversation_id', 'client_turn_id', 'user_message_id', 'user_input', 'page_context', 'renderers'], ['client_conversation_id', 'client_turn_id', 'user_message_id', 'user_input'])
|
|
152
|
+
if (!declaredFields(body, ['client_conversation_id', 'client_turn_id', 'user_message_id', 'user_input', 'page_context', 'renderers', 'task_binding'], ['client_conversation_id', 'client_turn_id', 'user_message_id', 'user_input'])
|
|
122
153
|
|| typeof body['client_conversation_id'] !== 'string'
|
|
123
154
|
|| typeof body['client_turn_id'] !== 'string'
|
|
124
155
|
|| typeof body['user_message_id'] !== 'string'
|
|
@@ -133,6 +164,7 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
|
|
|
133
164
|
user_message_id: body['user_message_id'], user_input: body['user_input'],
|
|
134
165
|
...(record(body['page_context']) ? { page_context: record(body['page_context'])! } : {}),
|
|
135
166
|
...(Array.isArray(body['renderers']) ? { renderers: body['renderers'] as string[] } : {}),
|
|
167
|
+
...(Object.hasOwn(body, 'task_binding') ? { task_binding: body['task_binding'] } : {}),
|
|
136
168
|
}));
|
|
137
169
|
} catch (error) { sendAgentToolError(res, error); }
|
|
138
170
|
return true;
|
|
@@ -192,6 +224,20 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
|
|
|
192
224
|
catch (error) { sendAgentToolError(res, error); }
|
|
193
225
|
return true;
|
|
194
226
|
}
|
|
227
|
+
if (method === 'GET' && path === '/agent-api/v1/tool-invocations/inspection-capabilities') {
|
|
228
|
+
if (!deps.toolProxyDeps || !deps.configStore) { send(res, 503, { error: 'agent_tools_unavailable' }); return true; }
|
|
229
|
+
if (url.search) { send(res, 400, { error: 'invalid_request', message: 'Invocation inspection does not accept query parameters.' }); return true; }
|
|
230
|
+
send(res, 200, agentInvocationInspectionCapabilities());
|
|
231
|
+
return true;
|
|
232
|
+
}
|
|
233
|
+
const receiptMatch = method === 'GET' ? path.match(/^\/agent-api\/v1\/tool-invocations\/([a-f0-9]{64})\/receipt$/) : null;
|
|
234
|
+
if (receiptMatch) {
|
|
235
|
+
if (!deps.toolProxyDeps) { send(res, 503, { error: 'agent_tools_unavailable' }); return true; }
|
|
236
|
+
if (url.search) { send(res, 400, { error: 'invalid_request', message: 'Invocation inspection does not accept query parameters.' }); return true; }
|
|
237
|
+
try { send(res, 200, await inspectAgentToolInvocationFor(deps.toolProxyDeps, auth, { invocation_id: receiptMatch[1]! })); }
|
|
238
|
+
catch (error) { sendAgentToolError(res, error); }
|
|
239
|
+
return true;
|
|
240
|
+
}
|
|
195
241
|
if (method === 'POST' && path === '/agent-api/v1/tool-invocations') {
|
|
196
242
|
if (!deps.toolProxyDeps) { send(res, 503, { error: 'agent_tools_unavailable' }); return true; }
|
|
197
243
|
if (deps.isPaused()) { send(res, 503, { error: 'hub_paused', status: 'paused' }); return true; }
|
|
@@ -236,6 +282,8 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
|
|
|
236
282
|
return true;
|
|
237
283
|
}
|
|
238
284
|
if (method === 'POST' && path === '/agent-api/v1/run') {
|
|
285
|
+
try { await assertAgentLegacyTaskAllowedFor(deps.configStore, auth.session.session_id); }
|
|
286
|
+
catch (error) { sendAgentToolError(res, error); return true; }
|
|
239
287
|
await deps.handleRun(req, res, principal);
|
|
240
288
|
return true;
|
|
241
289
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { send } from '../app/http';
|
|
3
|
+
import { AgentToolApiError, type AgentToolAuthContext } from '../app/agent-tool-invocations';
|
|
4
|
+
import { ARTIFACT_MAX_BYTES } from '../core/config/artifact-config';
|
|
5
|
+
import { artifactError, artifactMetadata, readAgentArtifact, uploadAgentArtifact, type ArtifactDeps } from '../app/agent-artifacts';
|
|
6
|
+
|
|
7
|
+
export async function handleAgentArtifacts(deps: ArtifactDeps & { isPaused: () => boolean }, auth: AgentToolAuthContext, req: IncomingMessage, res: ServerResponse, path: string): Promise<boolean> {
|
|
8
|
+
const m = path.match(/^\/agent-api\/v1\/workspaces\/([a-z0-9][a-z0-9_-]{1,63})\/artifacts\/([a-f0-9]{64})$/);
|
|
9
|
+
if (!m) return false;
|
|
10
|
+
try {
|
|
11
|
+
if (req.method === 'GET') send(res, 200, await readAgentArtifact(deps, auth, m[1]!, m[2]!));
|
|
12
|
+
else if (req.method === 'POST') {
|
|
13
|
+
if (deps.isPaused()) artifactError(503, 'hub_paused');
|
|
14
|
+
const raw = req.headers['x-bailing-artifact'];
|
|
15
|
+
if (typeof raw !== 'string' || raw.length > 4096 || !/^[a-zA-Z0-9_-]+$/.test(raw)) artifactError(400, 'artifact_invalid_request');
|
|
16
|
+
let value: unknown;
|
|
17
|
+
try { value = JSON.parse(Buffer.from(raw as string, 'base64url').toString('utf8')); } catch { artifactError(400, 'artifact_invalid_request'); }
|
|
18
|
+
const metadata = artifactMetadata(value);
|
|
19
|
+
if (req.headers['content-type'] !== metadata.mime || (req.headers['content-length'] !== undefined && Number(req.headers['content-length']) !== metadata.bytes)) artifactError(400, 'artifact_content_mismatch');
|
|
20
|
+
const chunks: Buffer[] = []; let size = 0;
|
|
21
|
+
for await (const chunk of req) { const data = Buffer.from(chunk); size += data.length; if (size > Math.min(metadata.bytes, ARTIFACT_MAX_BYTES)) artifactError(413, 'artifact_too_large'); chunks.push(data); }
|
|
22
|
+
send(res, 200, await uploadAgentArtifact(deps, auth, m[1]!, m[2]!, metadata, Buffer.concat(chunks)));
|
|
23
|
+
} else send(res, 405, { error: 'method_not_allowed' });
|
|
24
|
+
} catch (error) {
|
|
25
|
+
if (error instanceof AgentToolApiError) send(res, error.statusCode, { error: error.code });
|
|
26
|
+
else send(res, 503, { error: 'artifact_storage_unavailable' });
|
|
27
|
+
}
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
import type { AddressInfo } from 'node:net';
|
|
4
|
+
import test, { type TestContext } from 'node:test';
|
|
5
|
+
import type { Pool } from 'mysql2/promise';
|
|
6
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
7
|
+
import { AgentAuthRepository } from '../infrastructure/config/config-agent-auth-repository';
|
|
8
|
+
import { evaluateBusinessSessionQuery } from '../test-support/agent-auth-business-query-fixture';
|
|
9
|
+
import { LedgerFixture, REDIRECT } from '../test-support/agent-auth-lifecycle-fixture';
|
|
10
|
+
import { handleAgentAuthHttpFor, pkceChallenge } from './agent-auth';
|
|
11
|
+
|
|
12
|
+
// Real loopback HTTP, route parsing/authorization and repository SQL. Only the
|
|
13
|
+
// SQL engine, client registry and rate counter are synthetic; no MySQL or business
|
|
14
|
+
// server is contacted. Transaction/lock semantics have separate repository tests.
|
|
15
|
+
const CLIENTS = [
|
|
16
|
+
{ app_id: 'example-business', name: 'Example', enabled: true, token: 'synthetic-client-token-a', allowed_routes: ['orders'], agent_authorize_url: 'https://example.test/authorize' },
|
|
17
|
+
{ app_id: 'other-business', name: 'Other', enabled: true, token: 'synthetic-client-token-b', allowed_routes: ['inventory'], agent_authorize_url: 'https://other.example.test/authorize' },
|
|
18
|
+
] as const;
|
|
19
|
+
type SyntheticClient = typeof CLIENTS[number];
|
|
20
|
+
const A = CLIENTS[0];
|
|
21
|
+
const B = CLIENTS[1];
|
|
22
|
+
const verifier = 'synthetic-pkce-verifier-'.padEnd(64, 'v');
|
|
23
|
+
const principal = { id: 'operator', tenant: 'tenant-A', roles: ['manager'] };
|
|
24
|
+
|
|
25
|
+
/** Match the production mysql2 pool's timezone:'Z' DATETIME result decoding. */
|
|
26
|
+
function driverRows(result: any[]): any[] {
|
|
27
|
+
if (!Array.isArray(result[0])) return result;
|
|
28
|
+
return [result[0].map((row: Record<string, unknown>) => Object.fromEntries(Object.entries(row).map(([key, value]) => [key,
|
|
29
|
+
key.endsWith('_at') && typeof value === 'string' && /^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/.test(value)
|
|
30
|
+
? new Date(`${value.replace(' ', 'T')}Z`) : value,
|
|
31
|
+
]))), ...result.slice(1)];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function fixture(t: TestContext) {
|
|
35
|
+
const ledger = new LedgerFixture();
|
|
36
|
+
for (const table of Object.values(ledger.rows)) table.clear();
|
|
37
|
+
const originalQuery = ledger.pool.query.bind(ledger.pool) as (sql: string, params: unknown[]) => Promise<any[]>;
|
|
38
|
+
const pool = {
|
|
39
|
+
async getConnection() {
|
|
40
|
+
const connection = await ledger.pool.getConnection();
|
|
41
|
+
return {
|
|
42
|
+
beginTransaction: connection.beginTransaction.bind(connection), commit: connection.commit.bind(connection),
|
|
43
|
+
rollback: connection.rollback.bind(connection), release: connection.release.bind(connection),
|
|
44
|
+
async query(sql: string, params: unknown[] = []) { return driverRows(await connection.query(sql, params)); },
|
|
45
|
+
};
|
|
46
|
+
},
|
|
47
|
+
async query(sql: string, params: unknown[] = []) {
|
|
48
|
+
if (sql.includes('FROM bz_agent_sessions s WHERE')) {
|
|
49
|
+
return driverRows(evaluateBusinessSessionQuery([...ledger.rows.session.values()], [...ledger.rows.authorization.values()], sql, params));
|
|
50
|
+
}
|
|
51
|
+
return driverRows(await originalQuery(sql, params));
|
|
52
|
+
},
|
|
53
|
+
} as unknown as Pool;
|
|
54
|
+
const repository = new AgentAuthRepository(() => pool);
|
|
55
|
+
const store = {
|
|
56
|
+
agentAuth: repository,
|
|
57
|
+
clients: {
|
|
58
|
+
async get(id: string) { return CLIENTS.find((client) => client.app_id === id) ?? null; },
|
|
59
|
+
async getByToken(token: string) { return CLIENTS.find((client) => client.token === token) ?? null; },
|
|
60
|
+
},
|
|
61
|
+
rateLimits: { async consume() { return false; } },
|
|
62
|
+
} as unknown as ConfigStoreContract;
|
|
63
|
+
const failures: unknown[] = [];
|
|
64
|
+
const server = createServer(async (req, res) => {
|
|
65
|
+
try {
|
|
66
|
+
if (!await handleAgentAuthHttpFor({ configStore: store }, req, res, new URL(req.url!, 'http://127.0.0.1'))) {
|
|
67
|
+
res.writeHead(404); res.end();
|
|
68
|
+
}
|
|
69
|
+
} catch (error) { failures.push(error); res.writeHead(500); res.end('{"error":"fixture_failure"}'); }
|
|
70
|
+
});
|
|
71
|
+
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
72
|
+
t.after(async () => {
|
|
73
|
+
await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
|
|
74
|
+
assert.deepEqual(failures, [], 'unexpected SQL or route exceptions must fail the integration');
|
|
75
|
+
});
|
|
76
|
+
const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
|
77
|
+
async function call(path: string, method = 'GET', body?: unknown, token?: string) {
|
|
78
|
+
const response = await fetch(`${origin}/agent-auth/v1${path}`, {
|
|
79
|
+
method, headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
|
|
80
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
81
|
+
});
|
|
82
|
+
assert.equal(response.headers.get('cache-control'), 'no-store');
|
|
83
|
+
if (path === '/token') assert.equal(response.headers.get('pragma'), 'no-cache');
|
|
84
|
+
return { status: response.status, body: await response.json() as any };
|
|
85
|
+
}
|
|
86
|
+
async function approve(client: SyntheticClient = A) {
|
|
87
|
+
const created = await call('/authorizations', 'POST', {
|
|
88
|
+
client_app_id: client.app_id, redirect_uri: REDIRECT, state: 'synthetic-state', requested_routes: client.allowed_routes,
|
|
89
|
+
device_label: 'Synthetic device', code_challenge: pkceChallenge(verifier), code_challenge_method: 'S256',
|
|
90
|
+
});
|
|
91
|
+
assert.equal(created.status, 201);
|
|
92
|
+
const id: string = created.body.authorization_id;
|
|
93
|
+
assert.equal(new URL(created.body.authorization_url).searchParams.get('authorization_id'), id);
|
|
94
|
+
const context = await call(`/authorizations/${id}`, 'GET', undefined, client.token);
|
|
95
|
+
assert.equal(context.status, 200); assert.equal(context.body.status, 'pending');
|
|
96
|
+
const approved = await call(`/authorizations/${id}/approve`, 'POST', { principal, on_behalf_of: 'tenant-A:operator', allowed_routes: client.allowed_routes }, client.token);
|
|
97
|
+
assert.equal(approved.status, 200);
|
|
98
|
+
const redirect = new URL(approved.body.redirect_uri);
|
|
99
|
+
assert.equal(redirect.searchParams.get('state'), 'synthetic-state');
|
|
100
|
+
const code = redirect.searchParams.get('code'); assert.ok(code);
|
|
101
|
+
return { id, client, code };
|
|
102
|
+
}
|
|
103
|
+
async function exchange(authorization: Awaited<ReturnType<typeof approve>>) {
|
|
104
|
+
return call('/token', 'POST', { grant_type: 'authorization_code', client_app_id: authorization.client.app_id,
|
|
105
|
+
code: authorization.code, redirect_uri: REDIRECT, code_verifier: verifier });
|
|
106
|
+
}
|
|
107
|
+
return { ledger, call, approve, exchange };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
test('HTTP and real repository: approved authorization links to a scoped session; atomic revoke rejects access and refresh', async (t) => {
|
|
111
|
+
const f = await fixture(t);
|
|
112
|
+
const authorization = await f.approve();
|
|
113
|
+
const token = await f.exchange(authorization); assert.equal(token.status, 200);
|
|
114
|
+
const sessionId = token.body.session_id;
|
|
115
|
+
assert.equal(f.ledger.rows.authorization.get(authorization.id)?.session_id, sessionId);
|
|
116
|
+
const context = await f.call(`/authorizations/${authorization.id}`, 'GET', undefined, A.token);
|
|
117
|
+
assert.equal(context.status, 200); assert.equal(context.body.status, 'consumed');
|
|
118
|
+
assert.deepEqual(Object.keys(context.body.session).sort(), ['expires_at', 'session_id', 'state', 'subject_display', 'subject_display_status']);
|
|
119
|
+
assert.equal(context.body.session.session_id, sessionId); assert.equal(context.body.session.state, 'active');
|
|
120
|
+
assert.doesNotMatch(JSON.stringify(context.body), /code_hash|code_challenge|redirect_uri|access_token|refresh_token|principal/);
|
|
121
|
+
|
|
122
|
+
const filters = new URLSearchParams({ authorization_id: authorization.id, on_behalf_of: 'tenant-A:operator', principal_id: 'operator', tenant: 'tenant-A', state: 'active' });
|
|
123
|
+
const listed = await f.call(`/sessions?${filters}`, 'GET', undefined, A.token);
|
|
124
|
+
assert.equal(listed.status, 200); assert.equal(listed.body.list.length, 1);
|
|
125
|
+
assert.equal(listed.body.list[0].session_id, sessionId); assert.equal(listed.body.list[0].authorization_id, authorization.id);
|
|
126
|
+
assert.deepEqual(listed.body.list[0].principal, principal); assert.equal(listed.body.next_cursor, null);
|
|
127
|
+
assert.doesNotMatch(JSON.stringify(listed.body), /token_hash|access_token|refresh_token|code_challenge|code_hash/);
|
|
128
|
+
filters.set('tenant', 'tenant-B');
|
|
129
|
+
assert.deepEqual((await f.call(`/sessions?${filters}`, 'GET', undefined, A.token)).body.list, []);
|
|
130
|
+
assert.equal((await f.call('/session', 'GET', undefined, token.body.access_token)).status, 200);
|
|
131
|
+
|
|
132
|
+
const revoked = await f.call(`/authorizations/${authorization.id}/revoke`, 'POST', {}, A.token);
|
|
133
|
+
assert.equal(revoked.status, 200);
|
|
134
|
+
assert.deepEqual(revoked.body, { authorization_id: authorization.id, revoked: true, session_id: sessionId });
|
|
135
|
+
const after = await f.call(`/authorizations/${authorization.id}`, 'GET', undefined, A.token);
|
|
136
|
+
assert.equal(after.body.status, 'consumed'); assert.equal(after.body.session.state, 'revoked'); assert.ok(after.body.session.revoked_at);
|
|
137
|
+
assert.equal((await f.call('/session', 'GET', undefined, token.body.access_token)).status, 401);
|
|
138
|
+
const refreshed = await f.call('/token', 'POST', { grant_type: 'refresh_token', client_app_id: A.app_id, refresh_token: token.body.refresh_token });
|
|
139
|
+
assert.deepEqual(refreshed, { status: 400, body: { error: 'invalid_grant' } });
|
|
140
|
+
assert.deepEqual(await f.call(`/authorizations/${authorization.id}/revoke`, 'POST', {}, A.token), revoked);
|
|
141
|
+
assert.equal(f.ledger.rows.session.size, 1); assert.equal(f.ledger.rows.token.size, 1);
|
|
142
|
+
assert.ok(f.ledger.rows.session.get(sessionId)?.revoked_at);
|
|
143
|
+
assert.ok([...f.ledger.rows.token.values()].every((row) => row.status === 'revoked'));
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test('HTTP and real repository: revocation after approval but before exchange prevents session issuance', async (t) => {
|
|
147
|
+
const f = await fixture(t); const authorization = await f.approve();
|
|
148
|
+
const revoked = await f.call(`/authorizations/${authorization.id}/revoke`, 'POST', {}, A.token);
|
|
149
|
+
assert.deepEqual(revoked, { status: 200, body: { authorization_id: authorization.id, revoked: true } });
|
|
150
|
+
const stored = f.ledger.rows.authorization.get(authorization.id)!;
|
|
151
|
+
assert.equal(stored.status, 'revoked'); assert.equal(stored.code_hash, null); assert.equal(stored.code_expires_at, null);
|
|
152
|
+
assert.deepEqual(await f.exchange(authorization), { status: 400, body: { error: 'invalid_grant' } });
|
|
153
|
+
assert.equal(f.ledger.rows.session.size, 0); assert.equal(f.ledger.rows.token.size, 0);
|
|
154
|
+
const context = await f.call(`/authorizations/${authorization.id}`, 'GET', undefined, A.token);
|
|
155
|
+
assert.equal(context.body.status, 'revoked'); assert.equal('session' in context.body, false);
|
|
156
|
+
assert.deepEqual(await f.call(`/authorizations/${authorization.id}/revoke`, 'POST', {}, A.token), revoked);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
test('HTTP and real repository: another Client App cannot query or revoke an authorization or its session', async (t) => {
|
|
160
|
+
const f = await fixture(t);
|
|
161
|
+
const authorizationA = await f.approve(A); const tokenA = await f.exchange(authorizationA); assert.equal(tokenA.status, 200);
|
|
162
|
+
const authorizationB = await f.approve(B); const tokenB = await f.exchange(authorizationB); assert.equal(tokenB.status, 200);
|
|
163
|
+
const unknown = { status: 404, body: { error: 'not_found' } };
|
|
164
|
+
assert.deepEqual(await f.call(`/authorizations/${authorizationA.id}`, 'GET', undefined, B.token), unknown);
|
|
165
|
+
assert.deepEqual(await f.call(`/authorizations/${authorizationA.id}/revoke`, 'POST', {}, B.token), unknown);
|
|
166
|
+
assert.deepEqual(await f.call(`/sessions/${tokenA.body.session_id}/revoke`, 'POST', {}, B.token), unknown);
|
|
167
|
+
const hidden = await f.call(`/sessions?authorization_id=${authorizationA.id}`, 'GET', undefined, B.token);
|
|
168
|
+
assert.deepEqual(hidden, { status: 200, body: { list: [], next_cursor: null } });
|
|
169
|
+
for (const [client, token] of [[A, tokenA], [B, tokenB]] as const) {
|
|
170
|
+
const list = await f.call('/sessions?tenant=tenant-A', 'GET', undefined, client.token);
|
|
171
|
+
assert.equal(list.status, 200); assert.equal(list.body.list.length, 1);
|
|
172
|
+
assert.equal(list.body.list[0].client_app_id, client.app_id); assert.equal(list.body.list[0].session_id, token.body.session_id);
|
|
173
|
+
assert.equal((await f.call('/session', 'GET', undefined, token.body.access_token)).status, 200);
|
|
174
|
+
}
|
|
175
|
+
assert.ok([...f.ledger.rows.session.values()].every((row) => row.revoked_at === null));
|
|
176
|
+
assert.ok([...f.ledger.rows.token.values()].every((row) => row.status === 'active'));
|
|
177
|
+
});
|
|
@@ -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)}`);
|