bailinghub 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/README.en.md +11 -7
  2. package/README.md +10 -7
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/AGENT_AUTH_API.en.md +112 -1
  5. package/docs/AGENT_AUTH_API.md +99 -1
  6. package/docs/AGENT_CLIENT_QUICKSTART.en.md +32 -5
  7. package/docs/AGENT_CLIENT_QUICKSTART.md +27 -4
  8. package/docs/AGENT_CLIENT_RUNTIME_API.md +4 -1
  9. package/docs/AGENT_CONVERSATION_AUDIT.en.md +109 -4
  10. package/docs/AGENT_CONVERSATION_AUDIT.md +84 -3
  11. package/docs/AGENT_SUBJECT_DISPLAY.en.md +95 -0
  12. package/docs/AGENT_SUBJECT_DISPLAY.md +95 -0
  13. package/docs/AGENT_SYSTEM_INFO.en.md +99 -0
  14. package/docs/AGENT_SYSTEM_INFO.md +97 -0
  15. package/docs/CHANGELOG.en.md +25 -2
  16. package/docs/CHANGELOG.md +24 -1
  17. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  18. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  19. package/docs/LOCAL_AGENT_SETUP.en.md +116 -0
  20. package/docs/LOCAL_AGENT_SETUP.md +116 -0
  21. package/docs/README.en.md +8 -0
  22. package/docs/README.md +8 -0
  23. package/docs/RELEASE_NOTES_NEXT.en.md +3 -0
  24. package/docs/RELEASE_NOTES_NEXT.md +3 -0
  25. package/docs/RELEASE_NOTES_v0.6.0.en.md +4 -2
  26. package/docs/RELEASE_NOTES_v0.6.0.md +2 -0
  27. package/docs/RELEASE_NOTES_v0.6.1.en.md +53 -0
  28. package/docs/RELEASE_NOTES_v0.6.1.md +53 -0
  29. package/docs/RELEASE_NOTES_v0.7.0.en.md +116 -0
  30. package/docs/RELEASE_NOTES_v0.7.0.md +116 -0
  31. package/docs/SDK.en.md +31 -0
  32. package/docs/user-guide/conversations.en.md +4 -2
  33. package/docs/user-guide/conversations.md +4 -2
  34. package/package.json +1 -1
  35. package/schemas/config/route.schema.json +15 -2
  36. package/scripts/check-doc-links.mjs +2 -0
  37. package/scripts/check-image-tags.sh +1 -1
  38. package/scripts/check-release-consistency.test.mjs +2 -2
  39. package/scripts/install.sh +1 -1
  40. package/scripts/publish-images.sh +1 -1
  41. package/scripts/release-audit.mjs +2 -0
  42. package/scripts/sdk-agent-auth-lifecycle-check.mjs +178 -0
  43. package/scripts/sdk-runtime-test.mjs +5 -2
  44. package/scripts/verify-github-repo.mjs +2 -0
  45. package/sdk/php/README.md +29 -0
  46. package/sdk/php/src/AgentAuth.php +100 -4
  47. package/sdk/php/src/HubClient.php +2 -1
  48. package/sdk/php7/README.md +31 -0
  49. package/sdk/php7/src/AgentAuth.php +99 -4
  50. package/sdk/php7/src/HubClient.php +2 -1
  51. package/sql/058_agent_conversation_member_bindings.sql +9 -0
  52. package/sql/059_agent_subject_display.sql +5 -0
  53. package/sql/README.en.md +15 -0
  54. package/sql/README.md +25 -0
  55. package/src/app/agent-conversation-audit.ts +20 -0
  56. package/src/app/agent-system-info.ts +41 -0
  57. package/src/app/agent-tool-invocations.ts +16 -4
  58. package/src/core/config/agent-setup.ts +37 -0
  59. package/src/core/config/client-agent-setup.ts +25 -0
  60. package/src/core/config/config-schema.test.ts +11 -0
  61. package/src/core/config/route-config.test.ts +28 -0
  62. package/src/core/config/route-config.ts +43 -4
  63. package/src/core/contracts/agent-subject-display.test.ts +19 -0
  64. package/src/core/contracts/agent-subject-display.ts +36 -0
  65. package/src/core/contracts/types.ts +15 -0
  66. package/src/core/runtime/agent-conversation-audit.test.ts +19 -1
  67. package/src/core/runtime/agent-conversation-audit.ts +39 -0
  68. package/src/infrastructure/config/config-agent-auth-business-sessions.test.ts +120 -0
  69. package/src/infrastructure/config/config-agent-auth-lifecycle-race.test.ts +152 -0
  70. package/src/infrastructure/config/config-agent-auth-repository.test.ts +2 -0
  71. package/src/infrastructure/config/config-agent-auth-repository.ts +208 -18
  72. package/src/infrastructure/config/config-agent-conversation-audit-cross-binding.test.ts +120 -0
  73. package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +117 -23
  74. package/src/infrastructure/config/config-agent-subject-display.test.ts +103 -0
  75. package/src/infrastructure/config/config-client-repository.ts +21 -0
  76. package/src/infrastructure/config/config-route-agent-setup.test.ts +59 -0
  77. package/src/infrastructure/config/config-route-repository.ts +24 -0
  78. package/src/infrastructure/config/configstore.ts +7 -3
  79. package/src/infrastructure/schema/core-schema-migrator.test.ts +90 -0
  80. package/src/routes/admin-access.ts +37 -0
  81. package/src/routes/admin-agent-clients.ts +11 -0
  82. package/src/routes/admin-agent-setup.test.ts +130 -0
  83. package/src/routes/admin-agent-setup.ts +68 -0
  84. package/src/routes/admin-client-agent-setup.test.ts +93 -0
  85. package/src/routes/admin-dispatch-config.ts +2 -0
  86. package/src/routes/agent-api.ts +7 -0
  87. package/src/routes/agent-auth-lifecycle-http.test.ts +177 -0
  88. package/src/routes/agent-auth-lifecycle.test.ts +193 -0
  89. package/src/routes/agent-auth.test.ts +1 -1
  90. package/src/routes/agent-auth.ts +206 -16
  91. package/src/routes/agent-conversation-audit-cross-binding-http.test.ts +122 -0
  92. package/src/routes/agent-conversation-audit.ts +8 -2
  93. package/src/routes/agent-subject-display-http.test.ts +145 -0
  94. package/src/routes/agent-system-info.test.ts +132 -0
  95. package/src/test-support/agent-auth-business-query-fixture.ts +43 -0
  96. package/src/test-support/agent-auth-lifecycle-fixture.ts +288 -0
  97. package/src/test-support/agent-conversation-audit-fixture.ts +30 -6
  98. package/src/test-support/agent-conversation-audit-http-fixture.ts +84 -0
  99. package/web/connect/bailing-connect-php.tgz +0 -0
  100. package/web/connect/bailing-connect-php7.tgz +0 -0
  101. package/web/console/assets/{Accounts-Ca_VnSu9.js → Accounts-ChL9k-XA.js} +1 -1
  102. package/web/console/assets/AgentClients-Bs7UgVDj.js +1 -0
  103. package/web/console/assets/AgentClients-DkgPTEbq.css +1 -0
  104. package/web/console/assets/{Approvals-CMvPWacY.js → Approvals-Bs6FGbp2.js} +1 -1
  105. package/web/console/assets/{Audit-CIRqOCnL.js → Audit-4WWYhkFM.js} +1 -1
  106. package/web/console/assets/{BrandLockup-BrytmTTH.js → BrandLockup-D2GhCipL.js} +1 -1
  107. package/web/console/assets/{Channels-CApxH2TB.js → Channels-CmoGpiCJ.js} +1 -1
  108. package/web/console/assets/{ChatEntries-CJon3bWJ.js → ChatEntries-BFRMtwta.js} +1 -1
  109. package/web/console/assets/Clients-CSHIsaWU.css +1 -0
  110. package/web/console/assets/Clients-DGkkSXyA.js +3 -0
  111. package/web/console/assets/{Cost-BbhlQFP8.js → Cost-BmGt0MfS.js} +1 -1
  112. package/web/console/assets/{Credentials-kqr1W0K7.js → Credentials-CR-sYINT.js} +1 -1
  113. package/web/console/assets/{Diagnostics-Kljt9XTH.js → Diagnostics-DAPbKSJp.js} +1 -1
  114. package/web/console/assets/{Executors-DnsB-Xz4.js → Executors-CgpiT3o8.js} +1 -1
  115. package/web/console/assets/{Kb-DLZSAFWP.js → Kb-Cm9dVSQw.js} +1 -1
  116. package/web/console/assets/{Login-DiTjPWmN.js → Login-CyUcsTZ_.js} +1 -1
  117. package/web/console/assets/{Projects-CXcVCgCD.js → Projects-DldFPgWg.js} +1 -1
  118. package/web/console/assets/Routes-DkMIjMQA.css +1 -0
  119. package/web/console/assets/Routes-DubfjlBD.js +124 -0
  120. package/web/console/assets/Runs-1hxgkuR4.js +3 -0
  121. package/web/console/assets/Runs-CvGTV8I-.css +1 -0
  122. package/web/console/assets/{Setup-FqoCKmfZ.js → Setup-DBLOnI2_.js} +1 -1
  123. package/web/console/assets/{Shell-BEqpONiy.js → Shell-gJ5Vz_E7.js} +1 -1
  124. package/web/console/assets/{StorageBuckets-CkORbYXY.js → StorageBuckets-DkDW16tj.js} +1 -1
  125. package/web/console/assets/{SystemSettings-gTQAazu7.js → SystemSettings-cDkudo2y.js} +1 -1
  126. package/web/console/assets/{SystemStatus-DAmUUNqO.js → SystemStatus-DZd6s8OX.js} +1 -1
  127. package/web/console/assets/{Targets-CZmDcjsE.js → Targets-DYNGq1NU.js} +1 -1
  128. package/web/console/assets/{Tools-CIHInlHL.js → Tools-DpWM59vV.js} +1 -1
  129. package/web/console/assets/{index-BkLbd7Cc.js → index-DGqs28gI.js} +2 -2
  130. package/web/console/assets/{request-r7GHVJzw.js → request-B7MLvOqo.js} +1 -1
  131. package/web/console/assets/{schema-BVn_hB7M.js → schema-CMuwjYdJ.js} +1 -1
  132. package/web/console/index.html +1 -1
  133. package/web-admin/scripts/subject-display-ui.mjs +78 -0
  134. package/web-admin/src/components/AgentSetupPanel.vue +262 -0
  135. package/web-admin/src/components/ClientConversations.vue +21 -4
  136. package/web-admin/src/components/conversation-audit.ts +20 -0
  137. package/web-admin/src/pages/AgentClients.vue +97 -23
  138. package/web-admin/src/pages/Clients.vue +4 -1
  139. package/web-admin/src/pages/Routes.vue +10 -1
  140. package/web-admin/tests/conversation-audit.fixture.mjs +13 -10
  141. package/web-admin/tests/conversation-audit.test.mjs +63 -1
  142. package/web/console/assets/AgentClients-BPIvlLYY.js +0 -1
  143. package/web/console/assets/AgentClients-DsWADpzr.css +0 -1
  144. package/web/console/assets/Clients-BSA1rlTB.js +0 -3
  145. package/web/console/assets/Clients-CNIVs7Qn.css +0 -1
  146. package/web/console/assets/Routes-CXGl9SMM.css +0 -1
  147. package/web/console/assets/Routes-DN9_d9Po.js +0 -124
  148. package/web/console/assets/Runs-Cwbe6thL.js +0 -3
  149. package/web/console/assets/Runs-D8UmjP5G.css +0 -1
@@ -0,0 +1,178 @@
1
+ import { createServer } from 'node:http';
2
+
3
+ // Invoked by sdk-runtime-test.mjs so lifecycle checks share its runtime matrix.
4
+ export async function checkAgentAuthLifecycle({ root, runAsync, ok, closeServer }) {
5
+ const authorizationId = '11111111-1111-4111-8111-111111111111';
6
+ const unmappedId = '33333333-3333-4333-8333-333333333333';
7
+ const sessionId = '22222222-2222-4222-8222-222222222222';
8
+ const session = { session_id: sessionId, state: 'revoked', expires_at: '2030-02-01T00:00:00.000Z', revoked_at: '2030-01-02T00:00:00.000Z' };
9
+ const item = {
10
+ ...session, authorization_id: authorizationId, client_app_id: 'merchant-agent',
11
+ device_label: 'Test device', principal: { id: '用户 +/?&=😀', tenant: '租户&=' },
12
+ on_behalf_of: 'tenant:user +/?&=😀', allowed_routes: ['staff-route'],
13
+ created_at: '2030-01-01T00:00:00.000Z', last_seen_at: '2030-01-01T01:00:00.000Z',
14
+ };
15
+ const filters = {
16
+ authorization_id: authorizationId, on_behalf_of: item.on_behalf_of,
17
+ principal_id: item.principal.id, tenant: item.principal.tenant,
18
+ state: 'revoked', limit: 100, cursor: 'next_page-1',
19
+ };
20
+ const invalid = [
21
+ { unknown: 'field' }, { client_app_id: 'other-app' }, { 0: 'active' },
22
+ { authorization_id: null }, { authorization_id: '-'.repeat(36) },
23
+ { authorization_id: '11111111-1111-0111-8111-111111111111' },
24
+ { authorization_id: '11111111-1111-4111-0111-111111111111' },
25
+ { on_behalf_of: '' }, { on_behalf_of: 'x'.repeat(192) }, { on_behalf_of: [] },
26
+ { principal_id: 'u' }, { principal_id: '', tenant: '' },
27
+ { principal_id: 'u'.repeat(129), tenant: '' },
28
+ { tenant: null }, { tenant: 't'.repeat(129) },
29
+ { on_behalf_of: ' user' }, { tenant: 'tenant ' }, { tenant: '\uFEFFtenant' },
30
+ { tenant: 'a\u0000b' }, { tenant: 'a\u007fb' },
31
+ { tenant: '😀'.repeat(65) }, { state: 'all' }, { state: [] },
32
+ { limit: 0 }, { limit: 101 }, { limit: '20' }, { limit: 1.5 }, { limit: true },
33
+ { cursor: '' }, { cursor: null }, { cursor: 'with=' }, { cursor: 'with+' },
34
+ { cursor: 'with/' }, { cursor: 'next\n' }, { cursor: 'a'.repeat(2049) },
35
+ ];
36
+ const invalidDisplays = [
37
+ {}, { name: '' }, { name: ' ' }, { name: 42 }, { name: 'a', scope: '*' },
38
+ { name: 'a'.repeat(121) }, { name: '😀'.repeat(61) }, { name: 'a\nb' },
39
+ { name: '\ta' }, { name: 'a\u007f' }, { name: 'a\u0085' }, { name: 'a\u2028b' },
40
+ { name: 'a\u2029b' }, [], 'Account A',
41
+ ];
42
+ const requests = [];
43
+ const server = createServer(async (req, res) => {
44
+ let body = '';
45
+ for await (const chunk of req) body += chunk;
46
+ requests.push({ method: req.method, url: req.url, body, headers: req.headers });
47
+ res.setHeader('Content-Type', 'application/json');
48
+ const url = new URL(req.url, 'http://fixture.invalid');
49
+ if (url.pathname === `/agent-auth/v1/authorizations/${authorizationId}`) {
50
+ res.end(JSON.stringify({ status: 'consumed', requested_routes: ['staff-route'], session }));
51
+ } else if (url.pathname === `/agent-auth/v1/authorizations/${unmappedId}`) {
52
+ res.end(JSON.stringify({ status: 'consumed', requested_routes: ['staff-route'], session: null }));
53
+ } else if (url.pathname === '/agent-auth/v1/sessions') {
54
+ res.end(JSON.stringify({ list: [item], next_cursor: url.search ? null : 'next_page-1' }));
55
+ } else if (url.pathname === `/agent-auth/v1/authorizations/${authorizationId}/revoke`) {
56
+ res.end(JSON.stringify({ authorization_id: authorizationId, revoked: true, session_id: sessionId }));
57
+ } else if (url.pathname === `/agent-auth/v1/authorizations/${authorizationId}/approve`) {
58
+ res.end(JSON.stringify({ redirect_uri: 'http://127.0.0.1:12345/callback?code=synthetic-code' }));
59
+ } else if (url.pathname === `/agent-auth/v1/sessions/${sessionId}/subject-display`) {
60
+ const display = JSON.parse(body).subject_display;
61
+ res.end(JSON.stringify({ ...item, state: 'active', subject_display: display, subject_display_status: display ? 'provided' : 'missing' }));
62
+ } else if (url.pathname.endsWith('/deny') || url.pathname.endsWith('/revoke') || url.pathname === '/body-check') {
63
+ res.end('{}');
64
+ } else {
65
+ res.statusCode = 404;
66
+ res.end('{"error":"not found"}');
67
+ }
68
+ });
69
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
70
+ const encoded = (value) => Buffer.from(JSON.stringify(value)).toString('base64');
71
+ try {
72
+ for (const variant of ['php', 'php7']) {
73
+ const command = variant === 'php7' ? (process.env.BAILING_SDK_PHP7_BINARY || 'php') : 'php';
74
+ const start = requests.length;
75
+ const result = await runAsync(command, ['-r', `
76
+ require '${root}/sdk/${variant}/src/HubClient.php';
77
+ require '${root}/sdk/${variant}/src/AgentAuth.php';
78
+ $auth = new Bailing\\Connect\\AgentAuth('http://127.0.0.1:${server.address().port}', 'synthetic-client-token');
79
+ $out = array('runtime' => PHP_VERSION);
80
+ $out['context'] = $auth->context('${authorizationId}');
81
+ $out['unmapped'] = $auth->context('${unmappedId}');
82
+ $out['default'] = $auth->listSessions();
83
+ $out['filtered'] = $auth->listSessions(json_decode(base64_decode('${encoded(filters)}'), true));
84
+ $out['tenantless'] = $auth->listSessions(array('principal_id' => 'u', 'tenant' => '', 'limit' => 1));
85
+ $out['tenant'] = $auth->listSessions(array('tenant' => str_repeat('😀', 64)));
86
+ $out['revoke'] = $auth->revokeAuthorization('${authorizationId}');
87
+ $out['repeat'] = $auth->revokeAuthorization('${authorizationId}');
88
+ $auth->deny('${authorizationId}');
89
+ $auth->revokeSession('${sessionId}');
90
+ $hub = new Bailing\\Connect\\HubClient('http://127.0.0.1:${server.address().port}', 'synthetic-client-token');
91
+ $hub->post('/body-check', array('nested' => array(), 'value' => 'kept'));
92
+ $hub->post('/body-check', array('nonempty-list'));
93
+ $principal = array('id' => 'user-a', 'tenant' => 'tenant-a');
94
+ $out['approveOld'] = $auth->approve('${authorizationId}', $principal, 'tenant-a:user-a', array('staff-route'));
95
+ $out['approveNamed'] = $auth->approve('${authorizationId}', $principal, 'tenant-a:user-a', array('staff-route'), array('name' => ' Account A '));
96
+ $out['approveMissing'] = $auth->approve('${authorizationId}', $principal, 'tenant-a:user-a', array('staff-route'), null);
97
+ $out['named'] = $auth->updateSubjectDisplay('${sessionId}', array('name' => ' Account A '));
98
+ $out['cleared'] = $auth->updateSubjectDisplay('${sessionId}', null);
99
+ $out['unicodeName'] = $auth->updateSubjectDisplay('${sessionId}', array('name' => str_repeat('😀', 60)));
100
+ $out['invalidDisplays'] = array();
101
+ foreach (json_decode(base64_decode('${encoded(invalidDisplays)}'), true) as $display) {
102
+ try { $auth->updateSubjectDisplay('${sessionId}', $display); $out['invalidDisplays'][] = false; }
103
+ catch (Throwable $e) { $out['invalidDisplays'][] = true; }
104
+ try { $auth->approve('${authorizationId}', $principal, 'tenant-a:user-a', array('staff-route'), $display); $out['invalidDisplays'][] = false; }
105
+ catch (Throwable $e) { $out['invalidDisplays'][] = true; }
106
+ }
107
+ try { $auth->updateSubjectDisplay('${sessionId}', array('name' => "\\xFF")); $out['invalidDisplayUtf8'] = false; }
108
+ catch (Throwable $e) { $out['invalidDisplayUtf8'] = true; }
109
+ try { $auth->updateSubjectDisplay('not-a-uuid', null); $out['invalidDisplayId'] = false; }
110
+ catch (Throwable $e) { $out['invalidDisplayId'] = true; }
111
+ $out['invalid'] = array();
112
+ foreach (json_decode(base64_decode('${encoded(invalid)}'), true) as $filters) {
113
+ try { $auth->listSessions($filters); $out['invalid'][] = false; }
114
+ catch (InvalidArgumentException $e) { $out['invalid'][] = true; }
115
+ }
116
+ try { $auth->listSessions(array('tenant' => "\\xFF")); $out['invalidUtf8'] = false; }
117
+ catch (InvalidArgumentException $e) { $out['invalidUtf8'] = true; }
118
+ try { $auth->revokeAuthorization('not-a-uuid'); $out['invalidId'] = false; }
119
+ catch (InvalidArgumentException $e) { $out['invalidId'] = true; }
120
+ echo json_encode($out, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
121
+ `]);
122
+ let data;
123
+ try { data = JSON.parse(result.stdout); } catch {}
124
+ const captured = requests.slice(start);
125
+ const label = `${variant.toUpperCase()} AgentAuth lifecycle`;
126
+ ok(`${label} runs on PHP ${data?.runtime ?? 'unknown'}`, result.status === 0 && !!data, result.stderr || result.stdout);
127
+ ok(`${label} preserves consumed context and missing-session projection`,
128
+ JSON.stringify(data?.context?.session) === JSON.stringify(session)
129
+ && data?.context?.requested_routes?.[0] === 'staff-route'
130
+ && data?.unmapped?.session === null);
131
+ ok(`${label} returns list metadata and opaque/null cursors unchanged`,
132
+ JSON.stringify(data?.default?.list) === JSON.stringify([item])
133
+ && data?.default?.next_cursor === 'next_page-1' && data?.filtered?.next_cursor === null);
134
+ const listRequests = captured.filter((request) => request.url.startsWith('/agent-auth/v1/sessions') && request.method === 'GET');
135
+ const query = new URL(listRequests[1]?.url ?? '/', 'http://fixture.invalid');
136
+ ok(`${label} uses only whitelisted RFC3986 query fields without broadening`,
137
+ listRequests[0]?.url === '/agent-auth/v1/sessions'
138
+ && JSON.stringify(Object.fromEntries(query.searchParams)) === JSON.stringify(Object.fromEntries(Object.entries(filters).map(([key, value]) => [key, String(value)])))
139
+ && listRequests[1]?.url.includes('%20') && !listRequests[1]?.url.includes('+')
140
+ && listRequests[2]?.url === '/agent-auth/v1/sessions?principal_id=u&tenant=&limit=1'
141
+ && new URL(listRequests[3]?.url ?? '/', 'http://fixture.invalid').searchParams.get('tenant') === '😀'.repeat(64));
142
+ ok(`${label} rejects ${invalid.length + 2} invalid filters/IDs before HTTP`,
143
+ data?.invalid?.length === invalid.length && data.invalid.every(Boolean)
144
+ && data?.invalidUtf8 === true && data?.invalidId === true && captured.length === 18);
145
+ ok(`${label} uses idempotent revoke-authorization path and empty object bodies`,
146
+ JSON.stringify(data?.revoke) === JSON.stringify({ authorization_id: authorizationId, revoked: true, session_id: sessionId })
147
+ && JSON.stringify(data?.repeat) === JSON.stringify(data?.revoke)
148
+ && captured.slice(6, 10).every((request) => request.method === 'POST' && request.body === '{}')
149
+ && captured[6]?.url === `/agent-auth/v1/authorizations/${authorizationId}/revoke`
150
+ && captured[7]?.url === captured[6]?.url);
151
+ ok(`${label} keeps non-empty HubClient bodies unchanged`,
152
+ captured[10]?.body === '{"nested":[],"value":"kept"}' && captured[11]?.body === '["nonempty-list"]');
153
+ const approvals = captured.filter((request) => request.url.endsWith('/approve'));
154
+ ok(`${label} keeps four-argument approval compatible and transmits explicit display/null`,
155
+ approvals.length === 3 && approvals.every((request) => request.method === 'POST')
156
+ && !Object.hasOwn(JSON.parse(approvals[0].body), 'subject_display')
157
+ && JSON.stringify(JSON.parse(approvals[1].body).subject_display) === JSON.stringify({ name: 'Account A' })
158
+ && JSON.parse(approvals[2].body).subject_display === null
159
+ && JSON.parse(approvals[1].body).principal.id === 'user-a');
160
+ const updates = captured.filter((request) => request.url.endsWith('/subject-display'));
161
+ ok(`${label} updates only display via PUT and preserves returned session metadata`,
162
+ updates.length === 3 && updates.every((request) => request.method === 'PUT'
163
+ && Object.keys(JSON.parse(request.body)).join(',') === 'subject_display')
164
+ && data?.named?.subject_display?.name === 'Account A' && data?.named?.subject_display_status === 'provided'
165
+ && data?.named?.session_id === sessionId && data?.named?.principal?.id === item.principal.id
166
+ && data?.cleared?.subject_display === null && data?.cleared?.subject_display_status === 'missing'
167
+ && data?.unicodeName?.subject_display?.name === '😀'.repeat(60));
168
+ ok(`${label} rejects invalid display objects, controls, length, UTF-8 and IDs before HTTP`,
169
+ data?.invalidDisplays?.length === invalidDisplays.length * 2 && data.invalidDisplays.every(Boolean)
170
+ && data?.invalidDisplayUtf8 === true && data?.invalidDisplayId === true && captured.length === 18);
171
+ ok(`${label} sends only server-side Client Token headers`, captured.every((request) =>
172
+ request.headers.authorization === 'Bearer synthetic-client-token'
173
+ && !request.url.includes('synthetic-client-token') && !request.body.includes('synthetic-client-token')));
174
+ }
175
+ } finally {
176
+ await closeServer(server);
177
+ }
178
+ }
@@ -2,6 +2,7 @@ import { spawn, spawnSync } from 'node:child_process';
2
2
  import { createServer } from 'node:http';
3
3
  import { dirname, resolve } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
+ import { checkAgentAuthLifecycle } from './sdk-agent-auth-lifecycle-check.mjs';
5
6
  import {
6
7
  HubClient,
7
8
  authzProbeResponse,
@@ -103,7 +104,7 @@ ok('PHP protected spec response is private/no-store', php.status === 0 && php.st
103
104
  ok('PHP explicit public spec helper works', php.status === 0 && php.stdout.split('\n')[4] === 'public-helper', php.stderr || php.stdout);
104
105
  ok('PHP legacy null-public signature remains compatible', php.status === 0 && php.stdout.split('\n')[5] === 'legacy-null', php.stderr || php.stdout);
105
106
 
106
- const php7 = run('php', ['-r', `
107
+ const php7 = run(process.env.BAILING_SDK_PHP7_BINARY || 'php', ['-r', `
107
108
  require '${root}/sdk/php7/src/Ticket.php';
108
109
  require '${root}/sdk/php7/src/HubClient.php';
109
110
  require '${root}/sdk/php7/src/AgentAuth.php';
@@ -176,7 +177,7 @@ let php7AgentAuth;
176
177
  try {
177
178
  const address = agentAuthServer.address();
178
179
  const baseUrl = `http://127.0.0.1:${address.port}`;
179
- php7AgentAuth = await runAsync('php', ['-r', `
180
+ php7AgentAuth = await runAsync(process.env.BAILING_SDK_PHP7_BINARY || 'php', ['-r', `
180
181
  require '${root}/sdk/php7/src/HubClient.php';
181
182
  require '${root}/sdk/php7/src/AgentAuth.php';
182
183
  $authorizationId = '${authorizationId}';
@@ -261,6 +262,8 @@ ok('PHP7 HubClient does not follow a Bearer-authenticated redirect',
261
262
  php7AgentAuthData?.redirect === 'HTTP 302'
262
263
  && !agentAuthRequests.some((request) => request.url === '/agent-auth-leak'));
263
264
 
265
+ await checkAgentAuthLifecycle({ root, runAsync, ok, closeServer });
266
+
264
267
  console.log(`\n结果:通过 ${pass} / 失败 ${fail}`);
265
268
  process.exit(fail ? 1 : 0);
266
269
 
@@ -129,6 +129,8 @@ const requiredFiles = [
129
129
  'docs/RELEASE_NOTES_v0.3.4.md',
130
130
  'docs/RELEASE_NOTES_v0.5.0.md',
131
131
  'docs/RELEASE_NOTES_v0.5.1.md',
132
+ 'docs/RELEASE_NOTES_v0.7.0.md',
133
+ 'docs/RELEASE_NOTES_v0.6.1.md',
132
134
  'docs/RELEASE_NOTES_v0.6.0.md',
133
135
  'docs/CHANGELOG.md',
134
136
  ];
package/sdk/php/README.md CHANGED
@@ -221,6 +221,35 @@ $result = $agentAuth->approve(
221
221
 
222
222
  `principal` 和 `on_behalf_of` 必须由业务后端从当前登录态生成,不得从前端表单原样透传。该协议只绑定业务身份、路由与设备会话,不承载套餐、付费或权益字段。
223
223
 
224
+ **Core 0.7.0 配套的生命周期接口**支持核对和收回现有授权。请同时升级本 SDK 下载包与 Core。业务后端可以先查询自己有权管理的租户,再按原授权记录撤销:
225
+
226
+ ```php
227
+ $page = $agentAuth->listSessions(['tenant' => (string) $tenantId, 'limit' => 20]);
228
+ $session = $agentAuth->context($authorizationId)['session'] ?? null;
229
+ $revoked = $agentAuth->revokeAuthorization($authorizationId);
230
+ ```
231
+
232
+ `listSessions()` 默认 20 条,最大 100;下一页原样保留筛选条件并传 `next_cursor`,返回 null 即结束。
233
+ 按操作人筛选必须同时传 `principal_id` 与 `tenant`,无租户用 `tenant => ''`。分页反映当前状态,
234
+ 不是跨请求快照。`session` 缺失/null 不可猜测;`active` 不保证业务账号仍有权限,过期按 refresh
235
+ 生命周期判断。撤销可按同一授权 ID 幂等重试,503/超时或 consumed 映射缺失的 404 不代表成功。
236
+ Client Token 与管理权限判断均留在业务后端;字段规则见上方 Agent Auth 契约。
237
+
238
+ ### 授权后显示业务名称
239
+
240
+ Core 0.7.0 支持批准授权时附上服务端读取的业务名称。原四参数调用保持兼容;第五参数可选,名称可用于门店、公司、项目等业务对象。
241
+
242
+ ```php
243
+ $result = $agentAuth->approve($authorizationId, $principal, $onBehalfOf, $allowedRoutes, array('name' => $accountName));
244
+ $session = $agentAuth->updateSubjectDisplay($sessionId, array('name' => $accountName));
245
+ // 仅清除显示信息,不撤销或替换授权:
246
+ $session = $agentAuth->updateSubjectDisplay($sessionId, null);
247
+ ```
248
+
249
+ 名称由业务后端从真实记录读取,不参与身份或权限判断;更新只允许当前接入方自己的有效会话。
250
+ 旧授权没有名称时显示待同步,不需要重新登录或重建连接。详见
251
+ [授权名称与三方职责](../../docs/AGENT_SUBJECT_DISPLAY.md)。
252
+
224
253
  ## CI 集成
225
254
 
226
255
  ```bash
@@ -28,12 +28,55 @@ final class AgentAuth
28
28
  return $this->hub->get('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId));
29
29
  }
30
30
 
31
+ /**
32
+ * 查询当前接入方的授权会话;principal_id 必须同时指定 tenant。
33
+ * tenant='' 精确选择无租户主体,省略 tenant 则不按租户过滤。
34
+ *
35
+ * @param array{authorization_id?:string,on_behalf_of?:string,principal_id?:string,tenant?:string,state?:string,limit?:int,cursor?:string} $filters
36
+ * @return array<string,mixed>
37
+ */
38
+ public function listSessions(array $filters = []): array
39
+ {
40
+ $allowed = ['authorization_id', 'on_behalf_of', 'principal_id', 'tenant', 'state', 'limit', 'cursor'];
41
+ foreach ($filters as $key => $value) {
42
+ if (!in_array($key, $allowed, true)) {
43
+ throw new InvalidArgumentException('未知会话筛选字段');
44
+ }
45
+ if ($key === 'authorization_id') {
46
+ if (!is_string($value) || !preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iD', $value)) {
47
+ throw new InvalidArgumentException('authorization_id 必须是 UUID');
48
+ }
49
+ } elseif (in_array($key, ['on_behalf_of', 'principal_id', 'tenant'], true)) {
50
+ self::assertFilterString($value, $key, $key === 'on_behalf_of' ? 191 : 128, $key === 'tenant');
51
+ } elseif ($key === 'state' && !in_array($value, ['active', 'expired', 'revoked'], true)) {
52
+ throw new InvalidArgumentException('state 必须是 active、expired 或 revoked');
53
+ } elseif ($key === 'limit' && (!is_int($value) || $value < 1 || $value > 100)) {
54
+ throw new InvalidArgumentException('limit 必须是 1 到 100 的整数');
55
+ } elseif ($key === 'cursor' && (!is_string($value) || strlen($value) > 2048 || !preg_match('/^[A-Za-z0-9_-]+$/D', $value))) {
56
+ throw new InvalidArgumentException('cursor 必须是非空、不带填充的 base64url 字符串,长度不超过 2048');
57
+ }
58
+ }
59
+ if (array_key_exists('principal_id', $filters) && !array_key_exists('tenant', $filters)) {
60
+ throw new InvalidArgumentException('principal_id 必须同时指定 tenant');
61
+ }
62
+ $query = http_build_query($filters, '', '&', PHP_QUERY_RFC3986);
63
+ return $this->hub->get('/agent-auth/v1/sessions' . ($query === '' ? '' : '?' . $query));
64
+ }
65
+
66
+ /** @return array<string,mixed> */
67
+ public function revokeAuthorization(string $authorizationId): array
68
+ {
69
+ self::assertId($authorizationId, 'authorizationId');
70
+ return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/revoke', []);
71
+ }
72
+
31
73
  /**
32
74
  * @param array{id:string,tenant?:string,roles?:array<int,string>,audience?:string,channel?:string} $principal
75
+ * @param array{name:string}|null $subjectDisplay Optional server-sourced display name; never an identity key.
33
76
  * @param array<int,string> $allowedRoutes
34
77
  * @return array<string,mixed>
35
78
  */
36
- public function approve(string $authorizationId, array $principal, string $onBehalfOf, array $allowedRoutes): array
79
+ public function approve(string $authorizationId, array $principal, string $onBehalfOf, array $allowedRoutes, ?array $subjectDisplay = null): array
37
80
  {
38
81
  self::assertId($authorizationId, 'authorizationId');
39
82
  if (!isset($principal['id']) || trim((string) $principal['id']) === '') {
@@ -48,11 +91,16 @@ final class AgentAuth
48
91
  if (!isset($principal['roles'])) {
49
92
  $principal['roles'] = [];
50
93
  }
51
- return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/approve', [
94
+ $body = [
52
95
  'principal' => $principal,
53
96
  'on_behalf_of' => $onBehalfOf,
54
97
  'allowed_routes' => array_values($allowedRoutes),
55
- ]);
98
+ ];
99
+ // Existing four-argument calls keep their original HTTP shape for older Core versions.
100
+ if (func_num_args() >= 5) {
101
+ $body['subject_display'] = self::normalizeSubjectDisplay($subjectDisplay);
102
+ }
103
+ return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/approve', $body);
56
104
  }
57
105
 
58
106
  /** @return array<string,mixed> */
@@ -69,10 +117,58 @@ final class AgentAuth
69
117
  return $this->hub->post('/agent-auth/v1/sessions/' . rawurlencode($sessionId) . '/revoke', []);
70
118
  }
71
119
 
120
+ /**
121
+ * 同步当前接入方已有有效授权的显示名称;不修改身份、权限或有效期。
122
+ * @param array{name:string}|null $subjectDisplay 业务服务端读取的名称,null 表示清除
123
+ * @return array
124
+ */
125
+ public function updateSubjectDisplay(string $sessionId, ?array $subjectDisplay): array
126
+ {
127
+ self::assertId($sessionId, 'sessionId');
128
+ return $this->hub->request('PUT', '/agent-auth/v1/sessions/' . rawurlencode($sessionId) . '/subject-display', [
129
+ 'subject_display' => self::normalizeSubjectDisplay($subjectDisplay),
130
+ ]);
131
+ }
132
+
133
+ private static function normalizeSubjectDisplay(mixed $value): ?array
134
+ {
135
+ if ($value === null) {
136
+ return null;
137
+ }
138
+ if (!is_array($value) || array_keys($value) !== ['name'] || !is_string($value['name'])) {
139
+ throw new InvalidArgumentException('subjectDisplay 只能包含字符串 name');
140
+ }
141
+ $name = $value['name'];
142
+ // Reject controls before trimming; line breaks must not become a valid one-line name.
143
+ if (preg_match('//u', $name) !== 1 || preg_match('/[\x00-\x1f\x7f-\x9f\x{2028}\x{2029}]/u', $name)) {
144
+ throw new InvalidArgumentException('subjectDisplay.name 必须是无控制字符的单行文本');
145
+ }
146
+ $name = preg_replace('/^[\p{Z}\x{FEFF}]+|[\p{Z}\x{FEFF}]+$/u', '', $name);
147
+ self::assertFilterString($name, 'subjectDisplay.name', 120, false);
148
+ return ['name' => $name];
149
+ }
150
+
72
151
  private static function assertId(string $value, string $name): void
73
152
  {
74
- if (!preg_match('/^[0-9a-f-]{36}$/i', $value)) {
153
+ if (!preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iD', $value)) {
75
154
  throw new InvalidArgumentException($name . ' 必须是 UUID');
76
155
  }
77
156
  }
157
+
158
+ private static function assertFilterString(mixed $value, string $name, int $max, bool $allowEmpty): void
159
+ {
160
+ if (!is_string($value) || (!$allowEmpty && $value === '') ||
161
+ preg_match('/[\x00-\x1f\x7f]|^[\p{Z}\x{FEFF}]|[\p{Z}\x{FEFF}]$/u', $value) ||
162
+ preg_match_all('/./us', $value, $characters) === false) {
163
+ throw new InvalidArgumentException($name . ' 必须是无首尾空白或控制字符的有效字符串');
164
+ }
165
+ // 与 HTTP 服务端的 UTF-16 长度一致,不依赖 mbstring 扩展。
166
+ $length = 0;
167
+ foreach ($characters[0] as $character) {
168
+ $length += strlen($character) > 3 ? 2 : 1;
169
+ }
170
+ if ($length > $max) {
171
+ throw new InvalidArgumentException($name . ' 长度超出限制');
172
+ }
173
+ }
78
174
  }
@@ -90,7 +90,8 @@ final class HubClient
90
90
  $headers = ['Authorization: Bearer ' . $this->token];
91
91
  $content = '';
92
92
  if ($body !== null) {
93
- $content = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: '{}';
93
+ // Hub API 请求顶层是对象,空参数也发送 {}(例如 deny/revoke)。
94
+ $content = $body === [] ? '{}' : (json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: '{}');
94
95
  $headers[] = 'Content-Type: application/json';
95
96
  }
96
97
  $http = [
@@ -215,6 +215,37 @@ $result = $agentAuth->approve(
215
215
 
216
216
  完整关系与 HTTP 契约见中枢文档 `docs/AGENT_CLIENT_QUICKSTART.md` 和 `docs/AGENT_AUTH_API.md`。
217
217
 
218
+ **Core 0.7.0 配套的生命周期接口**支持核对和收回现有授权。请同时升级本 SDK 下载包与 Core。PHP 7.3 版与 PHP 8.1+ 版方法和语义一致:
219
+
220
+ ```php
221
+ $page = $agentAuth->listSessions(array('tenant' => (string) $tenantId, 'limit' => 20));
222
+ $context = $agentAuth->context($authorizationId);
223
+ $session = isset($context['session']) ? $context['session'] : null;
224
+ $revoked = $agentAuth->revokeAuthorization($authorizationId);
225
+ ```
226
+
227
+ 默认每页 20 条、最大 100;下一页保留全部筛选条件并传 `next_cursor`,null 表示结束。按操作人
228
+ 筛选必须同时传 `principal_id` 与 `tenant`,无租户用 `tenant => ''`。分页反映当前状态,不是跨请求
229
+ 快照。`session` 缺失/null 不可猜测;`active` 不保证业务账号仍有权限,过期按 refresh 生命周期判断。
230
+ 撤销同一授权可幂等重试,503/超时或 consumed 映射缺失的 404 不代表成功。后端先确认管理权限,
231
+ 再调用这些方法;Client Token 不进入浏览器。完整字段见
232
+ [Agent Auth v1](../../docs/AGENT_AUTH_API.md)。
233
+
234
+ ### 授权后显示业务名称
235
+
236
+ Core 0.7.0 支持批准授权时附上服务端读取的业务名称。原四参数调用保持兼容;第五参数可选,名称可用于门店、公司、项目等业务对象。
237
+
238
+ ```php
239
+ $result = $agentAuth->approve($authorizationId, $principal, $onBehalfOf, $allowedRoutes, array('name' => $accountName));
240
+ $session = $agentAuth->updateSubjectDisplay($sessionId, array('name' => $accountName));
241
+ // 仅清除显示信息,不撤销或替换授权:
242
+ $session = $agentAuth->updateSubjectDisplay($sessionId, null);
243
+ ```
244
+
245
+ 名称由业务后端从真实记录读取,不参与身份或权限判断;更新只允许当前接入方自己的有效会话。
246
+ 旧授权没有名称时显示待同步,不需要重新登录或重建连接。详见
247
+ [授权名称与三方职责](../../docs/AGENT_SUBJECT_DISPLAY.md)。
248
+
218
249
  ## 范例
219
250
 
220
251
  - `examples/build-spec.php`:完整 builder 范例(覆盖全部字段;与 8.x 版同源,跑同一个跨语言契约测试)
@@ -27,12 +27,54 @@ final class AgentAuth
27
27
  return $this->hub->get('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId));
28
28
  }
29
29
 
30
+ /**
31
+ * 查询当前接入方的授权会话;principal_id 必须同时指定 tenant。
32
+ * tenant='' 精确选择无租户主体,省略 tenant 则不按租户过滤。
33
+ * @param array $filters authorization_id/on_behalf_of/principal_id/tenant/state/limit/cursor
34
+ * @return array
35
+ */
36
+ public function listSessions(array $filters = array())
37
+ {
38
+ $allowed = array('authorization_id', 'on_behalf_of', 'principal_id', 'tenant', 'state', 'limit', 'cursor');
39
+ foreach ($filters as $key => $value) {
40
+ if (!in_array($key, $allowed, true)) {
41
+ throw new InvalidArgumentException('未知会话筛选字段');
42
+ }
43
+ if ($key === 'authorization_id') {
44
+ if (!is_string($value) || !preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iD', $value)) {
45
+ throw new InvalidArgumentException('authorization_id 必须是 UUID');
46
+ }
47
+ } elseif (in_array($key, array('on_behalf_of', 'principal_id', 'tenant'), true)) {
48
+ self::assertFilterString($value, $key, $key === 'on_behalf_of' ? 191 : 128, $key === 'tenant');
49
+ } elseif ($key === 'state' && !in_array($value, array('active', 'expired', 'revoked'), true)) {
50
+ throw new InvalidArgumentException('state 必须是 active、expired 或 revoked');
51
+ } elseif ($key === 'limit' && (!is_int($value) || $value < 1 || $value > 100)) {
52
+ throw new InvalidArgumentException('limit 必须是 1 到 100 的整数');
53
+ } elseif ($key === 'cursor' && (!is_string($value) || strlen($value) > 2048 || !preg_match('/^[A-Za-z0-9_-]+$/D', $value))) {
54
+ throw new InvalidArgumentException('cursor 必须是非空、不带填充的 base64url 字符串,长度不超过 2048');
55
+ }
56
+ }
57
+ if (array_key_exists('principal_id', $filters) && !array_key_exists('tenant', $filters)) {
58
+ throw new InvalidArgumentException('principal_id 必须同时指定 tenant');
59
+ }
60
+ $query = http_build_query($filters, '', '&', PHP_QUERY_RFC3986);
61
+ return $this->hub->get('/agent-auth/v1/sessions' . ($query === '' ? '' : '?' . $query));
62
+ }
63
+
64
+ /** @return array */
65
+ public function revokeAuthorization($authorizationId)
66
+ {
67
+ self::assertId($authorizationId, 'authorizationId');
68
+ return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/revoke', array());
69
+ }
70
+
30
71
  /**
31
72
  * @param array $principal 业务后端从当前登录态推导的主体,必须包含 id
32
73
  * @param array $allowedRoutes 本次授权允许的路由标识
74
+ * @param array|null $subjectDisplay 业务服务端提供的显示名称,不参与身份判定
33
75
  * @return array
34
76
  */
35
- public function approve($authorizationId, array $principal, $onBehalfOf, array $allowedRoutes)
77
+ public function approve($authorizationId, array $principal, $onBehalfOf, array $allowedRoutes, $subjectDisplay = null)
36
78
  {
37
79
  self::assertId($authorizationId, 'authorizationId');
38
80
  if (!isset($principal['id']) || trim((string) $principal['id']) === '') {
@@ -47,11 +89,16 @@ final class AgentAuth
47
89
  if (!isset($principal['roles'])) {
48
90
  $principal['roles'] = array();
49
91
  }
50
- return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/approve', array(
92
+ $body = array(
51
93
  'principal' => $principal,
52
94
  'on_behalf_of' => $onBehalfOf,
53
95
  'allowed_routes' => array_values($allowedRoutes),
54
- ));
96
+ );
97
+ // Existing four-argument calls keep their original HTTP shape for older Core versions.
98
+ if (func_num_args() >= 5) {
99
+ $body['subject_display'] = self::normalizeSubjectDisplay($subjectDisplay);
100
+ }
101
+ return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/approve', $body);
55
102
  }
56
103
 
57
104
  /** @return array */
@@ -68,10 +115,58 @@ final class AgentAuth
68
115
  return $this->hub->post('/agent-auth/v1/sessions/' . rawurlencode($sessionId) . '/revoke', array());
69
116
  }
70
117
 
118
+ /**
119
+ * 同步当前接入方已有有效授权的显示名称;不修改身份、权限或有效期。
120
+ * @param array{name:string}|null $subjectDisplay 业务服务端读取的名称,null 表示清除
121
+ * @return array
122
+ */
123
+ public function updateSubjectDisplay($sessionId, $subjectDisplay)
124
+ {
125
+ self::assertId($sessionId, 'sessionId');
126
+ return $this->hub->request('PUT', '/agent-auth/v1/sessions/' . rawurlencode($sessionId) . '/subject-display', array(
127
+ 'subject_display' => self::normalizeSubjectDisplay($subjectDisplay),
128
+ ));
129
+ }
130
+
131
+ private static function normalizeSubjectDisplay($value)
132
+ {
133
+ if ($value === null) {
134
+ return null;
135
+ }
136
+ if (!is_array($value) || array_keys($value) !== array('name') || !is_string($value['name'])) {
137
+ throw new InvalidArgumentException('subjectDisplay 只能包含字符串 name');
138
+ }
139
+ $name = $value['name'];
140
+ // Reject controls before trimming; line breaks must not become a valid one-line name.
141
+ if (preg_match('//u', $name) !== 1 || preg_match('/[\x00-\x1f\x7f-\x9f\x{2028}\x{2029}]/u', $name)) {
142
+ throw new InvalidArgumentException('subjectDisplay.name 必须是无控制字符的单行文本');
143
+ }
144
+ $name = preg_replace('/^[\p{Z}\x{FEFF}]+|[\p{Z}\x{FEFF}]+$/u', '', $name);
145
+ self::assertFilterString($name, 'subjectDisplay.name', 120, false);
146
+ return array('name' => $name);
147
+ }
148
+
71
149
  private static function assertId($value, $name)
72
150
  {
73
- if (!is_string($value) || !preg_match('/^[0-9a-f-]{36}$/i', $value)) {
151
+ if (!is_string($value) || !preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iD', $value)) {
74
152
  throw new InvalidArgumentException($name . ' 必须是 UUID');
75
153
  }
76
154
  }
155
+
156
+ private static function assertFilterString($value, $name, $max, $allowEmpty)
157
+ {
158
+ if (!is_string($value) || (!$allowEmpty && $value === '') ||
159
+ preg_match('/[\x00-\x1f\x7f]|^[\p{Z}\x{FEFF}]|[\p{Z}\x{FEFF}]$/u', $value) ||
160
+ preg_match_all('/./us', $value, $characters) === false) {
161
+ throw new InvalidArgumentException($name . ' 必须是无首尾空白或控制字符的有效字符串');
162
+ }
163
+ // 与 HTTP 服务端的 UTF-16 长度一致,不依赖 mbstring 扩展。
164
+ $length = 0;
165
+ foreach ($characters[0] as $character) {
166
+ $length += strlen($character) > 3 ? 2 : 1;
167
+ }
168
+ if ($length > $max) {
169
+ throw new InvalidArgumentException($name . ' 长度超出限制');
170
+ }
171
+ }
77
172
  }
@@ -74,7 +74,8 @@ final class HubClient
74
74
  $headers = array('Authorization: Bearer ' . $this->token);
75
75
  $content = '';
76
76
  if ($body !== null) {
77
- $content = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
77
+ // Hub API 请求顶层是对象,空参数也发送 {}(例如 deny/revoke)。
78
+ $content = $body === array() ? '{}' : json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
78
79
  if ($content === false) {
79
80
  $content = '{}';
80
81
  }
@@ -0,0 +1,9 @@
1
+ -- Additive opt-in for cross-client/route audit membership. Legacy v1 rows keep
2
+ -- their original single binding; no Session, run, invocation or text is moved.
3
+ ALTER TABLE `bz_agent_conversation_audits` ADD COLUMN `membership_version` TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '1=legacy common binding, 2=explicit per-member binding';
4
+
5
+ ALTER TABLE `bz_agent_conversation_members` ADD COLUMN `client_app_id` VARCHAR(64) DEFAULT NULL COMMENT 'Frozen original Client App, NULL for legacy v1';
6
+
7
+ ALTER TABLE `bz_agent_conversation_members` ADD COLUMN `route_key` VARCHAR(64) DEFAULT NULL COMMENT 'Frozen original route/workspace, NULL for legacy v1';
8
+
9
+ ALTER TABLE `bz_agent_conversation_members` ADD COLUMN `client_name` VARCHAR(128) DEFAULT NULL COMMENT 'Display snapshot only, never identity or authorization';
@@ -0,0 +1,5 @@
1
+ -- Optional business-supplied display metadata. Existing authorizations remain
2
+ -- unnamed; no inference from device labels, identities, route names or history.
3
+ ALTER TABLE `bz_agent_authorizations` ADD COLUMN `subject_display` JSON DEFAULT NULL COMMENT 'Business subject display only, never an authorization identity';
4
+
5
+ ALTER TABLE `bz_agent_sessions` ADD COLUMN `subject_display` JSON DEFAULT NULL COMMENT 'Current business subject display, independent of frozen audit labels';
package/sql/README.en.md CHANGED
@@ -18,6 +18,21 @@ A small immutable catalog records the filename, original byte checksum, and leng
18
18
 
19
19
  Duplicate-column or duplicate-index errors are tolerated only when the live object exactly matches the official `ADD COLUMN` or `ADD INDEX` statement. Other SQL errors remain fatal.
20
20
 
21
+ ## Unreleased candidate: 059 authorization subject display
22
+
23
+ `059_agent_subject_display.sql` adds one nullable JSON column named `subject_display`,
24
+ with a NULL default, to each of `bz_agent_authorizations` and `bz_agent_sessions`.
25
+ Existing rows stay NULL (name pending sync); device names, local aliases and identity
26
+ values are not used to invent names. No principal, scope, credential, Session or
27
+ archive record is rewritten. Business backends can later name the original session
28
+ through the [authorization name API](../docs/AGENT_SUBJECT_DISPLAY.en.md).
29
+
30
+ Explicitly apply 059 through the existing migration entry point before starting this
31
+ candidate runtime. Custom Hosts must package the official SQL and implement the optional
32
+ display-update repository method. An older Host explicitly reports unavailable for
33
+ new naming operations while accepting the original approval request without a name.
34
+ These candidate files do not indicate that a deployment or migration has occurred.
35
+
21
36
  ## Migration Rules
22
37
 
23
38
  Schema files are part of the deployment safety boundary.