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
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { Readable } from 'node:stream';
|
|
3
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
4
|
+
import test from 'node:test';
|
|
5
|
+
import type { AgentSession, Client } from '../core/contracts/types';
|
|
6
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
7
|
+
import type { AgentAuthorization } from '../infrastructure/config/config-agent-auth-repository';
|
|
8
|
+
import { handleAgentAuthHttpFor, isLoopbackRedirectUri, pkceChallenge, tokenHash } from './agent-auth';
|
|
9
|
+
|
|
10
|
+
class FakeResponse {
|
|
11
|
+
statusCode = 0;
|
|
12
|
+
headers: Record<string, string | number | string[]> = {};
|
|
13
|
+
body = Buffer.alloc(0);
|
|
14
|
+
|
|
15
|
+
setHeader(name: string, value: string | number | string[]): void { this.headers[name.toLowerCase()] = value; }
|
|
16
|
+
writeHead(code: number, headers?: Record<string, string | number | string[]>): void {
|
|
17
|
+
this.statusCode = code;
|
|
18
|
+
for (const [name, value] of Object.entries(headers ?? {})) this.headers[name.toLowerCase()] = value;
|
|
19
|
+
}
|
|
20
|
+
end(value?: string | Buffer): void { this.body = value ? Buffer.from(value) : Buffer.alloc(0); }
|
|
21
|
+
json(): Record<string, any> { return JSON.parse(this.body.toString('utf8')) as Record<string, any>; }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function request(method: string, body?: Record<string, unknown>, headers: Record<string, string> = {}): IncomingMessage {
|
|
25
|
+
const chunks = body === undefined ? [] : [Buffer.from(JSON.stringify(body))];
|
|
26
|
+
const req = Readable.from(chunks) as unknown as IncomingMessage;
|
|
27
|
+
req.method = method;
|
|
28
|
+
req.headers = headers;
|
|
29
|
+
Object.defineProperty(req, 'socket', { value: { remoteAddress: '127.0.0.9' } });
|
|
30
|
+
return req;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function call(store: ConfigStoreContract, method: string, path: string, body?: Record<string, unknown>, headers: Record<string, string> = {}): Promise<FakeResponse> {
|
|
34
|
+
const res = new FakeResponse();
|
|
35
|
+
const handled = await handleAgentAuthHttpFor(
|
|
36
|
+
{ configStore: store },
|
|
37
|
+
request(method, body, headers),
|
|
38
|
+
res as unknown as ServerResponse,
|
|
39
|
+
new URL(path, 'https://hub.example.com'),
|
|
40
|
+
);
|
|
41
|
+
assert.equal(handled, true);
|
|
42
|
+
return res;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
test('Agent Auth loopback redirect only accepts explicit-port IP literals', () => {
|
|
46
|
+
assert.equal(isLoopbackRedirectUri('http://127.0.0.1:43123/callback'), true);
|
|
47
|
+
assert.equal(isLoopbackRedirectUri('http://[::1]:43123/callback'), true);
|
|
48
|
+
assert.equal(isLoopbackRedirectUri('http://localhost:43123/callback'), false);
|
|
49
|
+
assert.equal(isLoopbackRedirectUri('http://2130706433:43123/callback'), false);
|
|
50
|
+
assert.equal(isLoopbackRedirectUri('http://0x7f000001:43123/callback'), false);
|
|
51
|
+
assert.equal(isLoopbackRedirectUri('http://127.0.0.1/callback'), false);
|
|
52
|
+
assert.equal(isLoopbackRedirectUri('https://127.0.0.1:43123/callback'), false);
|
|
53
|
+
assert.equal(isLoopbackRedirectUri('http://user@127.0.0.1:43123/callback'), false);
|
|
54
|
+
assert.equal(isLoopbackRedirectUri('http://127.0.0.1:43123/callback#fragment'), false);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('Agent Auth v1: context is redacted, PKCE binds client/redirect, query tokens fail, and business can revoke', async () => {
|
|
58
|
+
const client: Client = {
|
|
59
|
+
app_id: 'example-business',
|
|
60
|
+
name: 'Example Business',
|
|
61
|
+
token: 'business-client-token-0001',
|
|
62
|
+
agent_authorize_url: 'https://tenant.example.com/agent-authorize?from=hub',
|
|
63
|
+
allowed_routes: ['orders'],
|
|
64
|
+
allowed_channels: [],
|
|
65
|
+
rate_limit_per_min: 0,
|
|
66
|
+
enabled: true,
|
|
67
|
+
};
|
|
68
|
+
const otherClient: Client = { ...client, app_id: 'other-client', name: 'Other', token: 'other-client-token-000001' };
|
|
69
|
+
let authorization: AgentAuthorization | null = null;
|
|
70
|
+
let approvedCodeHash = '';
|
|
71
|
+
let accessHash = '';
|
|
72
|
+
let refreshHash = '';
|
|
73
|
+
let session: AgentSession | null = null;
|
|
74
|
+
let revoked = false;
|
|
75
|
+
let rateLimited = false;
|
|
76
|
+
|
|
77
|
+
const agentAuth = {
|
|
78
|
+
async createAuthorization(input: any) {
|
|
79
|
+
authorization = {
|
|
80
|
+
authorization_id: input.authorizationId,
|
|
81
|
+
client_app_id: input.clientAppId,
|
|
82
|
+
redirect_uri: input.redirectUri,
|
|
83
|
+
state: input.state,
|
|
84
|
+
requested_routes: input.requestedRoutes,
|
|
85
|
+
device_label: input.deviceLabel,
|
|
86
|
+
code_challenge: input.codeChallenge,
|
|
87
|
+
status: 'pending',
|
|
88
|
+
created_at: new Date().toISOString(),
|
|
89
|
+
expires_at: input.expiresAt,
|
|
90
|
+
};
|
|
91
|
+
},
|
|
92
|
+
async getAuthorization(id: string) { return authorization?.authorization_id === id ? authorization : null; },
|
|
93
|
+
async approveAuthorization(input: any) {
|
|
94
|
+
if (!authorization || authorization.authorization_id !== input.authorizationId || authorization.status !== 'pending') return { ok: false, reason: 'invalid_state' };
|
|
95
|
+
approvedCodeHash = input.codeHash;
|
|
96
|
+
authorization = {
|
|
97
|
+
...authorization,
|
|
98
|
+
status: 'approved',
|
|
99
|
+
principal: input.principal,
|
|
100
|
+
on_behalf_of: input.onBehalfOf,
|
|
101
|
+
allowed_routes: input.allowedRoutes,
|
|
102
|
+
code_expires_at: input.codeExpiresAt,
|
|
103
|
+
};
|
|
104
|
+
return { ok: true, authorization };
|
|
105
|
+
},
|
|
106
|
+
async denyAuthorization() { return { ok: false, reason: 'invalid_state' }; },
|
|
107
|
+
async exchangeAuthorizationCode(input: any) {
|
|
108
|
+
if (!authorization || authorization.status !== 'approved' || input.codeHash !== approvedCodeHash ||
|
|
109
|
+
input.clientAppId !== authorization.client_app_id || input.redirectUri !== authorization.redirect_uri ||
|
|
110
|
+
input.codeChallenge !== authorization.code_challenge) return { ok: false, reason: 'invalid_grant' };
|
|
111
|
+
accessHash = input.accessTokenHash;
|
|
112
|
+
refreshHash = input.refreshTokenHash;
|
|
113
|
+
session = {
|
|
114
|
+
session_id: input.sessionId,
|
|
115
|
+
client_app_id: authorization.client_app_id,
|
|
116
|
+
device_label: authorization.device_label,
|
|
117
|
+
principal: authorization.principal!,
|
|
118
|
+
on_behalf_of: authorization.on_behalf_of!,
|
|
119
|
+
allowed_routes: authorization.allowed_routes!,
|
|
120
|
+
created_at: new Date().toISOString(),
|
|
121
|
+
access_expires_at: input.accessExpiresAt,
|
|
122
|
+
refresh_expires_at: input.refreshExpiresAt,
|
|
123
|
+
};
|
|
124
|
+
authorization = { ...authorization, status: 'consumed' };
|
|
125
|
+
return { ok: true, session };
|
|
126
|
+
},
|
|
127
|
+
async rotateRefreshToken() { return { ok: false, reason: 'invalid_grant' }; },
|
|
128
|
+
async getSessionByAccessHash(hash: string) { return !revoked && hash === accessHash ? session : null; },
|
|
129
|
+
async revokeByAccessHash(hash: string) { if (hash === accessHash) revoked = true; return hash === accessHash; },
|
|
130
|
+
async revokeByRefreshHash(_app: string, hash: string) { if (hash === refreshHash) revoked = true; return hash === refreshHash; },
|
|
131
|
+
async revokeSessionForClient(appId: string, sessionId: string) {
|
|
132
|
+
if (session?.client_app_id === appId && session.session_id === sessionId) { revoked = true; return true; }
|
|
133
|
+
return false;
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
const store = {
|
|
137
|
+
agentAuth,
|
|
138
|
+
clients: {
|
|
139
|
+
get: async (appId: string) => appId === client.app_id ? client : appId === otherClient.app_id ? otherClient : null,
|
|
140
|
+
getByToken: async (token: string) => token === client.token ? client : token === otherClient.token ? otherClient : null,
|
|
141
|
+
},
|
|
142
|
+
rateLimits: { consume: async () => rateLimited },
|
|
143
|
+
} as unknown as ConfigStoreContract;
|
|
144
|
+
|
|
145
|
+
const verifier = 'v'.repeat(43);
|
|
146
|
+
const redirectUri = 'http://127.0.0.1:43123/callback?local=1';
|
|
147
|
+
const created = await call(store, 'POST', '/agent-auth/v1/authorizations', {
|
|
148
|
+
client_app_id: client.app_id,
|
|
149
|
+
redirect_uri: redirectUri,
|
|
150
|
+
state: 'state-12345678',
|
|
151
|
+
requested_routes: ['orders'],
|
|
152
|
+
device_label: 'Mac mini',
|
|
153
|
+
code_challenge: pkceChallenge(verifier),
|
|
154
|
+
code_challenge_method: 'S256',
|
|
155
|
+
});
|
|
156
|
+
assert.equal(created.statusCode, 201);
|
|
157
|
+
assert.equal(created.json().expires_in, 600);
|
|
158
|
+
const authorizationId = String(created.json().authorization_id);
|
|
159
|
+
const authorizeUrl = new URL(String(created.json().authorization_url));
|
|
160
|
+
assert.equal(authorizeUrl.origin, 'https://tenant.example.com');
|
|
161
|
+
assert.equal(authorizeUrl.searchParams.get('from'), 'hub');
|
|
162
|
+
assert.equal(authorizeUrl.searchParams.get('authorization_id'), authorizationId);
|
|
163
|
+
|
|
164
|
+
const autoRoute = await call(store, 'POST', '/agent-auth/v1/authorizations', {
|
|
165
|
+
client_app_id: client.app_id,
|
|
166
|
+
redirect_uri: 'http://127.0.0.1:43124/callback',
|
|
167
|
+
state: 'state-87654321',
|
|
168
|
+
requested_routes: ['auto'],
|
|
169
|
+
device_label: 'Mac mini',
|
|
170
|
+
code_challenge: pkceChallenge(verifier),
|
|
171
|
+
code_challenge_method: 'S256',
|
|
172
|
+
});
|
|
173
|
+
assert.equal(autoRoute.statusCode, 400);
|
|
174
|
+
const wildcardRoute = await call(store, 'POST', '/agent-auth/v1/authorizations', {
|
|
175
|
+
client_app_id: client.app_id,
|
|
176
|
+
redirect_uri: 'http://127.0.0.1:43126/callback',
|
|
177
|
+
state: 'state-66778899',
|
|
178
|
+
requested_routes: ['*'],
|
|
179
|
+
device_label: 'Mac mini',
|
|
180
|
+
code_challenge: pkceChallenge(verifier),
|
|
181
|
+
code_challenge_method: 'S256',
|
|
182
|
+
});
|
|
183
|
+
assert.equal(wildcardRoute.statusCode, 400);
|
|
184
|
+
|
|
185
|
+
rateLimited = true;
|
|
186
|
+
const throttled = await call(store, 'POST', '/agent-auth/v1/authorizations', {
|
|
187
|
+
client_app_id: client.app_id,
|
|
188
|
+
redirect_uri: 'http://127.0.0.1:43125/callback',
|
|
189
|
+
state: 'state-11223344',
|
|
190
|
+
requested_routes: ['orders'],
|
|
191
|
+
device_label: 'Mac mini',
|
|
192
|
+
code_challenge: pkceChallenge(verifier),
|
|
193
|
+
code_challenge_method: 'S256',
|
|
194
|
+
});
|
|
195
|
+
assert.equal(throttled.statusCode, 429);
|
|
196
|
+
rateLimited = false;
|
|
197
|
+
|
|
198
|
+
const queryToken = await call(store, 'GET', `/agent-auth/v1/authorizations/${authorizationId}?token=${encodeURIComponent(client.token)}`);
|
|
199
|
+
assert.equal(queryToken.statusCode, 401);
|
|
200
|
+
const context = await call(store, 'GET', `/agent-auth/v1/authorizations/${authorizationId}`, undefined, { authorization: `Bearer ${client.token}` });
|
|
201
|
+
assert.equal(context.statusCode, 200);
|
|
202
|
+
assert.deepEqual(context.json(), {
|
|
203
|
+
authorization_id: authorizationId,
|
|
204
|
+
client: { app_id: client.app_id, name: client.name },
|
|
205
|
+
device: { name: 'Mac mini' },
|
|
206
|
+
requested_routes: ['orders'],
|
|
207
|
+
status: 'pending',
|
|
208
|
+
expires_at: authorization!.expires_at,
|
|
209
|
+
});
|
|
210
|
+
for (const secretField of ['redirect_uri', 'state', 'code_challenge']) assert.equal(secretField in context.json(), false);
|
|
211
|
+
|
|
212
|
+
const approveAuto = await call(store, 'POST', `/agent-auth/v1/authorizations/${authorizationId}/approve`, {
|
|
213
|
+
principal: { id: 'user-7', tenant: 'tenant-2', roles: ['manager'] },
|
|
214
|
+
on_behalf_of: 'tenant-2:user-7',
|
|
215
|
+
allowed_routes: ['auto'],
|
|
216
|
+
}, { authorization: `Bearer ${client.token}` });
|
|
217
|
+
assert.equal(approveAuto.statusCode, 400);
|
|
218
|
+
const approveWildcard = await call(store, 'POST', `/agent-auth/v1/authorizations/${authorizationId}/approve`, {
|
|
219
|
+
principal: { id: 'user-7', tenant: 'tenant-2', roles: ['manager'] },
|
|
220
|
+
on_behalf_of: 'tenant-2:user-7',
|
|
221
|
+
allowed_routes: ['*'],
|
|
222
|
+
}, { authorization: `Bearer ${client.token}` });
|
|
223
|
+
assert.equal(approveWildcard.statusCode, 400);
|
|
224
|
+
|
|
225
|
+
const approved = await call(store, 'POST', `/agent-auth/v1/authorizations/${authorizationId}/approve`, {
|
|
226
|
+
principal: { id: 'user-7', tenant: 'tenant-2', roles: ['manager'] },
|
|
227
|
+
on_behalf_of: 'tenant-2:user-7',
|
|
228
|
+
allowed_routes: ['orders'],
|
|
229
|
+
}, { authorization: `Bearer ${client.token}` });
|
|
230
|
+
assert.equal(approved.statusCode, 200);
|
|
231
|
+
assert.match(approvedCodeHash, /^[a-f0-9]{64}$/);
|
|
232
|
+
assert.ok(Date.parse(authorization!.code_expires_at!) - Date.now() <= 120_000);
|
|
233
|
+
const redirect = new URL(String(approved.json().redirect_uri));
|
|
234
|
+
const code = String(redirect.searchParams.get('code'));
|
|
235
|
+
assert.equal(redirect.origin + redirect.pathname, 'http://127.0.0.1:43123/callback');
|
|
236
|
+
assert.equal(redirect.searchParams.get('local'), '1');
|
|
237
|
+
assert.equal(redirect.searchParams.get('state'), 'state-12345678');
|
|
238
|
+
assert.equal(tokenHash(code), approvedCodeHash);
|
|
239
|
+
|
|
240
|
+
const mixedUp = await call(store, 'POST', '/agent-auth/v1/token', {
|
|
241
|
+
grant_type: 'authorization_code', client_app_id: otherClient.app_id, code, redirect_uri: redirectUri, code_verifier: verifier,
|
|
242
|
+
});
|
|
243
|
+
assert.equal(mixedUp.statusCode, 400);
|
|
244
|
+
assert.equal(mixedUp.json().error, 'invalid_grant');
|
|
245
|
+
|
|
246
|
+
const token = await call(store, 'POST', '/agent-auth/v1/token', {
|
|
247
|
+
grant_type: 'authorization_code', client_app_id: client.app_id, code, redirect_uri: redirectUri, code_verifier: verifier,
|
|
248
|
+
});
|
|
249
|
+
assert.equal(token.statusCode, 200);
|
|
250
|
+
assert.equal(token.headers['cache-control'], 'no-store');
|
|
251
|
+
assert.equal(token.headers['pragma'], 'no-cache');
|
|
252
|
+
assert.deepEqual(Object.keys(token.json()).sort(), ['access_token', 'client_app_id', 'expires_in', 'refresh_expires_in', 'refresh_token', 'session_id', 'token_type'].sort());
|
|
253
|
+
const accessToken = String(token.json().access_token);
|
|
254
|
+
|
|
255
|
+
const queryAccess = await call(store, 'GET', `/agent-auth/v1/session?token=${encodeURIComponent(accessToken)}`);
|
|
256
|
+
assert.equal(queryAccess.statusCode, 401);
|
|
257
|
+
const current = await call(store, 'GET', '/agent-auth/v1/session', undefined, { authorization: `Bearer ${accessToken}` });
|
|
258
|
+
assert.equal(current.statusCode, 200);
|
|
259
|
+
assert.equal(current.json().principal.id, 'user-7');
|
|
260
|
+
assert.equal(current.json().on_behalf_of, 'tenant-2:user-7');
|
|
261
|
+
|
|
262
|
+
const savedAuthorizeUrl = client.agent_authorize_url;
|
|
263
|
+
client.agent_authorize_url = 'http://business.example.com/agent-authorize';
|
|
264
|
+
const invalidConfig = await call(store, 'GET', '/agent-auth/v1/session', undefined, { authorization: `Bearer ${accessToken}` });
|
|
265
|
+
assert.equal(invalidConfig.statusCode, 401);
|
|
266
|
+
client.agent_authorize_url = savedAuthorizeUrl;
|
|
267
|
+
client.enabled = false;
|
|
268
|
+
const disabledClient = await call(store, 'GET', '/agent-auth/v1/session', undefined, { authorization: `Bearer ${accessToken}` });
|
|
269
|
+
assert.equal(disabledClient.statusCode, 401);
|
|
270
|
+
client.enabled = true;
|
|
271
|
+
|
|
272
|
+
const revokedByBusiness = await call(store, 'POST', `/agent-auth/v1/sessions/${token.json().session_id}/revoke`, {}, { authorization: `Bearer ${client.token}` });
|
|
273
|
+
assert.equal(revokedByBusiness.statusCode, 200);
|
|
274
|
+
const afterRevoke = await call(store, 'GET', '/agent-auth/v1/session', undefined, { authorization: `Bearer ${accessToken}` });
|
|
275
|
+
assert.equal(afterRevoke.statusCode, 401);
|
|
276
|
+
});
|
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
2
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
3
|
+
import { namedRateLimitedFor } from '../app/auth';
|
|
4
|
+
import { ipOf, readBody, send } from '../app/http';
|
|
5
|
+
import type { AgentBusinessPrincipal, AgentSession, Client } from '../core/contracts/types';
|
|
6
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
7
|
+
|
|
8
|
+
export const AGENT_AUTHORIZATION_TTL_SEC = 10 * 60;
|
|
9
|
+
export const AGENT_AUTHORIZATION_CODE_TTL_SEC = 2 * 60;
|
|
10
|
+
export const AGENT_ACCESS_TTL_SEC = 15 * 60;
|
|
11
|
+
export const AGENT_REFRESH_TTL_SEC = 30 * 24 * 60 * 60;
|
|
12
|
+
|
|
13
|
+
const RESOURCE_RE = /^[a-z0-9][a-z0-9_-]{1,63}$/;
|
|
14
|
+
const PKCE_CHALLENGE_RE = /^[A-Za-z0-9_-]{43}$/;
|
|
15
|
+
const PKCE_VERIFIER_RE = /^[A-Za-z0-9._~-]{43,128}$/;
|
|
16
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
17
|
+
|
|
18
|
+
type RecordValue = Record<string, unknown>;
|
|
19
|
+
|
|
20
|
+
export interface AgentAuthHttpDeps {
|
|
21
|
+
configStore: ConfigStoreContract | null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function record(value: unknown): RecordValue | null {
|
|
25
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value as RecordValue : null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function allowedFields(value: RecordValue, fields: readonly string[]): boolean {
|
|
29
|
+
const known = new Set(fields);
|
|
30
|
+
return Object.keys(value).every((key) => known.has(key));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function stringList(value: unknown): string[] | null {
|
|
34
|
+
if (!Array.isArray(value) || value.length < 1 || value.length > 64) return null;
|
|
35
|
+
const items = value.map((item) => typeof item === 'string' ? item.trim() : '');
|
|
36
|
+
if (items.some((item) => !item || item === 'auto' || item === '*' || !RESOURCE_RE.test(item))) return null;
|
|
37
|
+
const unique = [...new Set(items)];
|
|
38
|
+
return unique.length === items.length ? unique : null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function hasStrictLoopbackHttpAuthority(value: string): boolean {
|
|
42
|
+
const match = /^http:\/\/(?:127\.0\.0\.1|\[::1\]):([0-9]{1,5})(?:[/?#]|$)/i.exec(value);
|
|
43
|
+
if (!match) return false;
|
|
44
|
+
const port = Number(match[1]);
|
|
45
|
+
return Number.isInteger(port) && port >= 1 && port <= 65535;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function isAgentAuthorizeUrl(value: string): boolean {
|
|
49
|
+
try {
|
|
50
|
+
const url = new URL(value);
|
|
51
|
+
const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
|
52
|
+
const loopbackDev = hasStrictLoopbackHttpAuthority(value) && (hostname === '127.0.0.1' || hostname === '::1');
|
|
53
|
+
return (url.protocol === 'https:' || loopbackDev) && !url.username && !url.password && !url.hash;
|
|
54
|
+
} catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function isLoopbackRedirectUri(value: string): boolean {
|
|
60
|
+
if (!value || value.length > 2048) return false;
|
|
61
|
+
try {
|
|
62
|
+
const url = new URL(value);
|
|
63
|
+
const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
|
64
|
+
const loopback = hostname === '127.0.0.1' || hostname === '::1';
|
|
65
|
+
return url.protocol === 'http:' && loopback && hasStrictLoopbackHttpAuthority(value) && !url.username && !url.password && !url.hash;
|
|
66
|
+
} catch {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function tokenHash(value: string): string {
|
|
72
|
+
return createHash('sha256').update(value, 'utf8').digest('hex');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function pkceChallenge(codeVerifier: string): string {
|
|
76
|
+
return createHash('sha256').update(codeVerifier, 'ascii').digest('base64url');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function randomSecret(prefix: 'bha' | 'bhr' | 'bhc'): string {
|
|
80
|
+
return `${prefix}_${randomBytes(32).toString('base64url')}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function authorizationUrl(base: string, authorizationId: string): string | null {
|
|
84
|
+
if (!isAgentAuthorizeUrl(base) || base.length > 2048) return null;
|
|
85
|
+
const url = new URL(base);
|
|
86
|
+
url.searchParams.set('authorization_id', authorizationId);
|
|
87
|
+
return url.toString();
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function redirectResult(base: string, result: { code?: string; error?: string }, state: string): string {
|
|
91
|
+
const url = new URL(base);
|
|
92
|
+
url.searchParams.delete('code');
|
|
93
|
+
url.searchParams.delete('error');
|
|
94
|
+
if (result.code) url.searchParams.set('code', result.code);
|
|
95
|
+
if (result.error) url.searchParams.set('error', result.error);
|
|
96
|
+
url.searchParams.set('state', state);
|
|
97
|
+
return url.toString();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function clientAllowsRoute(client: Client, route: string): boolean {
|
|
101
|
+
return client.allowed_routes.includes('*') || client.allowed_routes.includes(route);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function requestedAllowsRoute(requested: string[], route: string): boolean {
|
|
105
|
+
return requested.includes('*') || requested.includes(route);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function parsePrincipal(value: unknown): AgentBusinessPrincipal | null {
|
|
109
|
+
const item = record(value);
|
|
110
|
+
if (!item || !allowedFields(item, ['id', 'tenant', 'roles', 'audience', 'channel'])) return null;
|
|
111
|
+
const id = typeof item['id'] === 'string' ? item['id'].trim() : '';
|
|
112
|
+
const tenant = typeof item['tenant'] === 'string' ? item['tenant'].trim() : '';
|
|
113
|
+
const audience = typeof item['audience'] === 'string' ? item['audience'].trim() : '';
|
|
114
|
+
const channel = typeof item['channel'] === 'string' ? item['channel'].trim() : '';
|
|
115
|
+
const roles = Array.isArray(item['roles'])
|
|
116
|
+
? item['roles'].map((role) => typeof role === 'string' ? role.trim() : '')
|
|
117
|
+
: [];
|
|
118
|
+
if (!id || id.length > 128 || tenant.length > 128 || audience.length > 64 || channel.length > 128 ||
|
|
119
|
+
roles.length > 64 || roles.some((role) => !role || role.length > 64)) return null;
|
|
120
|
+
return {
|
|
121
|
+
id,
|
|
122
|
+
...(tenant ? { tenant } : {}),
|
|
123
|
+
roles: [...new Set(roles)],
|
|
124
|
+
...(audience ? { audience } : {}),
|
|
125
|
+
...(channel ? { channel } : {}),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async function businessClient(deps: AgentAuthHttpDeps, req: IncomingMessage, url: URL): Promise<Client | null> {
|
|
130
|
+
const token = bearerToken(req);
|
|
131
|
+
if (!token || !deps.configStore) return null;
|
|
132
|
+
const client = await deps.configStore.clients.getByToken(token);
|
|
133
|
+
return client?.enabled ? client : null;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function bearerToken(req: IncomingMessage): string {
|
|
137
|
+
const header = (req.headers['authorization'] ?? '').toString();
|
|
138
|
+
const match = /^Bearer ([^\s]+)$/i.exec(header);
|
|
139
|
+
return match?.[1] ?? '';
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function publicSession(session: AgentSession): RecordValue {
|
|
143
|
+
return {
|
|
144
|
+
session_id: session.session_id,
|
|
145
|
+
client_app_id: session.client_app_id,
|
|
146
|
+
device_label: session.device_label,
|
|
147
|
+
principal: session.principal,
|
|
148
|
+
on_behalf_of: session.on_behalf_of,
|
|
149
|
+
allowed_routes: session.allowed_routes,
|
|
150
|
+
created_at: session.created_at,
|
|
151
|
+
expires_at: session.access_expires_at,
|
|
152
|
+
refresh_expires_at: session.refresh_expires_at,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function createAuthorization(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
157
|
+
if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
|
|
158
|
+
const body = record(await readBody(req).catch(() => null));
|
|
159
|
+
if (!body || !allowedFields(body, ['client_app_id', 'redirect_uri', 'state', 'requested_routes', 'device_label', 'code_challenge', 'code_challenge_method'])) {
|
|
160
|
+
send(res, 400, { error: 'invalid_request' }); return;
|
|
161
|
+
}
|
|
162
|
+
const clientAppId = typeof body['client_app_id'] === 'string' ? body['client_app_id'].trim() : '';
|
|
163
|
+
const redirectUri = typeof body['redirect_uri'] === 'string' ? body['redirect_uri'] : '';
|
|
164
|
+
const state = typeof body['state'] === 'string' ? body['state'] : '';
|
|
165
|
+
const requestedRoutes = stringList(body['requested_routes']);
|
|
166
|
+
const deviceLabel = typeof body['device_label'] === 'string' ? body['device_label'].trim() : '';
|
|
167
|
+
const codeChallenge = typeof body['code_challenge'] === 'string' ? body['code_challenge'] : '';
|
|
168
|
+
if (!RESOURCE_RE.test(clientAppId) || !isLoopbackRedirectUri(redirectUri) || state.length < 8 || state.length > 512 ||
|
|
169
|
+
!requestedRoutes || !deviceLabel || deviceLabel.length > 128 || !PKCE_CHALLENGE_RE.test(codeChallenge) || body['code_challenge_method'] !== 'S256') {
|
|
170
|
+
send(res, 400, { error: 'invalid_request' }); return;
|
|
171
|
+
}
|
|
172
|
+
const client = await deps.configStore.clients.get(clientAppId);
|
|
173
|
+
if (!client?.enabled || !client.agent_authorize_url || requestedRoutes.some((route) => !clientAllowsRoute(client, route))) {
|
|
174
|
+
send(res, 400, { error: 'invalid_client' }); return;
|
|
175
|
+
}
|
|
176
|
+
if (await namedRateLimitedFor(deps.configStore, `agent-auth:create:${clientAppId}:${ipOf(req)}`, 10, 60)) {
|
|
177
|
+
send(res, 429, { error: 'rate_limited' }); return;
|
|
178
|
+
}
|
|
179
|
+
const authorizationId = randomUUID();
|
|
180
|
+
const authorizeUrl = authorizationUrl(client.agent_authorize_url, authorizationId);
|
|
181
|
+
if (!authorizeUrl) { send(res, 503, { error: 'agent_authorize_url_invalid' }); return; }
|
|
182
|
+
const expiresAt = new Date(Date.now() + AGENT_AUTHORIZATION_TTL_SEC * 1000).toISOString();
|
|
183
|
+
await deps.configStore.agentAuth.createAuthorization({
|
|
184
|
+
authorizationId,
|
|
185
|
+
clientAppId,
|
|
186
|
+
redirectUri,
|
|
187
|
+
state,
|
|
188
|
+
requestedRoutes,
|
|
189
|
+
deviceLabel,
|
|
190
|
+
codeChallenge,
|
|
191
|
+
expiresAt,
|
|
192
|
+
});
|
|
193
|
+
send(res, 201, { authorization_id: authorizationId, authorization_url: authorizeUrl, expires_in: AGENT_AUTHORIZATION_TTL_SEC });
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function authorizationContext(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL, authorizationId: string): Promise<void> {
|
|
197
|
+
if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
|
|
198
|
+
const client = await businessClient(deps, req, url);
|
|
199
|
+
if (!client) { send(res, 401, { error: 'unauthorized' }); return; }
|
|
200
|
+
const item = await deps.configStore.agentAuth.getAuthorization(authorizationId);
|
|
201
|
+
if (!item || item.client_app_id !== client.app_id) { send(res, 404, { error: 'not_found' }); return; }
|
|
202
|
+
const status = item.status === 'pending' && Date.parse(item.expires_at) <= Date.now() ? 'expired' : item.status;
|
|
203
|
+
send(res, 200, {
|
|
204
|
+
authorization_id: item.authorization_id,
|
|
205
|
+
client: { app_id: client.app_id, name: client.name },
|
|
206
|
+
device: { name: item.device_label },
|
|
207
|
+
requested_routes: item.requested_routes,
|
|
208
|
+
status,
|
|
209
|
+
expires_at: item.expires_at,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async function approveAuthorization(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL, authorizationId: string): Promise<void> {
|
|
214
|
+
if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
|
|
215
|
+
const client = await businessClient(deps, req, url);
|
|
216
|
+
if (!client) { send(res, 401, { error: 'unauthorized' }); return; }
|
|
217
|
+
const body = record(await readBody(req).catch(() => null));
|
|
218
|
+
if (!body || !allowedFields(body, ['principal', 'on_behalf_of', 'allowed_routes'])) { send(res, 400, { error: 'invalid_request' }); return; }
|
|
219
|
+
const principal = parsePrincipal(body['principal']);
|
|
220
|
+
const onBehalfOf = typeof body['on_behalf_of'] === 'string' ? body['on_behalf_of'].trim() : '';
|
|
221
|
+
const allowedRoutes = stringList(body['allowed_routes']);
|
|
222
|
+
if (!principal || !onBehalfOf || onBehalfOf.length > 191 || !allowedRoutes) { send(res, 400, { error: 'invalid_request' }); return; }
|
|
223
|
+
const pending = await deps.configStore.agentAuth.getAuthorization(authorizationId);
|
|
224
|
+
if (!pending || pending.client_app_id !== client.app_id) { send(res, 404, { error: 'not_found' }); return; }
|
|
225
|
+
if (allowedRoutes.some((route) => !requestedAllowsRoute(pending.requested_routes, route) || !clientAllowsRoute(client, route))) {
|
|
226
|
+
send(res, 403, { error: 'route_not_allowed' }); return;
|
|
227
|
+
}
|
|
228
|
+
const code = randomSecret('bhc');
|
|
229
|
+
const result = await deps.configStore.agentAuth.approveAuthorization({
|
|
230
|
+
authorizationId,
|
|
231
|
+
clientAppId: client.app_id,
|
|
232
|
+
principal: { ...principal },
|
|
233
|
+
onBehalfOf,
|
|
234
|
+
allowedRoutes,
|
|
235
|
+
codeHash: tokenHash(code),
|
|
236
|
+
codeExpiresAt: new Date(Date.now() + AGENT_AUTHORIZATION_CODE_TTL_SEC * 1000).toISOString(),
|
|
237
|
+
});
|
|
238
|
+
if (!result.ok) {
|
|
239
|
+
const status = result.reason === 'not_found' || result.reason === 'wrong_client' ? 404 : result.reason === 'expired' ? 410 : 409;
|
|
240
|
+
send(res, status, { error: result.reason }); return;
|
|
241
|
+
}
|
|
242
|
+
send(res, 200, { redirect_uri: redirectResult(result.authorization.redirect_uri, { code }, result.authorization.state) });
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function denyAuthorization(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL, authorizationId: string): Promise<void> {
|
|
246
|
+
if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
|
|
247
|
+
const client = await businessClient(deps, req, url);
|
|
248
|
+
if (!client) { send(res, 401, { error: 'unauthorized' }); return; }
|
|
249
|
+
const body = record(await readBody(req).catch(() => ({}))) ?? {};
|
|
250
|
+
if (!allowedFields(body, [])) { send(res, 400, { error: 'invalid_request' }); return; }
|
|
251
|
+
const result = await deps.configStore.agentAuth.denyAuthorization({ authorizationId, clientAppId: client.app_id });
|
|
252
|
+
if (!result.ok) {
|
|
253
|
+
const status = result.reason === 'not_found' || result.reason === 'wrong_client' ? 404 : result.reason === 'expired' ? 410 : 409;
|
|
254
|
+
send(res, status, { error: result.reason }); return;
|
|
255
|
+
}
|
|
256
|
+
send(res, 200, { redirect_uri: redirectResult(result.authorization.redirect_uri, { error: 'access_denied' }, result.authorization.state) });
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function tokenResponse(session: AgentSession, accessToken: string, refreshToken: string): RecordValue {
|
|
260
|
+
return {
|
|
261
|
+
token_type: 'Bearer',
|
|
262
|
+
access_token: accessToken,
|
|
263
|
+
expires_in: AGENT_ACCESS_TTL_SEC,
|
|
264
|
+
refresh_token: refreshToken,
|
|
265
|
+
refresh_expires_in: Math.max(0, Math.floor((Date.parse(session.refresh_expires_at) - Date.now()) / 1000)),
|
|
266
|
+
session_id: session.session_id,
|
|
267
|
+
client_app_id: session.client_app_id,
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
async function exchangeToken(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
272
|
+
if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
|
|
273
|
+
const body = record(await readBody(req).catch(() => null));
|
|
274
|
+
if (!body || typeof body['grant_type'] !== 'string') { send(res, 400, { error: 'invalid_request' }); return; }
|
|
275
|
+
const clientAppId = typeof body['client_app_id'] === 'string' ? body['client_app_id'].trim() : '';
|
|
276
|
+
if (!RESOURCE_RE.test(clientAppId)) { send(res, 400, { error: 'invalid_request' }); return; }
|
|
277
|
+
const client = await deps.configStore.clients.get(clientAppId);
|
|
278
|
+
if (!client?.enabled || !client.agent_authorize_url || !isAgentAuthorizeUrl(client.agent_authorize_url)) { send(res, 400, { error: 'invalid_grant' }); return; }
|
|
279
|
+
const accessToken = randomSecret('bha');
|
|
280
|
+
const refreshToken = randomSecret('bhr');
|
|
281
|
+
const accessExpiresAt = new Date(Date.now() + AGENT_ACCESS_TTL_SEC * 1000).toISOString();
|
|
282
|
+
const refreshExpiresAt = new Date(Date.now() + AGENT_REFRESH_TTL_SEC * 1000).toISOString();
|
|
283
|
+
|
|
284
|
+
if (body['grant_type'] === 'authorization_code') {
|
|
285
|
+
if (!allowedFields(body, ['grant_type', 'client_app_id', 'code', 'redirect_uri', 'code_verifier'])) { send(res, 400, { error: 'invalid_request' }); return; }
|
|
286
|
+
const code = typeof body['code'] === 'string' ? body['code'] : '';
|
|
287
|
+
const redirectUri = typeof body['redirect_uri'] === 'string' ? body['redirect_uri'] : '';
|
|
288
|
+
const verifier = typeof body['code_verifier'] === 'string' ? body['code_verifier'] : '';
|
|
289
|
+
if (!code.startsWith('bhc_') || code.length < 40 || !isLoopbackRedirectUri(redirectUri) || !PKCE_VERIFIER_RE.test(verifier)) {
|
|
290
|
+
send(res, 400, { error: 'invalid_grant' }); return;
|
|
291
|
+
}
|
|
292
|
+
const result = await deps.configStore.agentAuth.exchangeAuthorizationCode({
|
|
293
|
+
codeHash: tokenHash(code),
|
|
294
|
+
clientAppId,
|
|
295
|
+
redirectUri,
|
|
296
|
+
codeChallenge: pkceChallenge(verifier),
|
|
297
|
+
sessionId: randomUUID(),
|
|
298
|
+
accessTokenHash: tokenHash(accessToken),
|
|
299
|
+
refreshTokenHash: tokenHash(refreshToken),
|
|
300
|
+
accessExpiresAt,
|
|
301
|
+
refreshExpiresAt,
|
|
302
|
+
});
|
|
303
|
+
if (!result.ok) { send(res, 400, { error: 'invalid_grant' }); return; }
|
|
304
|
+
send(res, 200, tokenResponse(result.session, accessToken, refreshToken));
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
if (body['grant_type'] === 'refresh_token') {
|
|
309
|
+
if (!allowedFields(body, ['grant_type', 'client_app_id', 'refresh_token'])) { send(res, 400, { error: 'invalid_request' }); return; }
|
|
310
|
+
const current = typeof body['refresh_token'] === 'string' ? body['refresh_token'] : '';
|
|
311
|
+
if (!current.startsWith('bhr_') || current.length < 40) { send(res, 400, { error: 'invalid_grant' }); return; }
|
|
312
|
+
const result = await deps.configStore.agentAuth.rotateRefreshToken({
|
|
313
|
+
refreshTokenHash: tokenHash(current),
|
|
314
|
+
clientAppId,
|
|
315
|
+
accessTokenHash: tokenHash(accessToken),
|
|
316
|
+
nextRefreshTokenHash: tokenHash(refreshToken),
|
|
317
|
+
accessExpiresAt,
|
|
318
|
+
});
|
|
319
|
+
if (!result.ok) { send(res, 400, { error: 'invalid_grant' }); return; }
|
|
320
|
+
send(res, 200, tokenResponse(result.session, accessToken, refreshToken));
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
send(res, 400, { error: 'unsupported_grant_type' });
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
export async function authenticateAgentAccess(deps: AgentAuthHttpDeps, req: IncomingMessage, url: URL): Promise<{ session: AgentSession; client: Client } | null> {
|
|
328
|
+
if (!deps.configStore?.agentAuth) return null;
|
|
329
|
+
const token = bearerToken(req);
|
|
330
|
+
if (!token.startsWith('bha_') || token.length < 40) return null;
|
|
331
|
+
const session = await deps.configStore.agentAuth.getSessionByAccessHash(tokenHash(token));
|
|
332
|
+
if (!session) return null;
|
|
333
|
+
const client = await deps.configStore.clients.get(session.client_app_id);
|
|
334
|
+
return client?.enabled && client.agent_authorize_url && isAgentAuthorizeUrl(client.agent_authorize_url) ? { session, client } : null;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async function readSession(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL): Promise<void> {
|
|
338
|
+
const auth = await authenticateAgentAccess(deps, req, url);
|
|
339
|
+
if (!auth) { send(res, 401, { error: 'unauthorized' }); return; }
|
|
340
|
+
send(res, 200, publicSession(auth.session));
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async function revokeSession(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL): Promise<void> {
|
|
344
|
+
if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
|
|
345
|
+
const token = bearerToken(req);
|
|
346
|
+
if (token) {
|
|
347
|
+
if (!token.startsWith('bha_')) { send(res, 401, { error: 'unauthorized' }); return; }
|
|
348
|
+
await deps.configStore.agentAuth.revokeByAccessHash(tokenHash(token));
|
|
349
|
+
send(res, 200, { revoked: true });
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
const body = record(await readBody(req).catch(() => null));
|
|
353
|
+
if (!body || !allowedFields(body, ['client_app_id', 'refresh_token'])) { send(res, 400, { error: 'invalid_request' }); return; }
|
|
354
|
+
const clientAppId = typeof body['client_app_id'] === 'string' ? body['client_app_id'].trim() : '';
|
|
355
|
+
const refreshToken = typeof body['refresh_token'] === 'string' ? body['refresh_token'] : '';
|
|
356
|
+
if (!RESOURCE_RE.test(clientAppId) || !refreshToken.startsWith('bhr_')) { send(res, 400, { error: 'invalid_request' }); return; }
|
|
357
|
+
await deps.configStore.agentAuth.revokeByRefreshHash(clientAppId, tokenHash(refreshToken));
|
|
358
|
+
send(res, 200, { revoked: true });
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
async function businessRevokeSession(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL, sessionId: string): Promise<void> {
|
|
362
|
+
if (!deps.configStore?.agentAuth) { send(res, 503, { error: 'agent_auth_unavailable' }); return; }
|
|
363
|
+
const client = await businessClient(deps, req, url);
|
|
364
|
+
if (!client) { send(res, 401, { error: 'unauthorized' }); return; }
|
|
365
|
+
if (!UUID_RE.test(sessionId)) { send(res, 404, { error: 'not_found' }); return; }
|
|
366
|
+
const revoked = await deps.configStore.agentAuth.revokeSessionForClient(client.app_id, sessionId);
|
|
367
|
+
if (!revoked) { send(res, 404, { error: 'not_found' }); return; }
|
|
368
|
+
send(res, 200, { revoked: true });
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** Returns true when the request belongs to the dedicated Agent Auth surface. */
|
|
372
|
+
export async function handleAgentAuthHttpFor(deps: AgentAuthHttpDeps, req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> {
|
|
373
|
+
const method = req.method ?? 'GET';
|
|
374
|
+
const path = url.pathname;
|
|
375
|
+
if (!path.startsWith('/agent-auth/')) return false;
|
|
376
|
+
res.setHeader('cache-control', 'no-store');
|
|
377
|
+
if (path === '/agent-auth/v1/token') res.setHeader('pragma', 'no-cache');
|
|
378
|
+
if (method === 'POST' && path === '/agent-auth/v1/authorizations') { await createAuthorization(deps, req, res); return true; }
|
|
379
|
+
const authorizationMatch = path.match(/^\/agent-auth\/v1\/authorizations\/([0-9a-f-]{36})(?:\/(approve|deny))?$/i);
|
|
380
|
+
if (authorizationMatch) {
|
|
381
|
+
const id = authorizationMatch[1]!;
|
|
382
|
+
const action = authorizationMatch[2];
|
|
383
|
+
if (!UUID_RE.test(id)) { send(res, 404, { error: 'not_found' }); return true; }
|
|
384
|
+
if (method === 'GET' && !action) { await authorizationContext(deps, req, res, url, id); return true; }
|
|
385
|
+
if (method === 'POST' && action === 'approve') { await approveAuthorization(deps, req, res, url, id); return true; }
|
|
386
|
+
if (method === 'POST' && action === 'deny') { await denyAuthorization(deps, req, res, url, id); return true; }
|
|
387
|
+
send(res, 405, { error: 'method_not_allowed' }); return true;
|
|
388
|
+
}
|
|
389
|
+
if (method === 'POST' && path === '/agent-auth/v1/token') { await exchangeToken(deps, req, res); return true; }
|
|
390
|
+
if (method === 'GET' && path === '/agent-auth/v1/session') { await readSession(deps, req, res, url); return true; }
|
|
391
|
+
if (method === 'POST' && path === '/agent-auth/v1/revoke') { await revokeSession(deps, req, res, url); return true; }
|
|
392
|
+
const revokeMatch = method === 'POST' ? path.match(/^\/agent-auth\/v1\/sessions\/([0-9a-f-]{36})\/revoke$/i) : null;
|
|
393
|
+
if (revokeMatch) { await businessRevokeSession(deps, req, res, url, revokeMatch[1]!); return true; }
|
|
394
|
+
send(res, 404, { error: 'not_found' }); return true;
|
|
395
|
+
}
|