bailinghub 0.4.0 → 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 +5 -2
- package/README.md +5 -2
- 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 +13 -0
- package/docs/CHANGELOG.md +13 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/README.en.md +8 -2
- package/docs/README.md +8 -2
- package/docs/RELEASE_NOTES_v0.5.0.en.md +41 -0
- package/docs/RELEASE_NOTES_v0.5.0.md +41 -0
- package/package.json +3 -2
- 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 -1
- 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 -13
- 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 -12
- package/scripts/verify-oss-export.mjs +6 -12
- 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 +10 -0
- package/src/core/config/config-models.ts +21 -0
- package/src/core/config/config-schema.test.ts +6 -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 +36 -0
- 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/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/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-DuUY2UJU.js → Accounts-D4RRm5D1.js} +1 -1
- package/web/console/assets/{Approvals-B11mo1dy.js → Approvals-CsTTKb8o.js} +1 -1
- package/web/console/assets/{Audit-CQwJRIJT.js → Audit-BzvZ7JZw.js} +1 -1
- package/web/console/assets/{BrandLockup-BIF-h1pi.js → BrandLockup-CYcA93wh.js} +1 -1
- package/web/console/assets/{Channels-BIploUT-.js → Channels-DRQZggqM.js} +1 -1
- package/web/console/assets/{ChatEntries-Cpg_WV-o.js → ChatEntries-BUB7BWKU.js} +1 -1
- package/web/console/assets/Clients-CQ_MonGL.css +1 -0
- package/web/console/assets/Clients-HhCyrxfz.js +3 -0
- package/web/console/assets/{Cost-BF52tfU2.js → Cost-BZgFf1yM.js} +1 -1
- package/web/console/assets/{Credentials-SwfmQAv6.js → Credentials-BTe2Q07j.js} +1 -1
- package/web/console/assets/{Diagnostics-CJfbI_8p.js → Diagnostics-WL-buYli.js} +1 -1
- package/web/console/assets/{Executors-CzlZlznA.js → Executors-CGZ-7Xmp.js} +1 -1
- package/web/console/assets/{Kb-CVX22U4k.js → Kb-VVw8oGsT.js} +1 -1
- package/web/console/assets/{Login-PoUVsBI-.js → Login-rwvmBBPl.js} +1 -1
- package/web/console/assets/{Projects-DYlbjLQy.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-xiPXit_b.js → Setup-Djh5yadQ.js} +1 -1
- package/web/console/assets/{Shell-DNiWZOYB.js → Shell-kn763smL.js} +1 -1
- package/web/console/assets/{StorageBuckets-Bjsc3pLd.js → StorageBuckets-CQBR41W1.js} +1 -1
- package/web/console/assets/{SystemSettings-CcKF2lJ9.js → SystemSettings-DgnopekD.js} +1 -1
- package/web/console/assets/{SystemStatus-Oj1xjxJn.js → SystemStatus-Bj8-kPt2.js} +1 -1
- package/web/console/assets/{Targets-y1KllVXT.js → Targets-BAfCt_nH.js} +1 -1
- package/web/console/assets/{Tools-DoEP_y9x.js → Tools-xjd0NZdE.js} +1 -1
- package/web/console/assets/{index-CxPIS6G7.js → index-DfJA7iJS.js} +2 -2
- package/web/console/assets/{request-CBLNpLth.js → request-DkNPOweH.js} +1 -1
- package/web/console/assets/{schema-DzwLpuOy.js → schema-CgPWAu1_.js} +1 -1
- package/web/console/index.html +1 -1
- 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/Clients--D7NQJKk.css +0 -1
- package/web/console/assets/Clients-DS29eUi2.js +0 -3
- package/web/console/assets/Routes-DSEvGujN.js +0 -124
- package/web/console/assets/Routes-DWGQN5Pv.css +0 -1
- package/web/console/assets/Runs-B-TsYZEt.js +0 -3
- package/web/console/assets/Runs-CUtSsPW-.css +0 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { spawnSync } from 'node:child_process';
|
|
1
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
2
|
+
import { createServer } from 'node:http';
|
|
2
3
|
import { dirname, resolve } from 'node:path';
|
|
3
4
|
import { fileURLToPath } from 'node:url';
|
|
4
5
|
import {
|
|
@@ -33,6 +34,27 @@ function run(cmd, args, input) {
|
|
|
33
34
|
return { status: r.status, stdout: r.stdout.trim(), stderr: r.stderr.trim() };
|
|
34
35
|
}
|
|
35
36
|
|
|
37
|
+
function runAsync(cmd, args, input) {
|
|
38
|
+
return new Promise((resolveRun) => {
|
|
39
|
+
const child = spawn(cmd, args, { cwd: root, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
40
|
+
let stdout = '';
|
|
41
|
+
let stderr = '';
|
|
42
|
+
child.stdout.setEncoding('utf8');
|
|
43
|
+
child.stderr.setEncoding('utf8');
|
|
44
|
+
child.stdout.on('data', (chunk) => { stdout += chunk; });
|
|
45
|
+
child.stderr.on('data', (chunk) => { stderr += chunk; });
|
|
46
|
+
child.on('error', (error) => resolveRun({ status: null, stdout: stdout.trim(), stderr: String(error) }));
|
|
47
|
+
child.on('close', (status) => resolveRun({ status, stdout: stdout.trim(), stderr: stderr.trim() }));
|
|
48
|
+
child.stdin.end(input ?? '');
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function closeServer(server) {
|
|
53
|
+
await new Promise((resolveClose, rejectClose) => {
|
|
54
|
+
server.close((error) => error ? rejectClose(error) : resolveClose());
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
36
58
|
console.log('— SDK runtime helpers');
|
|
37
59
|
ok('Node signTicket deterministic vector', signTicket('secret', 'tenant:user', { expiresAt: 2_000_000_000 }) === expectedTicket);
|
|
38
60
|
|
|
@@ -62,9 +84,11 @@ ok('Python HubClient is exported', py.status === 0 && py.stdout.split('\n')[1] =
|
|
|
62
84
|
const php = run('php', ['-r', `
|
|
63
85
|
require '${root}/sdk/php/src/Ticket.php';
|
|
64
86
|
require '${root}/sdk/php/src/HubClient.php';
|
|
87
|
+
require '${root}/sdk/php/src/AgentAuth.php';
|
|
65
88
|
require '${root}/sdk/php/src/SpecServer.php';
|
|
66
89
|
echo Bailing\\Connect\\Ticket::sign('secret', 'tenant:user', 7200, 2000000000), "\\n";
|
|
67
90
|
echo class_exists('Bailing\\\\Connect\\\\HubClient') ? 'HubClient' : 'missing', "\\n";
|
|
91
|
+
echo class_exists('Bailing\\\\Connect\\\\AgentAuth') ? 'AgentAuth' : 'missing', "\\n";
|
|
68
92
|
$protectedHeaders = Bailing\\Connect\\SpecServer::responseHeaders('tool-secret');
|
|
69
93
|
echo isset($protectedHeaders['Cache-Control']) ? $protectedHeaders['Cache-Control'] : 'missing', "\\n";
|
|
70
94
|
list($publicStatus, $publicBody) = Bailing\\Connect\\SpecServer::handlePublic('{"ok":true}', 'GET', '/tools.json');
|
|
@@ -74,16 +98,19 @@ echo ($legacyStatus === 200 && $legacyBody === '{"ok":true}') ? 'legacy-null' :
|
|
|
74
98
|
`]);
|
|
75
99
|
ok('PHP sign ticket deterministic vector', php.status === 0 && php.stdout.split('\n')[0] === expectedTicket, php.stderr || php.stdout);
|
|
76
100
|
ok('PHP HubClient is exported', php.status === 0 && php.stdout.split('\n')[1] === 'HubClient', php.stderr || php.stdout);
|
|
77
|
-
ok('PHP
|
|
78
|
-
ok('PHP
|
|
79
|
-
ok('PHP
|
|
101
|
+
ok('PHP AgentAuth is exported', php.status === 0 && php.stdout.split('\n')[2] === 'AgentAuth', php.stderr || php.stdout);
|
|
102
|
+
ok('PHP protected spec response is private/no-store', php.status === 0 && php.stdout.split('\n')[3] === 'private, no-store', php.stderr || php.stdout);
|
|
103
|
+
ok('PHP explicit public spec helper works', php.status === 0 && php.stdout.split('\n')[4] === 'public-helper', php.stderr || php.stdout);
|
|
104
|
+
ok('PHP legacy null-public signature remains compatible', php.status === 0 && php.stdout.split('\n')[5] === 'legacy-null', php.stderr || php.stdout);
|
|
80
105
|
|
|
81
106
|
const php7 = run('php', ['-r', `
|
|
82
107
|
require '${root}/sdk/php7/src/Ticket.php';
|
|
83
108
|
require '${root}/sdk/php7/src/HubClient.php';
|
|
109
|
+
require '${root}/sdk/php7/src/AgentAuth.php';
|
|
84
110
|
require '${root}/sdk/php7/src/SpecServer.php';
|
|
85
111
|
echo Bailing\\Connect\\Ticket::sign('secret', 'tenant:user', 7200, 2000000000), "\\n";
|
|
86
112
|
echo class_exists('Bailing\\\\Connect\\\\HubClient') ? 'HubClient' : 'missing', "\\n";
|
|
113
|
+
echo class_exists('Bailing\\\\Connect\\\\AgentAuth') ? 'AgentAuth' : 'missing', "\\n";
|
|
87
114
|
$protectedHeaders = Bailing\\Connect\\SpecServer::responseHeaders('tool-secret');
|
|
88
115
|
echo isset($protectedHeaders['Cache-Control']) ? $protectedHeaders['Cache-Control'] : 'missing', "\\n";
|
|
89
116
|
list($publicStatus, $publicBody) = Bailing\\Connect\\SpecServer::handlePublic('{"ok":true}', 'GET', '/tools.json');
|
|
@@ -93,9 +120,146 @@ echo ($legacyStatus === 200 && $legacyBody === '{"ok":true}') ? 'legacy-null' :
|
|
|
93
120
|
`]);
|
|
94
121
|
ok('PHP7 sign ticket deterministic vector', php7.status === 0 && php7.stdout.split('\n')[0] === expectedTicket, php7.stderr || php7.stdout);
|
|
95
122
|
ok('PHP7 HubClient is exported', php7.status === 0 && php7.stdout.split('\n')[1] === 'HubClient', php7.stderr || php7.stdout);
|
|
96
|
-
ok('PHP7
|
|
97
|
-
ok('PHP7
|
|
98
|
-
ok('PHP7
|
|
123
|
+
ok('PHP7 AgentAuth is exported', php7.status === 0 && php7.stdout.split('\n')[2] === 'AgentAuth', php7.stderr || php7.stdout);
|
|
124
|
+
ok('PHP7 protected spec response is private/no-store', php7.status === 0 && php7.stdout.split('\n')[3] === 'private, no-store', php7.stderr || php7.stdout);
|
|
125
|
+
ok('PHP7 explicit public spec helper works', php7.status === 0 && php7.stdout.split('\n')[4] === 'public-helper', php7.stderr || php7.stdout);
|
|
126
|
+
ok('PHP7 legacy null-public signature remains compatible', php7.status === 0 && php7.stdout.split('\n')[5] === 'legacy-null', php7.stderr || php7.stdout);
|
|
127
|
+
|
|
128
|
+
const authorizationId = '11111111-1111-4111-8111-111111111111';
|
|
129
|
+
const sessionId = '22222222-2222-4222-8222-222222222222';
|
|
130
|
+
const agentAuthRequests = [];
|
|
131
|
+
const agentAuthServer = createServer(async (req, res) => {
|
|
132
|
+
let body = '';
|
|
133
|
+
for await (const chunk of req) body += chunk;
|
|
134
|
+
agentAuthRequests.push({
|
|
135
|
+
method: req.method,
|
|
136
|
+
url: req.url,
|
|
137
|
+
authorization: req.headers.authorization,
|
|
138
|
+
contentType: req.headers['content-type'],
|
|
139
|
+
body,
|
|
140
|
+
});
|
|
141
|
+
res.setHeader('Content-Type', 'application/json');
|
|
142
|
+
if (req.url === '/redirect') {
|
|
143
|
+
res.statusCode = 302;
|
|
144
|
+
res.setHeader('Location', '/agent-auth-leak');
|
|
145
|
+
res.end('{}');
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
if (req.url === '/agent-auth-leak') {
|
|
149
|
+
res.end('{"leaked":true}');
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (req.url === `/agent-auth/v1/authorizations/${authorizationId}`) {
|
|
153
|
+
res.end('{"requested_routes":["staff-route"]}');
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
if (req.url?.endsWith('/approve')) {
|
|
157
|
+
res.end('{"redirect_uri":"http://127.0.0.1/callback?code=unit-test"}');
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (req.url?.endsWith('/deny')) {
|
|
161
|
+
res.end('{"status":"denied"}');
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (req.url?.endsWith('/revoke')) {
|
|
165
|
+
res.end('{"status":"revoked"}');
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
res.statusCode = 404;
|
|
169
|
+
res.end('{"error":"not found"}');
|
|
170
|
+
});
|
|
171
|
+
await new Promise((resolveListen, rejectListen) => {
|
|
172
|
+
agentAuthServer.once('error', rejectListen);
|
|
173
|
+
agentAuthServer.listen(0, '127.0.0.1', resolveListen);
|
|
174
|
+
});
|
|
175
|
+
let php7AgentAuth;
|
|
176
|
+
try {
|
|
177
|
+
const address = agentAuthServer.address();
|
|
178
|
+
const baseUrl = `http://127.0.0.1:${address.port}`;
|
|
179
|
+
php7AgentAuth = await runAsync('php', ['-r', `
|
|
180
|
+
require '${root}/sdk/php7/src/HubClient.php';
|
|
181
|
+
require '${root}/sdk/php7/src/AgentAuth.php';
|
|
182
|
+
$authorizationId = '${authorizationId}';
|
|
183
|
+
$sessionId = '${sessionId}';
|
|
184
|
+
$auth = new Bailing\\Connect\\AgentAuth('${baseUrl}', 'unit-test-client-token');
|
|
185
|
+
$out = array();
|
|
186
|
+
$out['context'] = $auth->context($authorizationId);
|
|
187
|
+
$out['approve'] = $auth->approve(
|
|
188
|
+
$authorizationId,
|
|
189
|
+
array('id' => 'user-7', 'tenant' => 'tenant-3'),
|
|
190
|
+
'tenant-3:user-7',
|
|
191
|
+
array('selected' => 'staff-route')
|
|
192
|
+
);
|
|
193
|
+
$out['deny'] = $auth->deny($authorizationId);
|
|
194
|
+
$out['revoke'] = $auth->revokeSession($sessionId);
|
|
195
|
+
$out['validation'] = array();
|
|
196
|
+
$checks = array(
|
|
197
|
+
function () use ($auth) { $auth->context('not-a-uuid'); },
|
|
198
|
+
function () use ($auth, $authorizationId) { $auth->approve($authorizationId, array(), 'tenant-3:user-7', array('staff-route')); },
|
|
199
|
+
function () use ($auth, $authorizationId) { $auth->approve($authorizationId, array('id' => 'user-7'), '', array('staff-route')); },
|
|
200
|
+
function () use ($auth, $authorizationId) { $auth->approve($authorizationId, array('id' => 'user-7'), 'tenant-3:user-7', array()); }
|
|
201
|
+
);
|
|
202
|
+
foreach ($checks as $check) {
|
|
203
|
+
try {
|
|
204
|
+
$check();
|
|
205
|
+
$out['validation'][] = 'missing-error';
|
|
206
|
+
} catch (InvalidArgumentException $e) {
|
|
207
|
+
$out['validation'][] = $e->getMessage();
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
$hub = new Bailing\\Connect\\HubClient('${baseUrl}', 'unit-test-client-token');
|
|
211
|
+
try {
|
|
212
|
+
$hub->get('/redirect');
|
|
213
|
+
$out['redirect'] = 'followed';
|
|
214
|
+
} catch (RuntimeException $e) {
|
|
215
|
+
$out['redirect'] = $e->getMessage();
|
|
216
|
+
}
|
|
217
|
+
echo json_encode($out, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
|
218
|
+
`]);
|
|
219
|
+
} finally {
|
|
220
|
+
await closeServer(agentAuthServer);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
let php7AgentAuthData = null;
|
|
224
|
+
try {
|
|
225
|
+
php7AgentAuthData = JSON.parse(php7AgentAuth.stdout);
|
|
226
|
+
} catch {}
|
|
227
|
+
ok('PHP7 AgentAuth HTTP flow completes', php7AgentAuth.status === 0 && php7AgentAuthData !== null, php7AgentAuth.stderr || php7AgentAuth.stdout);
|
|
228
|
+
ok('PHP7 AgentAuth context/approve/deny/revoke responses round-trip',
|
|
229
|
+
php7AgentAuthData?.context?.requested_routes?.[0] === 'staff-route'
|
|
230
|
+
&& php7AgentAuthData?.approve?.redirect_uri === 'http://127.0.0.1/callback?code=unit-test'
|
|
231
|
+
&& php7AgentAuthData?.deny?.status === 'denied'
|
|
232
|
+
&& php7AgentAuthData?.revoke?.status === 'revoked');
|
|
233
|
+
ok('PHP7 AgentAuth validates UUID, principal, subject and route scope',
|
|
234
|
+
JSON.stringify(php7AgentAuthData?.validation) === JSON.stringify([
|
|
235
|
+
'authorizationId 必须是 UUID',
|
|
236
|
+
'principal.id 必填',
|
|
237
|
+
'onBehalfOf 必填',
|
|
238
|
+
'allowedRoutes 至少包含一条路由',
|
|
239
|
+
]));
|
|
240
|
+
ok('PHP7 AgentAuth uses the v1 paths and methods',
|
|
241
|
+
JSON.stringify(agentAuthRequests.slice(0, 4).map(({ method, url }) => [method, url])) === JSON.stringify([
|
|
242
|
+
['GET', `/agent-auth/v1/authorizations/${authorizationId}`],
|
|
243
|
+
['POST', `/agent-auth/v1/authorizations/${authorizationId}/approve`],
|
|
244
|
+
['POST', `/agent-auth/v1/authorizations/${authorizationId}/deny`],
|
|
245
|
+
['POST', `/agent-auth/v1/sessions/${sessionId}/revoke`],
|
|
246
|
+
]));
|
|
247
|
+
let approveBody = null;
|
|
248
|
+
try {
|
|
249
|
+
approveBody = JSON.parse(agentAuthRequests[1]?.body ?? '');
|
|
250
|
+
} catch {}
|
|
251
|
+
ok('PHP7 AgentAuth derives the approval wire body without client-side credentials',
|
|
252
|
+
JSON.stringify(approveBody) === JSON.stringify({
|
|
253
|
+
principal: { id: 'user-7', tenant: 'tenant-3', roles: [] },
|
|
254
|
+
on_behalf_of: 'tenant-3:user-7',
|
|
255
|
+
allowed_routes: ['staff-route'],
|
|
256
|
+
}));
|
|
257
|
+
ok('PHP7 AgentAuth keeps Client Token in the backend Authorization header',
|
|
258
|
+
agentAuthRequests.every((request) => request.authorization === 'Bearer unit-test-client-token')
|
|
259
|
+
&& agentAuthRequests.slice(1, 4).every((request) => request.contentType === 'application/json'));
|
|
260
|
+
ok('PHP7 HubClient does not follow a Bearer-authenticated redirect',
|
|
261
|
+
php7AgentAuthData?.redirect === 'HTTP 302'
|
|
262
|
+
&& !agentAuthRequests.some((request) => request.url === '/agent-auth-leak'));
|
|
99
263
|
|
|
100
264
|
console.log(`\n结果:通过 ${pass} / 失败 ${fail}`);
|
|
101
265
|
process.exit(fail ? 1 : 0);
|
|
@@ -2,7 +2,10 @@ import { execFileSync } from 'node:child_process';
|
|
|
2
2
|
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
|
|
5
|
+
import { findPublicContentDenylistMatches, loadPrivateExactTextDenylist } from './public-content-denylist.mjs';
|
|
6
|
+
|
|
5
7
|
const root = process.cwd();
|
|
8
|
+
const privateExactTextDenylist = loadPrivateExactTextDenylist({ root });
|
|
6
9
|
const requiredFiles = ['LICENSE', 'NOTICE', 'THIRD_PARTY_NOTICES.md', 'SECURITY.md', 'CONTRIBUTING.md', '.env.example', 'config.example.json'];
|
|
7
10
|
const allowedLiteralValues = new Set([
|
|
8
11
|
'demo-tool-secret-change-me',
|
|
@@ -27,7 +30,6 @@ const skipPath = (file) => (
|
|
|
27
30
|
|| file.startsWith('.git/')
|
|
28
31
|
);
|
|
29
32
|
const isTestFixture = (file) => /\.(test|spec)\.(ts|js|mjs)$/.test(file) || file.includes('/__tests__/');
|
|
30
|
-
const rx = (parts, flags = '') => new RegExp(parts.join(''), flags);
|
|
31
33
|
|
|
32
34
|
const patterns = [
|
|
33
35
|
{ name: 'private key', re: /-----BEGIN (?:RSA |DSA |EC |OPENSSH |)PRIVATE KEY-----/ },
|
|
@@ -35,8 +37,6 @@ const patterns = [
|
|
|
35
37
|
{ name: 'GitHub token', re: /\bgh[pousr]_[A-Za-z0-9_]{30,}\b/ },
|
|
36
38
|
{ name: 'AWS access key', re: /\bAKIA[0-9A-Z]{16}\b/ },
|
|
37
39
|
{ name: 'Tencent Cloud secret id', re: /\bAKID[A-Za-z0-9]{13,}\b/ },
|
|
38
|
-
{ name: 'known leaked password', re: rx(['Nie', '0712', '\\.\\.']) },
|
|
39
|
-
{ name: 'known managed MySQL host in source', re: rx(['sh-', 'cynosdb', 'mysql', '-[A-Za-z0-9.-]+', 'tencent', 'cdb\\.com']) },
|
|
40
40
|
{ name: 'legacy fixed server token fallback', re: /server(?:Token|\.token)\s*\|\|\s*['"]bailing['"]/ },
|
|
41
41
|
{ name: 'predictable Compose admin token', re: /BAILING_TOKEN:\s*\$\{BAILING_TOKEN:-[^}]+\}/ },
|
|
42
42
|
];
|
|
@@ -61,7 +61,7 @@ function scanSecretAssignments(file, text, findings) {
|
|
|
61
61
|
if (allowedLiteralValues.has(value)) continue;
|
|
62
62
|
if (/^(change-me|example|placeholder|your-|<.+>|xxx+|\*+|demo-|bailing-)/i.test(value)) continue;
|
|
63
63
|
if (file.includes('/README') || file.startsWith('docs/') || file.startsWith('sdk/')) continue;
|
|
64
|
-
findings.push({ file, name: `suspicious ${m[1]} assignment`, sample:
|
|
64
|
+
findings.push({ file, name: `suspicious ${m[1]} assignment`, sample: '[redacted]' });
|
|
65
65
|
}
|
|
66
66
|
}
|
|
67
67
|
|
|
@@ -80,7 +80,10 @@ for (const file of trackedAndUntrackedFiles()) {
|
|
|
80
80
|
for (const p of patterns) {
|
|
81
81
|
if (isTestFixture(file) && p.name === 'OpenAI API key') continue;
|
|
82
82
|
const m = text.match(p.re);
|
|
83
|
-
if (m) findings.push({ file, name: p.name, sample:
|
|
83
|
+
if (m) findings.push({ file, name: p.name, sample: '[redacted]' });
|
|
84
|
+
}
|
|
85
|
+
for (const match of findPublicContentDenylistMatches(text, privateExactTextDenylist, { generic: false })) {
|
|
86
|
+
findings.push({ file, name: match, sample: '[redacted]' });
|
|
84
87
|
}
|
|
85
88
|
scanSecretAssignments(file, text, findings);
|
|
86
89
|
}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { existsSync, readFileSync } from 'node:fs';
|
|
2
2
|
import { checkReleaseConsistency } from './check-release-consistency.mjs';
|
|
3
|
+
import { findPublicContentDenylistMatches, loadPrivateExactTextDenylist } from './public-content-denylist.mjs';
|
|
3
4
|
|
|
4
5
|
const findings = [];
|
|
6
|
+
const privateExactTextDenylist = loadPrivateExactTextDenylist();
|
|
5
7
|
|
|
6
8
|
function read(file) {
|
|
7
9
|
if (!existsSync(file)) {
|
|
@@ -65,7 +67,7 @@ for (const [file, text] of [
|
|
|
65
67
|
requireIncludes(file, text, 'BAILING_TOOL_INDEX_LOAD_TIMEOUT_MS: ${BAILING_TOOL_INDEX_LOAD_TIMEOUT_MS:-5000}');
|
|
66
68
|
requireIncludes(file, text, 'BAILING_TOOL_QUERY_EMBEDDING_TIMEOUT_MS: ${BAILING_TOOL_QUERY_EMBEDDING_TIMEOUT_MS:-15000}');
|
|
67
69
|
requireIncludes(file, text, 'BAILING_SEED_DEMO: "1"');
|
|
68
|
-
|
|
70
|
+
for (const match of findPublicContentDenylistMatches(text, privateExactTextDenylist)) findings.push(`${file}: ${match}`);
|
|
69
71
|
}
|
|
70
72
|
|
|
71
73
|
if (stableVersion && !composeImages.includes(`bailinghub:${stableVersion}`)) {
|
|
@@ -3,9 +3,12 @@ import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
|
3
3
|
import { tmpdir } from 'node:os';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
|
|
6
|
+
import { findPublicContentDenylistMatches, loadPrivateExactTextDenylist } from './public-content-denylist.mjs';
|
|
7
|
+
|
|
6
8
|
const root = process.cwd();
|
|
7
9
|
const exportDir = join(root, '.oss-dist', 'bailinghub');
|
|
8
10
|
const expectedRepo = 'git+https://github.com/bailinghub/bailinghub.git';
|
|
11
|
+
const privateExactTextDenylist = loadPrivateExactTextDenylist({ root });
|
|
9
12
|
|
|
10
13
|
function run(cmd, args, cwd = root) {
|
|
11
14
|
console.log(`> ${[cmd, ...args].join(' ')}`);
|
|
@@ -124,7 +127,7 @@ const requiredFiles = [
|
|
|
124
127
|
'docs/RELEASE_NOTES_v0.3.2.md',
|
|
125
128
|
'docs/RELEASE_NOTES_v0.3.3.md',
|
|
126
129
|
'docs/RELEASE_NOTES_v0.3.4.md',
|
|
127
|
-
'docs/RELEASE_NOTES_v0.
|
|
130
|
+
'docs/RELEASE_NOTES_v0.5.0.md',
|
|
128
131
|
'docs/CHANGELOG.md',
|
|
129
132
|
];
|
|
130
133
|
for (const file of requiredFiles) requireFile(file);
|
|
@@ -173,21 +176,13 @@ try {
|
|
|
173
176
|
assertNotTracked(files, (file) => file.includes('.bak.'), 'GitHub rehearsal must not track backup files');
|
|
174
177
|
assertNoInstallerEnvPrefix(files);
|
|
175
178
|
|
|
176
|
-
const bannedParts = [
|
|
177
|
-
String.raw`/Users/` + 'macmini',
|
|
178
|
-
'项目' + String.raw`/www`,
|
|
179
|
-
'Nie' + '0712',
|
|
180
|
-
'github' + '_pat_',
|
|
181
|
-
String.raw`pt-[A-Za-z0-9_-]{20,}`,
|
|
182
|
-
'sh-' + 'cynosdb' + 'mysql' + String.raw`-[A-Za-z0-9.-]+` + 'tencent' + String.raw`cdb\.com`,
|
|
183
|
-
'bnopen' + String.raw`\.cn`,
|
|
184
|
-
];
|
|
185
|
-
const bannedText = new RegExp(`(${bannedParts.join('|')})`);
|
|
186
179
|
const textFiles = files.filter((file) => /\.(?:md|ts|tsx|js|mjs|json|sql|php|py|vue|html|css|sh|yml|yaml|txt|gitignore|npmignore|dockerignore)$/.test(file));
|
|
187
180
|
const findings = [];
|
|
188
181
|
for (const file of textFiles) {
|
|
189
182
|
const text = output('git', ['show', `:${file}`], repoDir);
|
|
190
|
-
|
|
183
|
+
for (const match of findPublicContentDenylistMatches(text, privateExactTextDenylist)) {
|
|
184
|
+
findings.push(`${file}: ${match}`);
|
|
185
|
+
}
|
|
191
186
|
}
|
|
192
187
|
if (findings.length) {
|
|
193
188
|
throw new Error(`GitHub rehearsal found private text in: ${findings.slice(0, 20).join(', ')}`);
|
|
@@ -3,8 +3,11 @@ import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
|
3
3
|
import { tmpdir } from 'node:os';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
|
|
6
|
+
import { findPublicContentDenylistMatches, loadPrivateExactTextDenylist } from './public-content-denylist.mjs';
|
|
7
|
+
|
|
6
8
|
const root = process.cwd();
|
|
7
9
|
const exportDir = join(root, '.oss-dist', 'bailinghub');
|
|
10
|
+
const privateExactTextDenylist = loadPrivateExactTextDenylist({ root });
|
|
8
11
|
|
|
9
12
|
function run(cmd, args, cwd = root) {
|
|
10
13
|
console.log(`> ${[cmd, ...args].join(' ')}`);
|
|
@@ -15,8 +18,6 @@ function output(cmd, args, cwd = root) {
|
|
|
15
18
|
return execFileSync(cmd, args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
|
|
16
19
|
}
|
|
17
20
|
|
|
18
|
-
const rx = (parts, flags = '') => new RegExp(parts.join(''), flags);
|
|
19
|
-
|
|
20
21
|
function verifyGitBoundary() {
|
|
21
22
|
const rehearsalRoot = mkdtempSync(join(tmpdir(), 'bailinghub-oss-git-'));
|
|
22
23
|
const repoDir = join(rehearsalRoot, 'repo');
|
|
@@ -75,15 +76,6 @@ function verifyGitBoundary() {
|
|
|
75
76
|
const allowedHiddenRoots = new Set(['.github']);
|
|
76
77
|
const allowedHiddenFiles = new Set(['.dockerignore', '.env.example', '.gitignore', '.npmignore']);
|
|
77
78
|
const forbiddenFiles = new Set(['config.json', '.env', 'targets.local.json']);
|
|
78
|
-
const bannedText = rx([
|
|
79
|
-
'/Users/', 'macmini',
|
|
80
|
-
'|', '项目', '\\/www',
|
|
81
|
-
'|', 'Nie', '0712',
|
|
82
|
-
'|', 'github', '_pat', '_',
|
|
83
|
-
'|', 'pt', '-[A-Za-z0-9_-]{20,}',
|
|
84
|
-
'|', 'bnopen', '\\.cn',
|
|
85
|
-
'|', 'sh-', 'cynosdb', 'mysql', '-[A-Za-z0-9.-]+', 'tencent', 'cdb\\.com',
|
|
86
|
-
]);
|
|
87
79
|
const forbiddenPublicWording = new RegExp([
|
|
88
80
|
'商业' + '版',
|
|
89
81
|
'商业' + '扩展',
|
|
@@ -118,7 +110,9 @@ function verifyGitBoundary() {
|
|
|
118
110
|
const textFiles = files.filter((file) => /\.(?:md|ts|tsx|js|mjs|json|sql|php|py|vue|html|css|sh|yml|yaml|txt|gitignore|npmignore|dockerignore)$/.test(file));
|
|
119
111
|
for (const file of textFiles) {
|
|
120
112
|
const text = output('git', ['show', `:${file}`], repoDir);
|
|
121
|
-
|
|
113
|
+
for (const match of findPublicContentDenylistMatches(text, privateExactTextDenylist)) {
|
|
114
|
+
findings.push(`${file}: ${match} in git boundary`);
|
|
115
|
+
}
|
|
122
116
|
if (file !== 'LICENSE' && forbiddenPublicWording.test(text)) {
|
|
123
117
|
findings.push(`${file}: use neutral public wording for private extension boundaries`);
|
|
124
118
|
}
|
package/sdk/php/README.md
CHANGED
|
@@ -20,7 +20,7 @@ curl -O https://<中枢域名>/connect/bailing-connect-php.tgz && tar -xzf baili
|
|
|
20
20
|
}
|
|
21
21
|
```
|
|
22
22
|
|
|
23
|
-
或 ③ 直接拷贝 `src/`
|
|
23
|
+
或 ③ 直接拷贝 `src/` 目录进项目。零依赖,怎么引都行;请保留完整目录结构,避免可选模块 class not found。
|
|
24
24
|
|
|
25
25
|
## 第一步:标注解
|
|
26
26
|
|
|
@@ -195,6 +195,32 @@ $result = $hub->getJob($job['job_id']);
|
|
|
195
195
|
$hub->send('notice_1001', 'team-im', 'user_001', '任务已完成');
|
|
196
196
|
```
|
|
197
197
|
|
|
198
|
+
## 附:本地 Agent 网页授权(可选)
|
|
199
|
+
|
|
200
|
+
`AgentAuth` 是现有 SDK 的可选模块,不是第二套 SDK。业务网页先用自己的登录态确定当前操作人,后端再用接入方 Client Token 调中枢:
|
|
201
|
+
|
|
202
|
+
完整的组件关系、配置归属与非 PHP HTTP 契约分别见
|
|
203
|
+
[Agent Client v1 接入指南](../../docs/AGENT_CLIENT_QUICKSTART.md) 和
|
|
204
|
+
[Agent Auth v1](../../docs/AGENT_AUTH_API.md)。
|
|
205
|
+
|
|
206
|
+
```php
|
|
207
|
+
$agentAuth = new \Bailing\Connect\AgentAuth('https://hub.example.com', $clientToken);
|
|
208
|
+
$context = $agentAuth->context($authorizationId);
|
|
209
|
+
|
|
210
|
+
$result = $agentAuth->approve(
|
|
211
|
+
$authorizationId,
|
|
212
|
+
['id' => (string) $user->id, 'tenant' => (string) $tenantId, 'roles' => $user->roles],
|
|
213
|
+
"tenant_{$tenantId}:user_{$user->id}",
|
|
214
|
+
$context['requested_routes']
|
|
215
|
+
);
|
|
216
|
+
|
|
217
|
+
// 浏览器跳转 $result['redirect_uri'] 完成 loopback 回调。
|
|
218
|
+
// 用户取消时:$agentAuth->deny($authorizationId);
|
|
219
|
+
// 员工离职/设备丢失:$agentAuth->revokeSession($sessionId);
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
`principal` 和 `on_behalf_of` 必须由业务后端从当前登录态生成,不得从前端表单原样透传。该协议只绑定业务身份、路由与设备会话,不承载套餐、付费或权益字段。
|
|
223
|
+
|
|
198
224
|
## CI 集成
|
|
199
225
|
|
|
200
226
|
```bash
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
declare(strict_types=1);
|
|
4
|
+
|
|
5
|
+
namespace Bailing\Connect;
|
|
6
|
+
|
|
7
|
+
use InvalidArgumentException;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 业务后端对接 BailingHub Agent Auth v1 的薄客户端。
|
|
11
|
+
*
|
|
12
|
+
* 使用现有接入方 Client Token 读取授权上下文,并在业务系统
|
|
13
|
+
* 已完成登录和权限判定后批准/拒绝。不签发套餐、付费或权益数据。
|
|
14
|
+
*/
|
|
15
|
+
final class AgentAuth
|
|
16
|
+
{
|
|
17
|
+
private HubClient $hub;
|
|
18
|
+
|
|
19
|
+
public function __construct(string $baseUrl, string $clientToken, int $timeoutSeconds = 8)
|
|
20
|
+
{
|
|
21
|
+
$this->hub = new HubClient($baseUrl, $clientToken, $timeoutSeconds);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** @return array<string,mixed> */
|
|
25
|
+
public function context(string $authorizationId): array
|
|
26
|
+
{
|
|
27
|
+
self::assertId($authorizationId, 'authorizationId');
|
|
28
|
+
return $this->hub->get('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @param array{id:string,tenant?:string,roles?:array<int,string>,audience?:string,channel?:string} $principal
|
|
33
|
+
* @param array<int,string> $allowedRoutes
|
|
34
|
+
* @return array<string,mixed>
|
|
35
|
+
*/
|
|
36
|
+
public function approve(string $authorizationId, array $principal, string $onBehalfOf, array $allowedRoutes): array
|
|
37
|
+
{
|
|
38
|
+
self::assertId($authorizationId, 'authorizationId');
|
|
39
|
+
if (!isset($principal['id']) || trim((string) $principal['id']) === '') {
|
|
40
|
+
throw new InvalidArgumentException('principal.id 必填');
|
|
41
|
+
}
|
|
42
|
+
if ($onBehalfOf === '') {
|
|
43
|
+
throw new InvalidArgumentException('onBehalfOf 必填');
|
|
44
|
+
}
|
|
45
|
+
if ($allowedRoutes === []) {
|
|
46
|
+
throw new InvalidArgumentException('allowedRoutes 至少包含一条路由');
|
|
47
|
+
}
|
|
48
|
+
if (!isset($principal['roles'])) {
|
|
49
|
+
$principal['roles'] = [];
|
|
50
|
+
}
|
|
51
|
+
return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/approve', [
|
|
52
|
+
'principal' => $principal,
|
|
53
|
+
'on_behalf_of' => $onBehalfOf,
|
|
54
|
+
'allowed_routes' => array_values($allowedRoutes),
|
|
55
|
+
]);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** @return array<string,mixed> */
|
|
59
|
+
public function deny(string $authorizationId): array
|
|
60
|
+
{
|
|
61
|
+
self::assertId($authorizationId, 'authorizationId');
|
|
62
|
+
return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/deny', []);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** @return array<string,mixed> */
|
|
66
|
+
public function revokeSession(string $sessionId): array
|
|
67
|
+
{
|
|
68
|
+
self::assertId($sessionId, 'sessionId');
|
|
69
|
+
return $this->hub->post('/agent-auth/v1/sessions/' . rawurlencode($sessionId) . '/revoke', []);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private static function assertId(string $value, string $name): void
|
|
73
|
+
{
|
|
74
|
+
if (!preg_match('/^[0-9a-f-]{36}$/i', $value)) {
|
|
75
|
+
throw new InvalidArgumentException($name . ' 必须是 UUID');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -98,6 +98,9 @@ final class HubClient
|
|
|
98
98
|
'header' => implode("\r\n", $headers),
|
|
99
99
|
'timeout' => $this->timeoutSeconds,
|
|
100
100
|
'ignore_errors' => true,
|
|
101
|
+
// Bearer 凭证绝不跟随重定向,避免被跨主机 30x 带走。
|
|
102
|
+
'follow_location' => 0,
|
|
103
|
+
'max_redirects' => 0,
|
|
101
104
|
];
|
|
102
105
|
if ($body !== null) {
|
|
103
106
|
$http['content'] = $content;
|
package/sdk/php7/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
和 8.x 注解版**功能完全等价**,区别只在「怎么声明工具」:8.x 用 `#[AiTool]` 属性注解(PHP 8.0+ 语法),本版用 **fluent builder**(纯 PHP,**PHP ≥ 7.3** 即可),产出的 spec 与注解版**逐字段一致**。
|
|
4
4
|
|
|
5
5
|
> 用哪个版本:业务跑 **PHP 8.0+** 用注解版(`sdk/php`,更简洁);跑 **PHP 7.3 / 7.4** 用本版。**不要为了对接去迁 PHP 版本**。
|
|
6
|
-
> 验签 `Verify`、票据 `Ticket`、spec 托管 `SpecServer`
|
|
6
|
+
> 验签 `Verify`、票据 `Ticket`、spec 托管 `SpecServer`、中枢调用 `HubClient` 和本地 Agent 授权 `AgentAuth` 两版 API 与语义完全相同。
|
|
7
7
|
|
|
8
8
|
零依赖。能力声明遵循 ACC,验签与中枢接入约定见 `docs/CONTRACT.md §2.4`。
|
|
9
9
|
|
|
@@ -22,7 +22,7 @@ curl -O https://<中枢域名>/connect/bailing-connect-php7.tgz && tar -xzf bail
|
|
|
22
22
|
}
|
|
23
23
|
```
|
|
24
24
|
|
|
25
|
-
或 ③ 直接拷贝 `src/` 目录进项目——共 **
|
|
25
|
+
或 ③ 直接拷贝 `src/` 目录进项目——共 **7 个文件**(`ToolSpec`/`ToolDef`/`Verify`/`Ticket`/`SpecServer`/`HubClient`/`AgentAuth`)。零依赖,怎么引都行。命名空间同为 `Bailing\Connect`。
|
|
26
26
|
|
|
27
27
|
## 第一步:声明工具(builder,不动你的控制器)
|
|
28
28
|
|
|
@@ -185,6 +185,36 @@ $result = $hub->getJob($job['job_id']);
|
|
|
185
185
|
$hub->send('notice_1001', 'team-im', 'user_001', '任务已完成');
|
|
186
186
|
```
|
|
187
187
|
|
|
188
|
+
## 本地 Agent 网页授权(可选)
|
|
189
|
+
|
|
190
|
+
`AgentAuth` 是现有 PHP 7.3 SDK 的可选模块,不是第二套 SDK。业务网页先用自己的登录态确定当前操作人,后端再用接入方 Client Token 调中枢:
|
|
191
|
+
|
|
192
|
+
```php
|
|
193
|
+
use Bailing\Connect\AgentAuth;
|
|
194
|
+
|
|
195
|
+
$agentAuth = new AgentAuth('https://hub.example.com', $clientToken);
|
|
196
|
+
$context = $agentAuth->context($authorizationId);
|
|
197
|
+
|
|
198
|
+
$result = $agentAuth->approve(
|
|
199
|
+
$authorizationId,
|
|
200
|
+
array(
|
|
201
|
+
'id' => (string) $user->id,
|
|
202
|
+
'tenant' => (string) $tenantId,
|
|
203
|
+
'roles' => $user->roles,
|
|
204
|
+
),
|
|
205
|
+
'tenant_' . $tenantId . ':user_' . $user->id,
|
|
206
|
+
$context['requested_routes']
|
|
207
|
+
);
|
|
208
|
+
|
|
209
|
+
// 浏览器只跳转 $result['redirect_uri'] 完成 loopback 回调。
|
|
210
|
+
// 用户取消时:$agentAuth->deny($authorizationId);
|
|
211
|
+
// 员工离职/设备丢失:$agentAuth->revokeSession($sessionId);
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
`principal`、`on_behalf_of` 和 `allowed_routes` 必须由业务后端根据当前登录态与自身权限生成,不得从前端表单原样透传。Client Token 只存业务服务端,不得写进网页 JavaScript、URL、本地 Agent 或插件配置。授权协议只绑定业务身份、路由和设备会话,不承载套餐、付费或权益字段。
|
|
215
|
+
|
|
216
|
+
完整关系与 HTTP 契约见中枢文档 `docs/AGENT_CLIENT_QUICKSTART.md` 和 `docs/AGENT_AUTH_API.md`。
|
|
217
|
+
|
|
188
218
|
## 范例
|
|
189
219
|
|
|
190
220
|
- `examples/build-spec.php`:完整 builder 范例(覆盖全部字段;与 8.x 版同源,跑同一个跨语言契约测试)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
namespace Bailing\Connect;
|
|
4
|
+
|
|
5
|
+
use InvalidArgumentException;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* 业务后端对接 BailingHub Agent Auth v1 的薄客户端。
|
|
9
|
+
*
|
|
10
|
+
* 使用现有接入方 Client Token 读取授权上下文,并在业务系统
|
|
11
|
+
* 已完成登录和权限判定后批准/拒绝。不签发套餐、付费或权益数据。
|
|
12
|
+
* PHP 7.3 兼容版,语义与 8.x SDK 的 AgentAuth 一致。
|
|
13
|
+
*/
|
|
14
|
+
final class AgentAuth
|
|
15
|
+
{
|
|
16
|
+
private $hub;
|
|
17
|
+
|
|
18
|
+
public function __construct($baseUrl, $clientToken, $timeoutSeconds = 8)
|
|
19
|
+
{
|
|
20
|
+
$this->hub = new HubClient($baseUrl, $clientToken, $timeoutSeconds);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** @return array */
|
|
24
|
+
public function context($authorizationId)
|
|
25
|
+
{
|
|
26
|
+
self::assertId($authorizationId, 'authorizationId');
|
|
27
|
+
return $this->hub->get('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param array $principal 业务后端从当前登录态推导的主体,必须包含 id
|
|
32
|
+
* @param array $allowedRoutes 本次授权允许的路由标识
|
|
33
|
+
* @return array
|
|
34
|
+
*/
|
|
35
|
+
public function approve($authorizationId, array $principal, $onBehalfOf, array $allowedRoutes)
|
|
36
|
+
{
|
|
37
|
+
self::assertId($authorizationId, 'authorizationId');
|
|
38
|
+
if (!isset($principal['id']) || trim((string) $principal['id']) === '') {
|
|
39
|
+
throw new InvalidArgumentException('principal.id 必填');
|
|
40
|
+
}
|
|
41
|
+
if ($onBehalfOf === '') {
|
|
42
|
+
throw new InvalidArgumentException('onBehalfOf 必填');
|
|
43
|
+
}
|
|
44
|
+
if ($allowedRoutes === array()) {
|
|
45
|
+
throw new InvalidArgumentException('allowedRoutes 至少包含一条路由');
|
|
46
|
+
}
|
|
47
|
+
if (!isset($principal['roles'])) {
|
|
48
|
+
$principal['roles'] = array();
|
|
49
|
+
}
|
|
50
|
+
return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/approve', array(
|
|
51
|
+
'principal' => $principal,
|
|
52
|
+
'on_behalf_of' => $onBehalfOf,
|
|
53
|
+
'allowed_routes' => array_values($allowedRoutes),
|
|
54
|
+
));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** @return array */
|
|
58
|
+
public function deny($authorizationId)
|
|
59
|
+
{
|
|
60
|
+
self::assertId($authorizationId, 'authorizationId');
|
|
61
|
+
return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/deny', array());
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** @return array */
|
|
65
|
+
public function revokeSession($sessionId)
|
|
66
|
+
{
|
|
67
|
+
self::assertId($sessionId, 'sessionId');
|
|
68
|
+
return $this->hub->post('/agent-auth/v1/sessions/' . rawurlencode($sessionId) . '/revoke', array());
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
private static function assertId($value, $name)
|
|
72
|
+
{
|
|
73
|
+
if (!is_string($value) || !preg_match('/^[0-9a-f-]{36}$/i', $value)) {
|
|
74
|
+
throw new InvalidArgumentException($name . ' 必须是 UUID');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -85,6 +85,9 @@ final class HubClient
|
|
|
85
85
|
'header' => implode("\r\n", $headers),
|
|
86
86
|
'timeout' => $this->timeoutSeconds,
|
|
87
87
|
'ignore_errors' => true,
|
|
88
|
+
// Bearer 凭证绝不跟随重定向,避免被跨主机 30x 带走。
|
|
89
|
+
'follow_location' => 0,
|
|
90
|
+
'max_redirects' => 0,
|
|
88
91
|
);
|
|
89
92
|
if ($body !== null) {
|
|
90
93
|
$http['content'] = $content;
|