<!-- 来源: https://hostanagent.com/docs/integration/backend-auth/ | 协议: 1.0 | 更新: 2026-09-30 -->

# 产品登录、后端代理与用户隔离

接入方的产品仍负责确认“是谁”和“能做什么”。HostAnAgent 的应用 Key 只证明请求来自某个账号的应用；它不验证产品自己的登录会话、业务角色或资源 ACL。

## 最小服务端配置

产品服务器持有 `HAA_APPLICATION_KEY`，面向浏览器只提供自己的 `/api/agent/*` 代理。运行 Key 通常限制到目标 Agent，并含 `runtime:read`、`runtime:write`；执行工具时再加 `tools:execute`。变量只放服务端：

```dotenv
HAA_BACKEND_URL=https://api.hostanagent.com
HAA_APPLICATION_KEY=<从 API Keys 页面复制的一次性明文 Key>
PRODUCT_PUBLIC_ORIGIN=https://your-product.example
```

Node 产品先安装 `@hostanagent/client-core@0.2.5`。下面是完整的 `product-bridge.mjs` 代理工厂，只依赖该公开 npm 包；把返回的 Node 请求 handler 挂到产品服务器的 `/api/agent/*`。传入的身份和权限回调由产品实现：

```js
import { createProductBridge } from '@hostanagent/client-core/bridge';

export function productBridge({
  authenticateProductUser, canUseAgent, canExecuteTool, canUseExecutor,
  environment = process.env,
}) {
  return createProductBridge({
    endpoint: environment.HAA_BACKEND_URL || 'https://api.hostanagent.com',
    applicationKey: environment.HAA_APPLICATION_KEY,
    publicOrigin: environment.PRODUCT_PUBLIC_ORIGIN,
    async authenticate(request) {
      const user = await authenticateProductUser(request);
      if (!user) return null;
      return { subject: user.id, sessionId: user.loginSessionId, label: user.displayName };
    },
    authorizeAgent: (identity, agentId) => canUseAgent(identity.subject, agentId),
    authorizeTool: canExecuteTool && ((identity, call, operation) =>
      canExecuteTool(identity.subject, call, operation)),
    authorizeExecutor: canUseExecutor && ((identity, request) =>
      canUseExecutor(identity.subject, request)),
  });
}
```

调用 `productBridge({ authenticateProductUser, canUseAgent })` 时，前一个回调必须验证产品自己的 HttpOnly 登录 Cookie 并返回稳定用户 ID 与本次登录 Session ID；后一个回调每次读取当前 Agent ACL。这两个函数由你的服务实现，不是 SDK 内置对象。工具接入才传 `canExecuteTool`、`canUseExecutor`；缺失时执行路径保持拒绝。代理使用可信登录态生成 Subject，不能从请求正文、URL 或浏览器的自报 `user_id` 直接取值；身份切换时旧页面的 `X-Agent-Identity` 不能代替登录 Cookie。

工具 claim/receipt 和执行器连接还需显式 `authorizeTool`、`authorizeExecutor` 回调；未提供时相关路径保持拒绝。每次使用 Agent、资源或工具都重新检查产品 ACL，不能仅凭曾经签发的 Key 或页面按钮判断可操作。[ToolRunner](/docs/integration/tool-runner/)。

文本 Widget 只经代理读取运行发现，不能退回读取完整配置或在浏览器保存应用 Key。上线时先用自己的两名测试用户检查 Subject 隔离、Agent 范围与退出/切换身份；调试用模拟登录不能当作生产身份系统。
