bailinghub 0.3.4 → 0.5.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/.gitignore +5 -0
- package/README.en.md +6 -1
- package/README.md +6 -0
- package/SECURITY.md +11 -0
- package/docker-compose.images.yml +2 -2
- package/docs/AGENT_AUTH_API.en.md +175 -0
- package/docs/AGENT_AUTH_API.md +190 -0
- package/docs/AGENT_CLIENT_QUICKSTART.en.md +212 -0
- package/docs/AGENT_CLIENT_QUICKSTART.md +206 -0
- package/docs/AGENT_CLIENT_RUNTIME_API.en.md +157 -0
- package/docs/AGENT_CLIENT_RUNTIME_API.md +107 -0
- package/docs/CHANGELOG.en.md +59 -1
- package/docs/CHANGELOG.md +27 -1
- package/docs/COMPATIBILITY.en.md +25 -0
- package/docs/CONTRACT.en.md +79 -8
- package/docs/CONTRACT.md +36 -6
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/QUICKSTART.en.md +6 -0
- package/docs/QUICKSTART.md +1 -1
- package/docs/README.en.md +8 -0
- package/docs/README.md +8 -0
- package/docs/RELEASE_NOTES_v0.4.0.en.md +39 -0
- package/docs/RELEASE_NOTES_v0.4.0.md +39 -0
- package/docs/RELEASE_NOTES_v0.5.0.en.md +41 -0
- package/docs/RELEASE_NOTES_v0.5.0.md +41 -0
- package/docs/STREAMING.en.md +32 -0
- package/docs/STREAMING.md +8 -2
- package/docs/WIDGET_RENDERERS.en.md +123 -6
- package/docs/WIDGET_RENDERERS.md +75 -6
- package/docs/user-guide/console-map.en.md +1 -2
- package/docs/user-guide/console-map.md +2 -2
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +9 -0
- package/package.json +3 -2
- package/schemas/config/chat-entry.schema.json +2 -1
- package/schemas/config/client.schema.json +7 -0
- package/schemas/config/common.schema.json +30 -0
- package/schemas/config/route.schema.json +11 -0
- package/scripts/check-doc-links.mjs +1 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +5 -5
- package/scripts/e2e-console.mjs +144 -0
- package/scripts/export-oss.mjs +5 -12
- package/scripts/install.sh +1 -1
- package/scripts/public-content-denylist.mjs +82 -0
- package/scripts/public-content-denylist.test.mjs +53 -0
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +8 -12
- package/scripts/sdk-runtime-test.mjs +171 -7
- package/scripts/security-scan.mjs +8 -5
- package/scripts/validate-examples.mjs +3 -1
- package/scripts/verify-github-repo.mjs +7 -11
- package/scripts/verify-oss-export.mjs +6 -12
- package/scripts/widget-renderer-test.mjs +244 -16
- package/sdk/php/README.md +27 -1
- package/sdk/php/src/AgentAuth.php +78 -0
- package/sdk/php/src/HubClient.php +3 -0
- package/sdk/php7/README.md +32 -2
- package/sdk/php7/src/AgentAuth.php +77 -0
- package/sdk/php7/src/HubClient.php +3 -0
- package/sql/055_agent_auth.sql +72 -0
- package/sql/056_agent_client_runtime.sql +60 -0
- package/src/adapters/channels/wecom-api.ts +1 -1
- package/src/app/agent-client-runtime.test.ts +221 -0
- package/src/app/agent-client-runtime.ts +408 -0
- package/src/app/agent-tool-invocations.test.ts +462 -0
- package/src/app/agent-tool-invocations.ts +795 -0
- package/src/app/agent-tool-job.test.ts +62 -0
- package/src/app/agent-tool-job.ts +41 -0
- package/src/app/auth.ts +2 -1
- package/src/app/kernel.ts +2 -0
- package/src/app/runtime-context.ts +8 -0
- package/src/app/tool-approvals.ts +5 -1
- package/src/app/tool-assembly.ts +19 -1
- package/src/app/tool-context.ts +2 -1
- package/src/core/config/config-codec.ts +2 -1
- package/src/core/config/config-models.test.ts +28 -1
- package/src/core/config/config-models.ts +46 -3
- package/src/core/config/config-schema.test.ts +8 -0
- package/src/core/config/route-config.test.ts +15 -0
- package/src/core/config/route-config.ts +36 -0
- package/src/core/config/tools-config.test.ts +58 -1
- package/src/core/config/tools-config.ts +84 -0
- package/src/core/contracts/tools.ts +162 -29
- package/src/core/contracts/types.ts +38 -1
- package/src/core/platform/chat-form.test.ts +147 -0
- package/src/core/platform/chat-form.ts +402 -0
- package/src/core/platform/version.ts +1 -1
- package/src/core/runtime/agent-client-trace.test.ts +154 -0
- package/src/core/runtime/agent-client-trace.ts +288 -0
- package/src/core/runtime/execution-runtime.test.ts +61 -0
- package/src/core/runtime/execution-runtime.ts +17 -0
- package/src/core/runtime/launch-runtime.ts +13 -0
- package/src/core/runtime/trace-runtime.test.ts +18 -1
- package/src/core/runtime/trace-runtime.ts +28 -3
- package/src/core/state/state-codec.ts +2 -0
- package/src/infrastructure/config/config-agent-auth-repository.test.ts +147 -0
- package/src/infrastructure/config/config-agent-auth-repository.ts +356 -0
- package/src/infrastructure/config/config-agent-client-runtime-repository.ts +253 -0
- package/src/infrastructure/config/config-approval-ledger.test.ts +32 -0
- package/src/infrastructure/config/config-approval-ledger.ts +16 -0
- package/src/infrastructure/config/config-client-repository.ts +3 -3
- package/src/infrastructure/config/config-conversation-ledger.test.ts +69 -0
- package/src/infrastructure/config/config-conversation-ledger.ts +8 -7
- package/src/infrastructure/config/config-observability-ledger.test.ts +50 -0
- package/src/infrastructure/config/config-observability-ledger.ts +65 -10
- package/src/infrastructure/config/config-route-repository.ts +4 -3
- package/src/infrastructure/config/configstore.ts +14 -3
- package/src/infrastructure/state/state-mysql.ts +2 -2
- package/src/kernel-api/v1/contracts.ts +8 -0
- package/src/routes/admin-runtime.test.ts +214 -0
- package/src/routes/admin-runtime.ts +82 -2
- package/src/routes/agent-api.test.ts +379 -0
- package/src/routes/agent-api.ts +251 -0
- package/src/routes/agent-auth.test.ts +276 -0
- package/src/routes/agent-auth.ts +395 -0
- package/src/routes/approvals.ts +4 -1
- package/src/routes/chat.test.ts +319 -7
- package/src/routes/chat.ts +166 -21
- package/src/routes/critical-routes.test.ts +235 -1
- package/src/routes/private-default.ts +2 -1
- package/src/routes/private.ts +16 -1
- package/src/routes/run.ts +79 -13
- package/web/connect/bailing-connect-php.tgz +0 -0
- package/web/connect/bailing-connect-php7.tgz +0 -0
- package/web/console/assets/{Accounts-CAwrtBiS.js → Accounts-D4RRm5D1.js} +1 -1
- package/web/console/assets/{Approvals-C2BZ86T3.js → Approvals-CsTTKb8o.js} +1 -1
- package/web/console/assets/{Audit-B-E4Y_Up.js → Audit-BzvZ7JZw.js} +1 -1
- package/web/console/assets/{BrandLockup-C18u8Lx5.js → BrandLockup-CYcA93wh.js} +1 -1
- package/web/console/assets/{Channels-DTy8ylH-.js → Channels-DRQZggqM.js} +1 -1
- package/web/console/assets/ChatEntries-BUB7BWKU.js +7 -0
- package/web/console/assets/ChatEntries-DsYtcXN6.css +1 -0
- package/web/console/assets/Clients-CQ_MonGL.css +1 -0
- package/web/console/assets/Clients-HhCyrxfz.js +3 -0
- package/web/console/assets/{Cost-2SSYs1AT.js → Cost-BZgFf1yM.js} +1 -1
- package/web/console/assets/{Credentials-B79LtxCE.js → Credentials-BTe2Q07j.js} +1 -1
- package/web/console/assets/{Diagnostics-BakcRYvb.js → Diagnostics-WL-buYli.js} +1 -1
- package/web/console/assets/{Executors-BXoyo28u.js → Executors-CGZ-7Xmp.js} +1 -1
- package/web/console/assets/{Kb-ISbzquab.js → Kb-VVw8oGsT.js} +1 -1
- package/web/console/assets/{Login-Dlu6Wgcf.js → Login-rwvmBBPl.js} +1 -1
- package/web/console/assets/{Projects-DFzmtnqg.js → Projects-CexaCEY1.js} +1 -1
- package/web/console/assets/Routes-B9ZHbQAp.js +124 -0
- package/web/console/assets/Routes-BbkFpi6Y.css +1 -0
- package/web/console/assets/Runs-4zDD9VOC.css +1 -0
- package/web/console/assets/Runs-BzFNPTwD.js +3 -0
- package/web/console/assets/{Setup-CrBAV-b9.js → Setup-Djh5yadQ.js} +1 -1
- package/web/console/assets/{Shell-B1a8DvXQ.js → Shell-kn763smL.js} +1 -1
- package/web/console/assets/{StorageBuckets-BRfL_eHb.js → StorageBuckets-CQBR41W1.js} +1 -1
- package/web/console/assets/{SystemSettings-CyirVLbq.js → SystemSettings-DgnopekD.js} +1 -1
- package/web/console/assets/{SystemStatus-DZ_OR7sk.js → SystemStatus-Bj8-kPt2.js} +1 -1
- package/web/console/assets/{Targets-CtIMa66c.js → Targets-BAfCt_nH.js} +1 -1
- package/web/console/assets/{Tools-BfDZHt01.js → Tools-xjd0NZdE.js} +1 -1
- package/web/console/assets/{index-DBiByFiO.js → index-DfJA7iJS.js} +2 -2
- package/web/console/assets/{request-DY2cxQqZ.js → request-DkNPOweH.js} +1 -1
- package/web/console/assets/{schema-6mCQ7rR5.js → schema-CgPWAu1_.js} +1 -1
- package/web/console/index.html +1 -1
- package/web/widget/widget.js +493 -14
- package/web-admin/src/pages/ChatEntries.vue +18 -6
- package/web-admin/src/pages/Clients.vue +11 -3
- package/web-admin/src/pages/Routes.vue +282 -16
- package/web-admin/src/pages/Runs.vue +159 -38
- package/web/console/assets/ChatEntries-9xbRiQov.css +0 -1
- package/web/console/assets/ChatEntries-DvD-4IeE.js +0 -7
- package/web/console/assets/Clients--D7NQJKk.css +0 -1
- package/web/console/assets/Clients-DWs9JFr0.js +0 -3
- package/web/console/assets/Routes-B-hm9HGY.js +0 -124
- package/web/console/assets/Routes-DWGQN5Pv.css +0 -1
- package/web/console/assets/Runs-CUtSsPW-.css +0 -1
- package/web/console/assets/Runs-hMRu1im3.js +0 -3
|
@@ -93,17 +93,18 @@ export function completeTraceEntry(entry: AuditEntry): Required<AuditEntry> {
|
|
|
93
93
|
}
|
|
94
94
|
|
|
95
95
|
export function traceStageOf(event: string, detail: Record<string, unknown> = {}): TraceStage {
|
|
96
|
-
if (event === 'received' || event === 'awaiting_executor' || event === 'rejected') return 'launch';
|
|
96
|
+
if (event === 'received' || event === 'awaiting_executor' || event === 'rejected' || event === 'agent_client_run_started') return 'launch';
|
|
97
97
|
if (
|
|
98
98
|
event === 'kb_injected' || event === 'kb_error' ||
|
|
99
|
+
event === 'agent_client_turn_context_ready' ||
|
|
99
100
|
event === 'perception_degraded' || event === 'speech_degraded' || event === 'file_input' || event === 'file_input_degraded' ||
|
|
100
101
|
event === 'tools_retrieval_degraded' || event === 'tools_retrieval_diagnostics'
|
|
101
102
|
) return 'context';
|
|
102
103
|
if (event.startsWith('memory_summary') || event === 'memory_summarized') return 'summary';
|
|
103
104
|
if (event === 'recovered' || event === 'rerun' || event === 'retry_scheduled') return 'recovery';
|
|
104
105
|
if (event.includes('approval') || event === 'tool_approved' || event === 'tool_denied' || event === 'tool_args_drift') return 'approval';
|
|
105
|
-
if (event.startsWith('tool_') || event === 'tools_retrieved' || event === 'tool_lookup' || event === 'builtin_send' || event.startsWith('builtin_send_')) return 'tool';
|
|
106
|
-
if (event.startsWith('delivery') || event.startsWith('channel_delivery') || event.startsWith('dlq_')) return 'delivery';
|
|
106
|
+
if (event.startsWith('tool_') || event.startsWith('agent_tool_') || event === 'tools_retrieved' || event === 'tool_lookup' || event === 'builtin_send' || event.startsWith('builtin_send_')) return 'tool';
|
|
107
|
+
if (event === 'agent_client_run_completed' || event.startsWith('delivery') || event.startsWith('channel_delivery') || event.startsWith('dlq_')) return 'delivery';
|
|
107
108
|
if (event.startsWith('channel_') || event.startsWith('wecom_') || event === 'chat_upload' || event === 'chat_upload_error' || event === 'chat_rated') return 'channel';
|
|
108
109
|
if (
|
|
109
110
|
event === 'started' || event === 'dispatched' || event === 'finished' ||
|
|
@@ -124,6 +125,13 @@ export function traceStageOf(event: string, detail: Record<string, unknown> = {}
|
|
|
124
125
|
|
|
125
126
|
export function traceSeverityOf(event: string, detail: Record<string, unknown> = {}): TraceSeverity {
|
|
126
127
|
const status = String(detail['status'] ?? '');
|
|
128
|
+
if (event === 'agent_tool_invocation_state') {
|
|
129
|
+
const state = String(detail['state'] ?? '');
|
|
130
|
+
if (state === 'in_progress') return 'info';
|
|
131
|
+
if (state === 'awaiting_approval' || state === 'denied' || state === 'business_rejected' || state === 'rejected_before_dispatch') return 'warning';
|
|
132
|
+
if (state === 'reconciliation_required') return 'error';
|
|
133
|
+
if (state === 'executed') return detail['ok'] === false ? 'error' : 'info';
|
|
134
|
+
}
|
|
127
135
|
if (event === 'tools_retrieval_diagnostics' && status !== 'ok') return 'warning';
|
|
128
136
|
if (event === 'finished' && (status === 'error' || status === 'rejected')) return 'error';
|
|
129
137
|
if (event.includes('error') || event.includes('failed') || event.endsWith('_failure')) return 'error';
|
|
@@ -136,6 +144,11 @@ export function traceSeverityOf(event: string, detail: Record<string, unknown> =
|
|
|
136
144
|
export function traceTitleOf(event: string): string {
|
|
137
145
|
const titles: Record<string, string> = {
|
|
138
146
|
received: '任务已接收',
|
|
147
|
+
agent_client_run_started: '本地智能体开始处理',
|
|
148
|
+
agent_client_turn_context_ready: '运行上下文已就绪',
|
|
149
|
+
agent_client_run_completed: '本地智能体已提交最终回复',
|
|
150
|
+
agent_tool_invocation_created: 'ACC 工具调用已建立',
|
|
151
|
+
agent_tool_invocation_state: 'ACC 工具调用状态更新',
|
|
139
152
|
awaiting_executor: '等待执行器认领',
|
|
140
153
|
rejected: '任务被拒绝',
|
|
141
154
|
started: '本地执行开始',
|
|
@@ -196,6 +209,18 @@ export function traceTitleOf(event: string): string {
|
|
|
196
209
|
|
|
197
210
|
export function traceSummaryOf(event: string, detail: Record<string, unknown> = {}): string {
|
|
198
211
|
if (event === 'received') return compact([detail['target'], detail['profile'], detail['source']]);
|
|
212
|
+
if (event === 'agent_client_run_started') return '本地智能体规划;中枢保留治理与审计';
|
|
213
|
+
if (event === 'agent_client_turn_context_ready') return compact([
|
|
214
|
+
detail['route'],
|
|
215
|
+
detail['active_tools'] != null ? `${detail['active_tools']} active tools` : '',
|
|
216
|
+
]);
|
|
217
|
+
if (event === 'agent_client_run_completed') return compact([detail['status']]);
|
|
218
|
+
if (event === 'agent_tool_invocation_created') return compact([detail['tool'], detail['route']]);
|
|
219
|
+
if (event === 'agent_tool_invocation_state') return compact([
|
|
220
|
+
detail['tool'],
|
|
221
|
+
detail['state'],
|
|
222
|
+
detail['business_status'] != null ? `business=${detail['business_status']}` : '',
|
|
223
|
+
]);
|
|
199
224
|
if (event === 'awaiting_executor') return compact([detail['target']]);
|
|
200
225
|
if (event === 'rejected') return compact([detail['reason'], detail['quota'] != null ? `quota=${detail['quota']}` : '']);
|
|
201
226
|
if (event === 'dispatched') return compact([detail['executor_id'], detail['target'], detail['tools'] != null ? `${detail['tools']} tools` : '']);
|
|
@@ -19,6 +19,8 @@ export function rowToJob(r: any): Job {
|
|
|
19
19
|
project: r.project,
|
|
20
20
|
source: r.source,
|
|
21
21
|
client_app_id: r.client_app_id ?? undefined,
|
|
22
|
+
agent_session_id: r.agent_session_id ?? undefined,
|
|
23
|
+
on_behalf_of: r.on_behalf_of ?? undefined,
|
|
22
24
|
thread_id: r.thread_id != null ? Number(r.thread_id) : undefined,
|
|
23
25
|
session_id: r.session_id ?? undefined,
|
|
24
26
|
input_preview: r.input_preview ?? '',
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import type { Pool } from 'mysql2/promise';
|
|
4
|
+
import { AgentAuthRepository } from './config-agent-auth-repository';
|
|
5
|
+
|
|
6
|
+
function sessionRow(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
|
7
|
+
return {
|
|
8
|
+
session_id: '123e4567-e89b-42d3-a456-426614174000',
|
|
9
|
+
client_app_id: 'example-business',
|
|
10
|
+
device_label: 'Mac mini',
|
|
11
|
+
principal_json: JSON.stringify({ id: 'user-7', tenant: 'tenant-2', roles: ['manager'] }),
|
|
12
|
+
on_behalf_of: 'tenant-2:user-7',
|
|
13
|
+
allowed_routes: JSON.stringify(['orders']),
|
|
14
|
+
access_token_hash: 'a'.repeat(64),
|
|
15
|
+
access_expires_at: '2099-01-01 00:15:00',
|
|
16
|
+
refresh_expires_at: '2099-01-30 00:00:00',
|
|
17
|
+
created_at: '2099-01-01 00:00:00',
|
|
18
|
+
updated_at: '2099-01-01 00:00:00',
|
|
19
|
+
last_seen_at: null,
|
|
20
|
+
revoked_at: null,
|
|
21
|
+
...overrides,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
test('AgentAuthRepository refresh rotation keeps the original absolute refresh expiry', async () => {
|
|
26
|
+
const originalRefreshExpiry = '2099-01-30 00:00:00';
|
|
27
|
+
let insertedRefreshExpiry: unknown;
|
|
28
|
+
let updatedSessionParams: unknown[] = [];
|
|
29
|
+
const row = sessionRow({ refresh_expires_at: originalRefreshExpiry });
|
|
30
|
+
const connection = {
|
|
31
|
+
beginTransaction: async () => undefined,
|
|
32
|
+
commit: async () => undefined,
|
|
33
|
+
rollback: async () => undefined,
|
|
34
|
+
release: () => undefined,
|
|
35
|
+
async query(sql: string, params: unknown[] = []) {
|
|
36
|
+
if (sql.startsWith('SELECT * FROM bz_agent_refresh_tokens')) {
|
|
37
|
+
return [[{ token_hash: 'r'.repeat(64), session_id: row.session_id, status: 'active', expires_at: originalRefreshExpiry }], []];
|
|
38
|
+
}
|
|
39
|
+
if (sql.startsWith('SELECT * FROM bz_agent_sessions') && sql.includes('FOR UPDATE')) return [[row], []];
|
|
40
|
+
if (sql.startsWith('UPDATE bz_agent_refresh_tokens SET status=\'used\'')) return [{ affectedRows: 1 }, []];
|
|
41
|
+
if (sql.startsWith('INSERT INTO bz_agent_refresh_tokens')) {
|
|
42
|
+
insertedRefreshExpiry = params[3];
|
|
43
|
+
return [{ affectedRows: 1 }, []];
|
|
44
|
+
}
|
|
45
|
+
if (sql.startsWith('UPDATE bz_agent_sessions SET access_token_hash=')) {
|
|
46
|
+
updatedSessionParams = params;
|
|
47
|
+
row.access_token_hash = params[0];
|
|
48
|
+
row.access_expires_at = params[1];
|
|
49
|
+
return [{ affectedRows: 1 }, []];
|
|
50
|
+
}
|
|
51
|
+
if (sql.startsWith('SELECT * FROM bz_agent_sessions')) return [[row], []];
|
|
52
|
+
throw new Error(`unexpected query: ${sql}`);
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
const pool = { getConnection: async () => connection } as unknown as Pool;
|
|
56
|
+
const repo = new AgentAuthRepository(() => pool);
|
|
57
|
+
const result = await repo.rotateRefreshToken({
|
|
58
|
+
refreshTokenHash: 'r'.repeat(64),
|
|
59
|
+
clientAppId: 'example-business',
|
|
60
|
+
accessTokenHash: 'b'.repeat(64),
|
|
61
|
+
nextRefreshTokenHash: 'n'.repeat(64),
|
|
62
|
+
accessExpiresAt: '2099-01-01T00:30:00.000Z',
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
assert.equal(result.ok, true);
|
|
66
|
+
assert.equal(insertedRefreshExpiry, originalRefreshExpiry);
|
|
67
|
+
assert.equal(updatedSessionParams.length, 4);
|
|
68
|
+
assert.equal(updatedSessionParams.includes(originalRefreshExpiry), false);
|
|
69
|
+
if (result.ok) assert.equal(Date.parse(result.session.refresh_expires_at), new Date(originalRefreshExpiry).getTime());
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test('AgentAuthRepository refresh replay revokes the whole session fail closed', async () => {
|
|
73
|
+
let sessionRevoked = false;
|
|
74
|
+
let refreshFamilyRevoked = false;
|
|
75
|
+
const row = sessionRow();
|
|
76
|
+
const connection = {
|
|
77
|
+
beginTransaction: async () => undefined,
|
|
78
|
+
commit: async () => undefined,
|
|
79
|
+
rollback: async () => undefined,
|
|
80
|
+
release: () => undefined,
|
|
81
|
+
async query(sql: string) {
|
|
82
|
+
if (sql.startsWith('SELECT * FROM bz_agent_refresh_tokens')) {
|
|
83
|
+
return [[{ token_hash: 'r'.repeat(64), session_id: row.session_id, status: 'used', expires_at: row.refresh_expires_at }], []];
|
|
84
|
+
}
|
|
85
|
+
if (sql.startsWith('SELECT * FROM bz_agent_sessions')) return [[row], []];
|
|
86
|
+
if (sql.startsWith('UPDATE bz_agent_sessions SET revoked_at=')) { sessionRevoked = true; return [{ affectedRows: 1 }, []]; }
|
|
87
|
+
if (sql.startsWith('UPDATE bz_agent_refresh_tokens SET status=CASE')) { refreshFamilyRevoked = true; return [{ affectedRows: 2 }, []]; }
|
|
88
|
+
throw new Error(`unexpected query: ${sql}`);
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
const pool = { getConnection: async () => connection } as unknown as Pool;
|
|
92
|
+
const repo = new AgentAuthRepository(() => pool);
|
|
93
|
+
const result = await repo.rotateRefreshToken({
|
|
94
|
+
refreshTokenHash: 'r'.repeat(64),
|
|
95
|
+
clientAppId: 'example-business',
|
|
96
|
+
accessTokenHash: 'b'.repeat(64),
|
|
97
|
+
nextRefreshTokenHash: 'n'.repeat(64),
|
|
98
|
+
accessExpiresAt: '2099-01-01T00:30:00.000Z',
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
assert.deepEqual(result, { ok: false, reason: 'replayed' });
|
|
102
|
+
assert.equal(sessionRevoked, true);
|
|
103
|
+
assert.equal(refreshFamilyRevoked, true);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test('AgentAuthRepository rejects an approved authorization after its short code expiry', async () => {
|
|
107
|
+
let insertedSession = false;
|
|
108
|
+
const connection = {
|
|
109
|
+
beginTransaction: async () => undefined,
|
|
110
|
+
commit: async () => undefined,
|
|
111
|
+
rollback: async () => undefined,
|
|
112
|
+
release: () => undefined,
|
|
113
|
+
async query(sql: string) {
|
|
114
|
+
if (sql.startsWith('SELECT * FROM bz_agent_authorizations')) {
|
|
115
|
+
return [[{
|
|
116
|
+
authorization_id: '123e4567-e89b-42d3-a456-426614174000',
|
|
117
|
+
client_app_id: 'example-business',
|
|
118
|
+
redirect_uri: 'http://127.0.0.1:43123/callback',
|
|
119
|
+
code_challenge: 'c'.repeat(43),
|
|
120
|
+
code_expires_at: '2000-01-01 00:00:00',
|
|
121
|
+
status: 'approved',
|
|
122
|
+
principal_json: JSON.stringify({ id: 'user-7', roles: [] }),
|
|
123
|
+
on_behalf_of: 'tenant-2:user-7',
|
|
124
|
+
allowed_routes: JSON.stringify(['orders']),
|
|
125
|
+
}], []];
|
|
126
|
+
}
|
|
127
|
+
if (sql.startsWith('INSERT INTO bz_agent_sessions')) { insertedSession = true; return [{ affectedRows: 1 }, []]; }
|
|
128
|
+
throw new Error(`unexpected query: ${sql}`);
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
const pool = { getConnection: async () => connection } as unknown as Pool;
|
|
132
|
+
const repo = new AgentAuthRepository(() => pool);
|
|
133
|
+
const result = await repo.exchangeAuthorizationCode({
|
|
134
|
+
codeHash: 'c'.repeat(64),
|
|
135
|
+
clientAppId: 'example-business',
|
|
136
|
+
redirectUri: 'http://127.0.0.1:43123/callback',
|
|
137
|
+
codeChallenge: 'c'.repeat(43),
|
|
138
|
+
sessionId: '223e4567-e89b-42d3-a456-426614174000',
|
|
139
|
+
accessTokenHash: 'a'.repeat(64),
|
|
140
|
+
refreshTokenHash: 'r'.repeat(64),
|
|
141
|
+
accessExpiresAt: '2099-01-01T00:15:00.000Z',
|
|
142
|
+
refreshExpiresAt: '2099-01-30T00:00:00.000Z',
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
assert.deepEqual(result, { ok: false, reason: 'invalid_grant' });
|
|
146
|
+
assert.equal(insertedSession, false);
|
|
147
|
+
});
|
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
import type { Pool, PoolConnection, ResultSetHeader } from 'mysql2/promise';
|
|
2
|
+
import { dt, dtIso } from '../../core/config/config-codec';
|
|
3
|
+
import type { AgentBusinessPrincipal, AgentSession } from '../../core/contracts/types';
|
|
4
|
+
|
|
5
|
+
export type AgentAuthorizationStatus = 'pending' | 'approved' | 'consumed' | 'denied' | 'expired';
|
|
6
|
+
|
|
7
|
+
export interface AgentAuthorization {
|
|
8
|
+
authorization_id: string;
|
|
9
|
+
client_app_id: string;
|
|
10
|
+
redirect_uri: string;
|
|
11
|
+
state: string;
|
|
12
|
+
requested_routes: string[];
|
|
13
|
+
device_label: string;
|
|
14
|
+
code_challenge: string;
|
|
15
|
+
status: AgentAuthorizationStatus;
|
|
16
|
+
principal?: AgentBusinessPrincipal;
|
|
17
|
+
on_behalf_of?: string;
|
|
18
|
+
allowed_routes?: string[];
|
|
19
|
+
created_at: string;
|
|
20
|
+
expires_at: string;
|
|
21
|
+
code_expires_at?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type AuthorizationMutationResult =
|
|
25
|
+
| { ok: true; authorization: AgentAuthorization }
|
|
26
|
+
| { ok: false; reason: 'not_found' | 'wrong_client' | 'expired' | 'invalid_state' };
|
|
27
|
+
|
|
28
|
+
export type AuthorizationExchangeResult =
|
|
29
|
+
| { ok: true; session: AgentSession }
|
|
30
|
+
| { ok: false; reason: 'invalid_grant' };
|
|
31
|
+
|
|
32
|
+
export type RefreshRotationResult =
|
|
33
|
+
| { ok: true; session: AgentSession }
|
|
34
|
+
| { ok: false; reason: 'invalid_grant' | 'replayed' };
|
|
35
|
+
|
|
36
|
+
function jsonObject<T extends object>(value: unknown): T {
|
|
37
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) return value as T;
|
|
38
|
+
if (typeof value === 'string') {
|
|
39
|
+
const parsed: unknown = JSON.parse(value);
|
|
40
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed as T;
|
|
41
|
+
}
|
|
42
|
+
throw new Error('Agent Auth 账本包含无效 JSON 对象');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function stringArray(value: unknown): string[] {
|
|
46
|
+
const parsed: unknown = typeof value === 'string' ? JSON.parse(value) : value;
|
|
47
|
+
if (!Array.isArray(parsed) || !parsed.every((item) => typeof item === 'string')) {
|
|
48
|
+
throw new Error('Agent Auth 账本包含无效路由白名单');
|
|
49
|
+
}
|
|
50
|
+
return [...new Set(parsed)];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function iso(value: unknown): string {
|
|
54
|
+
return new Date(value as string | number | Date).toISOString();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function authorizationRow(row: any): AgentAuthorization {
|
|
58
|
+
return {
|
|
59
|
+
authorization_id: String(row.authorization_id),
|
|
60
|
+
client_app_id: String(row.client_app_id),
|
|
61
|
+
redirect_uri: String(row.redirect_uri),
|
|
62
|
+
state: String(row.state_value),
|
|
63
|
+
requested_routes: stringArray(row.requested_routes),
|
|
64
|
+
device_label: String(row.device_label),
|
|
65
|
+
code_challenge: String(row.code_challenge),
|
|
66
|
+
status: String(row.status) as AgentAuthorizationStatus,
|
|
67
|
+
...(row.principal_json ? { principal: jsonObject<AgentBusinessPrincipal>(row.principal_json) } : {}),
|
|
68
|
+
...(row.on_behalf_of ? { on_behalf_of: String(row.on_behalf_of) } : {}),
|
|
69
|
+
...(row.allowed_routes ? { allowed_routes: stringArray(row.allowed_routes) } : {}),
|
|
70
|
+
created_at: iso(row.created_at),
|
|
71
|
+
expires_at: iso(row.expires_at),
|
|
72
|
+
...(row.code_expires_at ? { code_expires_at: iso(row.code_expires_at) } : {}),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function sessionRow(row: any): AgentSession {
|
|
77
|
+
return {
|
|
78
|
+
session_id: String(row.session_id),
|
|
79
|
+
client_app_id: String(row.client_app_id),
|
|
80
|
+
device_label: String(row.device_label),
|
|
81
|
+
principal: jsonObject<AgentBusinessPrincipal>(row.principal_json),
|
|
82
|
+
on_behalf_of: String(row.on_behalf_of),
|
|
83
|
+
allowed_routes: stringArray(row.allowed_routes),
|
|
84
|
+
created_at: iso(row.created_at),
|
|
85
|
+
access_expires_at: iso(row.access_expires_at),
|
|
86
|
+
refresh_expires_at: iso(row.refresh_expires_at),
|
|
87
|
+
...(row.revoked_at ? { revoked_at: iso(row.revoked_at) } : {}),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function rollback(connection: PoolConnection): Promise<void> {
|
|
92
|
+
await connection.rollback().catch(() => undefined);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** MySQL-backed Agent Auth ledger. It only accepts token/code hashes. */
|
|
96
|
+
export class AgentAuthRepository {
|
|
97
|
+
constructor(private readonly poolOf: () => Pool) {}
|
|
98
|
+
|
|
99
|
+
private get pool(): Pool { return this.poolOf(); }
|
|
100
|
+
|
|
101
|
+
async createAuthorization(input: {
|
|
102
|
+
authorizationId: string;
|
|
103
|
+
clientAppId: string;
|
|
104
|
+
redirectUri: string;
|
|
105
|
+
state: string;
|
|
106
|
+
requestedRoutes: string[];
|
|
107
|
+
deviceLabel: string;
|
|
108
|
+
codeChallenge: string;
|
|
109
|
+
expiresAt: string;
|
|
110
|
+
}): Promise<void> {
|
|
111
|
+
await this.pool.query(
|
|
112
|
+
'INSERT INTO bz_agent_authorizations (authorization_id,client_app_id,redirect_uri,state_value,requested_routes,device_label,code_challenge,status,created_at,expires_at) VALUES (?,?,?,?,?,?,?,\'pending\',?,?)',
|
|
113
|
+
[input.authorizationId, input.clientAppId, input.redirectUri, input.state, JSON.stringify(input.requestedRoutes), input.deviceLabel,
|
|
114
|
+
input.codeChallenge, dt(), dtIso(input.expiresAt)],
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async getAuthorization(authorizationId: string): Promise<AgentAuthorization | null> {
|
|
119
|
+
const [rows] = await this.pool.query('SELECT * FROM bz_agent_authorizations WHERE authorization_id=? LIMIT 1', [authorizationId]);
|
|
120
|
+
return (rows as any[])[0] ? authorizationRow((rows as any[])[0]) : null;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async approveAuthorization(input: {
|
|
124
|
+
authorizationId: string;
|
|
125
|
+
clientAppId: string;
|
|
126
|
+
principal: AgentBusinessPrincipal;
|
|
127
|
+
onBehalfOf: string;
|
|
128
|
+
allowedRoutes: string[];
|
|
129
|
+
codeHash: string;
|
|
130
|
+
codeExpiresAt: string;
|
|
131
|
+
}): Promise<AuthorizationMutationResult> {
|
|
132
|
+
const connection = await this.pool.getConnection();
|
|
133
|
+
try {
|
|
134
|
+
await connection.beginTransaction();
|
|
135
|
+
const [rows] = await connection.query('SELECT * FROM bz_agent_authorizations WHERE authorization_id=? FOR UPDATE', [input.authorizationId]);
|
|
136
|
+
const row = (rows as any[])[0];
|
|
137
|
+
if (!row) { await rollback(connection); return { ok: false, reason: 'not_found' }; }
|
|
138
|
+
if (String(row.client_app_id) !== input.clientAppId) { await rollback(connection); return { ok: false, reason: 'wrong_client' }; }
|
|
139
|
+
if (new Date(row.expires_at).getTime() <= Date.now()) {
|
|
140
|
+
await connection.query('UPDATE bz_agent_authorizations SET status=\'expired\' WHERE authorization_id=? AND status=\'pending\'', [input.authorizationId]);
|
|
141
|
+
await connection.commit();
|
|
142
|
+
return { ok: false, reason: 'expired' };
|
|
143
|
+
}
|
|
144
|
+
if (String(row.status) !== 'pending') { await rollback(connection); return { ok: false, reason: 'invalid_state' }; }
|
|
145
|
+
const [result] = await connection.query<ResultSetHeader>(
|
|
146
|
+
'UPDATE bz_agent_authorizations SET status=\'approved\',principal_json=?,on_behalf_of=?,allowed_routes=?,code_hash=?,code_expires_at=?,approved_at=? WHERE authorization_id=? AND status=\'pending\'',
|
|
147
|
+
[JSON.stringify(input.principal), input.onBehalfOf, JSON.stringify(input.allowedRoutes), input.codeHash, dtIso(input.codeExpiresAt), dt(), input.authorizationId],
|
|
148
|
+
);
|
|
149
|
+
if (result.affectedRows !== 1) { await rollback(connection); return { ok: false, reason: 'invalid_state' }; }
|
|
150
|
+
const [updated] = await connection.query('SELECT * FROM bz_agent_authorizations WHERE authorization_id=? LIMIT 1', [input.authorizationId]);
|
|
151
|
+
await connection.commit();
|
|
152
|
+
return { ok: true, authorization: authorizationRow((updated as any[])[0]) };
|
|
153
|
+
} catch (error) {
|
|
154
|
+
await rollback(connection);
|
|
155
|
+
throw error;
|
|
156
|
+
} finally {
|
|
157
|
+
connection.release();
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async denyAuthorization(input: { authorizationId: string; clientAppId: string }): Promise<AuthorizationMutationResult> {
|
|
162
|
+
const connection = await this.pool.getConnection();
|
|
163
|
+
try {
|
|
164
|
+
await connection.beginTransaction();
|
|
165
|
+
const [rows] = await connection.query('SELECT * FROM bz_agent_authorizations WHERE authorization_id=? FOR UPDATE', [input.authorizationId]);
|
|
166
|
+
const row = (rows as any[])[0];
|
|
167
|
+
if (!row) { await rollback(connection); return { ok: false, reason: 'not_found' }; }
|
|
168
|
+
if (String(row.client_app_id) !== input.clientAppId) { await rollback(connection); return { ok: false, reason: 'wrong_client' }; }
|
|
169
|
+
if (new Date(row.expires_at).getTime() <= Date.now()) {
|
|
170
|
+
await connection.query('UPDATE bz_agent_authorizations SET status=\'expired\' WHERE authorization_id=? AND status=\'pending\'', [input.authorizationId]);
|
|
171
|
+
await connection.commit();
|
|
172
|
+
return { ok: false, reason: 'expired' };
|
|
173
|
+
}
|
|
174
|
+
if (String(row.status) !== 'pending') { await rollback(connection); return { ok: false, reason: 'invalid_state' }; }
|
|
175
|
+
await connection.query('UPDATE bz_agent_authorizations SET status=\'denied\' WHERE authorization_id=? AND status=\'pending\'', [input.authorizationId]);
|
|
176
|
+
const [updated] = await connection.query('SELECT * FROM bz_agent_authorizations WHERE authorization_id=? LIMIT 1', [input.authorizationId]);
|
|
177
|
+
await connection.commit();
|
|
178
|
+
return { ok: true, authorization: authorizationRow((updated as any[])[0]) };
|
|
179
|
+
} catch (error) {
|
|
180
|
+
await rollback(connection);
|
|
181
|
+
throw error;
|
|
182
|
+
} finally {
|
|
183
|
+
connection.release();
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async exchangeAuthorizationCode(input: {
|
|
188
|
+
codeHash: string;
|
|
189
|
+
clientAppId: string;
|
|
190
|
+
redirectUri: string;
|
|
191
|
+
codeChallenge: string;
|
|
192
|
+
sessionId: string;
|
|
193
|
+
accessTokenHash: string;
|
|
194
|
+
refreshTokenHash: string;
|
|
195
|
+
accessExpiresAt: string;
|
|
196
|
+
refreshExpiresAt: string;
|
|
197
|
+
}): Promise<AuthorizationExchangeResult> {
|
|
198
|
+
const connection = await this.pool.getConnection();
|
|
199
|
+
try {
|
|
200
|
+
await connection.beginTransaction();
|
|
201
|
+
const [rows] = await connection.query('SELECT * FROM bz_agent_authorizations WHERE code_hash=? FOR UPDATE', [input.codeHash]);
|
|
202
|
+
const row = (rows as any[])[0];
|
|
203
|
+
if (!row || String(row.status) !== 'approved' || String(row.client_app_id) !== input.clientAppId ||
|
|
204
|
+
String(row.redirect_uri) !== input.redirectUri || String(row.code_challenge) !== input.codeChallenge ||
|
|
205
|
+
!row.code_expires_at || new Date(row.code_expires_at).getTime() <= Date.now() || !row.principal_json || !row.on_behalf_of || !row.allowed_routes) {
|
|
206
|
+
await rollback(connection);
|
|
207
|
+
return { ok: false, reason: 'invalid_grant' };
|
|
208
|
+
}
|
|
209
|
+
const createdAt = dt();
|
|
210
|
+
await connection.query(
|
|
211
|
+
'INSERT INTO bz_agent_sessions (session_id,client_app_id,device_label,principal_json,on_behalf_of,allowed_routes,access_token_hash,access_expires_at,refresh_expires_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)',
|
|
212
|
+
[input.sessionId, input.clientAppId, row.device_label, typeof row.principal_json === 'string' ? row.principal_json : JSON.stringify(row.principal_json),
|
|
213
|
+
row.on_behalf_of, typeof row.allowed_routes === 'string' ? row.allowed_routes : JSON.stringify(row.allowed_routes), input.accessTokenHash,
|
|
214
|
+
dtIso(input.accessExpiresAt), dtIso(input.refreshExpiresAt), createdAt, createdAt],
|
|
215
|
+
);
|
|
216
|
+
await connection.query(
|
|
217
|
+
'INSERT INTO bz_agent_refresh_tokens (token_hash,session_id,status,created_at,expires_at) VALUES (?,? ,\'active\',?,?)',
|
|
218
|
+
[input.refreshTokenHash, input.sessionId, createdAt, dtIso(input.refreshExpiresAt)],
|
|
219
|
+
);
|
|
220
|
+
const [updated] = await connection.query<ResultSetHeader>(
|
|
221
|
+
'UPDATE bz_agent_authorizations SET status=\'consumed\',session_id=?,consumed_at=? WHERE authorization_id=? AND status=\'approved\'',
|
|
222
|
+
[input.sessionId, createdAt, row.authorization_id],
|
|
223
|
+
);
|
|
224
|
+
if (updated.affectedRows !== 1) { await rollback(connection); return { ok: false, reason: 'invalid_grant' }; }
|
|
225
|
+
const [sessionRows] = await connection.query('SELECT * FROM bz_agent_sessions WHERE session_id=? LIMIT 1', [input.sessionId]);
|
|
226
|
+
await connection.commit();
|
|
227
|
+
return { ok: true, session: sessionRow((sessionRows as any[])[0]) };
|
|
228
|
+
} catch (error) {
|
|
229
|
+
await rollback(connection);
|
|
230
|
+
throw error;
|
|
231
|
+
} finally {
|
|
232
|
+
connection.release();
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async getSessionByAccessHash(accessTokenHash: string): Promise<AgentSession | null> {
|
|
237
|
+
const [rows] = await this.pool.query(
|
|
238
|
+
'SELECT * FROM bz_agent_sessions WHERE access_token_hash=? AND revoked_at IS NULL AND access_expires_at>=? AND refresh_expires_at>=? LIMIT 1',
|
|
239
|
+
[accessTokenHash, dt(), dt()],
|
|
240
|
+
);
|
|
241
|
+
const row = (rows as any[])[0];
|
|
242
|
+
if (!row) return null;
|
|
243
|
+
void this.pool.query('UPDATE bz_agent_sessions SET last_seen_at=? WHERE session_id=?', [dt(), row.session_id]).catch(() => undefined);
|
|
244
|
+
return sessionRow(row);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async rotateRefreshToken(input: {
|
|
248
|
+
refreshTokenHash: string;
|
|
249
|
+
clientAppId: string;
|
|
250
|
+
accessTokenHash: string;
|
|
251
|
+
nextRefreshTokenHash: string;
|
|
252
|
+
accessExpiresAt: string;
|
|
253
|
+
}): Promise<RefreshRotationResult> {
|
|
254
|
+
const connection = await this.pool.getConnection();
|
|
255
|
+
try {
|
|
256
|
+
await connection.beginTransaction();
|
|
257
|
+
const [tokenRows] = await connection.query('SELECT * FROM bz_agent_refresh_tokens WHERE token_hash=? FOR UPDATE', [input.refreshTokenHash]);
|
|
258
|
+
const tokenRow = (tokenRows as any[])[0];
|
|
259
|
+
if (!tokenRow) { await rollback(connection); return { ok: false, reason: 'invalid_grant' }; }
|
|
260
|
+
const [sessionRows] = await connection.query('SELECT * FROM bz_agent_sessions WHERE session_id=? FOR UPDATE', [tokenRow.session_id]);
|
|
261
|
+
const session = (sessionRows as any[])[0];
|
|
262
|
+
if (!session || String(session.client_app_id) !== input.clientAppId) { await rollback(connection); return { ok: false, reason: 'invalid_grant' }; }
|
|
263
|
+
if (String(tokenRow.status) !== 'active') {
|
|
264
|
+
const stamp = dt();
|
|
265
|
+
await connection.query('UPDATE bz_agent_sessions SET revoked_at=COALESCE(revoked_at,?),updated_at=? WHERE session_id=?', [stamp, stamp, session.session_id]);
|
|
266
|
+
await connection.query('UPDATE bz_agent_refresh_tokens SET status=CASE WHEN token_hash=? THEN \'replayed\' ELSE \'revoked\' END,used_at=COALESCE(used_at,?) WHERE session_id=? AND status IN (\'active\',\'used\')', [input.refreshTokenHash, stamp, session.session_id]);
|
|
267
|
+
await connection.commit();
|
|
268
|
+
return { ok: false, reason: 'replayed' };
|
|
269
|
+
}
|
|
270
|
+
if (session.revoked_at || new Date(tokenRow.expires_at).getTime() <= Date.now() || new Date(session.refresh_expires_at).getTime() <= Date.now()) {
|
|
271
|
+
await rollback(connection);
|
|
272
|
+
return { ok: false, reason: 'invalid_grant' };
|
|
273
|
+
}
|
|
274
|
+
const stamp = dt();
|
|
275
|
+
await connection.query('UPDATE bz_agent_refresh_tokens SET status=\'used\',used_at=? WHERE token_hash=? AND status=\'active\'', [stamp, input.refreshTokenHash]);
|
|
276
|
+
await connection.query(
|
|
277
|
+
'INSERT INTO bz_agent_refresh_tokens (token_hash,session_id,status,created_at,expires_at) VALUES (?,? ,\'active\',?,?)',
|
|
278
|
+
[input.nextRefreshTokenHash, session.session_id, stamp, session.refresh_expires_at],
|
|
279
|
+
);
|
|
280
|
+
await connection.query(
|
|
281
|
+
'UPDATE bz_agent_sessions SET access_token_hash=?,access_expires_at=?,updated_at=? WHERE session_id=? AND revoked_at IS NULL',
|
|
282
|
+
[input.accessTokenHash, dtIso(input.accessExpiresAt), stamp, session.session_id],
|
|
283
|
+
);
|
|
284
|
+
const [updated] = await connection.query('SELECT * FROM bz_agent_sessions WHERE session_id=? LIMIT 1', [session.session_id]);
|
|
285
|
+
await connection.commit();
|
|
286
|
+
return { ok: true, session: sessionRow((updated as any[])[0]) };
|
|
287
|
+
} catch (error) {
|
|
288
|
+
await rollback(connection);
|
|
289
|
+
throw error;
|
|
290
|
+
} finally {
|
|
291
|
+
connection.release();
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async revokeByAccessHash(accessTokenHash: string): Promise<boolean> {
|
|
296
|
+
const stamp = dt();
|
|
297
|
+
const [result] = await this.pool.query<ResultSetHeader>(
|
|
298
|
+
'UPDATE bz_agent_sessions SET revoked_at=COALESCE(revoked_at,?),updated_at=? WHERE access_token_hash=?',
|
|
299
|
+
[stamp, stamp, accessTokenHash],
|
|
300
|
+
);
|
|
301
|
+
if (result.affectedRows > 0) {
|
|
302
|
+
await this.pool.query(
|
|
303
|
+
'UPDATE bz_agent_refresh_tokens r JOIN bz_agent_sessions s ON s.session_id=r.session_id SET r.status=\'revoked\',r.used_at=COALESCE(r.used_at,?) WHERE s.access_token_hash=? AND r.status=\'active\'',
|
|
304
|
+
[stamp, accessTokenHash],
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
return result.affectedRows > 0;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async revokeByRefreshHash(clientAppId: string, refreshTokenHash: string): Promise<boolean> {
|
|
311
|
+
const connection = await this.pool.getConnection();
|
|
312
|
+
try {
|
|
313
|
+
await connection.beginTransaction();
|
|
314
|
+
const [rows] = await connection.query(
|
|
315
|
+
'SELECT s.session_id FROM bz_agent_refresh_tokens r JOIN bz_agent_sessions s ON s.session_id=r.session_id WHERE r.token_hash=? AND s.client_app_id=? LIMIT 1 FOR UPDATE',
|
|
316
|
+
[refreshTokenHash, clientAppId],
|
|
317
|
+
);
|
|
318
|
+
const sessionId = (rows as any[])[0]?.session_id;
|
|
319
|
+
if (!sessionId) { await rollback(connection); return false; }
|
|
320
|
+
const stamp = dt();
|
|
321
|
+
await connection.query('UPDATE bz_agent_sessions SET revoked_at=COALESCE(revoked_at,?),updated_at=? WHERE session_id=?', [stamp, stamp, sessionId]);
|
|
322
|
+
await connection.query('UPDATE bz_agent_refresh_tokens SET status=\'revoked\',used_at=COALESCE(used_at,?) WHERE session_id=? AND status=\'active\'', [stamp, sessionId]);
|
|
323
|
+
await connection.commit();
|
|
324
|
+
return true;
|
|
325
|
+
} catch (error) {
|
|
326
|
+
await rollback(connection);
|
|
327
|
+
throw error;
|
|
328
|
+
} finally {
|
|
329
|
+
connection.release();
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
async revokeSessionForClient(clientAppId: string, sessionId: string): Promise<boolean> {
|
|
334
|
+
const connection = await this.pool.getConnection();
|
|
335
|
+
try {
|
|
336
|
+
await connection.beginTransaction();
|
|
337
|
+
const [rows] = await connection.query(
|
|
338
|
+
'SELECT session_id FROM bz_agent_sessions WHERE session_id=? AND client_app_id=? LIMIT 1 FOR UPDATE',
|
|
339
|
+
[sessionId, clientAppId],
|
|
340
|
+
);
|
|
341
|
+
if (!(rows as any[])[0]) { await rollback(connection); return false; }
|
|
342
|
+
const stamp = dt();
|
|
343
|
+
await connection.query('UPDATE bz_agent_sessions SET revoked_at=COALESCE(revoked_at,?),updated_at=? WHERE session_id=?', [stamp, stamp, sessionId]);
|
|
344
|
+
await connection.query('UPDATE bz_agent_refresh_tokens SET status=\'revoked\',used_at=COALESCE(used_at,?) WHERE session_id=? AND status=\'active\'', [stamp, sessionId]);
|
|
345
|
+
await connection.commit();
|
|
346
|
+
return true;
|
|
347
|
+
} catch (error) {
|
|
348
|
+
await rollback(connection);
|
|
349
|
+
throw error;
|
|
350
|
+
} finally {
|
|
351
|
+
connection.release();
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
export type AgentAuthRepositoryContract = Pick<AgentAuthRepository, keyof AgentAuthRepository>;
|