# API 认证

根据 client 和 API surface，选择 OAuth 或 scoped environment-secret handoff。

- Canonical: https://docs.xmemo.dev/zh/docs/api/authentication
- Locale: zh-CN
- Content-Locale: zh-CN
- Canonical-Content-Digest: 2ccb101521e35878569be22c158ebf3f733f976c32f1b7952809dc29ffb5dba5
- Edition-Digest: e7aea915e02831befd370eedf716c233e0dcdd7896dba07d0b2326f10c91e543
- Source-Revision: sha256:0f4e5aaa7eba4f6a045f2818119002c0ddba188a30db4cee7ebfd8a2164d3e96

## 两种 authenticated surface

hosted MCP endpoint 和 REST API 使用不同的认证方式。选择与你正在接入的 client 相匹配的一种，绝不要把 credential 放入 public configuration 或生成的 URL。

- MCP — client 支持时使用 OAuth，否则使用 Authorization: Bearer ${XMEMO_KEY}。
- REST data plane — X-API-Key: <your-assigned-api-key>（server 也接受 Authorization: Bearer <token>）。在满足 onboarding 条件和每日 IP 配额的前提下，POST /v1/agents/temporary-register 允许匿名注册。
- Identity headers 仅用于 attribution，不授予 access。

## Base URL

将 BASE_URL 设为 deployment origin。hosted product 使用 https://xmemo.dev；已提交的 OpenAPI document 还声明了用于 local development 的 http://localhost:8000，以及作为示例 server 的 https://api.memory-os.example.com。REST data-plane calls 使用 /v1 paths。

```bash
BASE_URL="${BASE_URL:-https://xmemo.dev}"
curl -sS "$BASE_URL/v1/recall?query=connection%20check&limit=1" \
  -H "X-API-Key: $XMEMO_KEY"
```

## REST authentication header

大多数 REST requests 会携带 API key header。没有有效 credential 的 request 会在读取或写入任何 memory 之前被拒绝；POST /v1/agents/temporary-register 是文档化的 temporary registration 例外。提交的无效凭据将被拒绝。

```http
X-API-Key: <your-assigned-api-key>
```

## MCP authentication

OAuth clients 只需要 hosted server URL。未验证的动态客户端必须显式请求 memory 和 knowledge scopes；已验证的客户端在省略 scope 时仍保留现有默认行为。Grant 仅提供经批准的 scopes。Direct 和 headless clients 则从环境中读取 token。

```json
{
  "servers": {
    "XMemo": {
      "type": "http",
      "url": "https://xmemo.dev/mcp"
    }
  }
}
```

## Scopes

服务端分别独立评估凭据的 scope 与请求的 memory space。使用 memory:read 进行 recall、search、context、list 和项目读取；使用 memory:write 进行写入与修改。Knowledge 操作严格需要 knowledge:read，仅持 memory:read 会被返回 403 拒绝。高级直接 token 可使用更窄的能力，如 memory:update、memory:delete、memory:restore、memory:redact 或 memory:hard_delete。旧版 REST 别名 read:memories 和 write:memories 仍作为兼容值保留；scope 绝不会扩大 owner、团队或 token-space 的授权边界。

- 读取: memory:read。
- 写入: memory:write；当 token profile 支持时，mutation 操作可要求更窄的能力。
- Knowledge: knowledge:read；检索与列出 knowledge 严格需要此 scope（持 memory:read 会返回 403）。
- 项目/团队访问: token 的 owner 或绑定团队与实时角色必须同时授权所请求的 scope/team_id。
- Attribution headers 和 source 字段仅用于调用者归属识别；它们不是 scope，不会授予访问权限。

## Error schema

OpenAPI paths 为 request validation（422）声明 HTTPValidationError，其他大多数 response schemas 则保持 untyped。默认 REST error 仍是带有 detail value 的 JSON object。已识别的 authorization failures 也可以请求 RFC 9457-style application/problem+json；机器处理应使用 code field，而不要匹配 prose。

```json
{
  "detail": "invalid_token"
}

{
  "type": "urn:xmemo:problem:invalid_token",
  "title": "Invalid access token",
  "status": 401,
  "code": "invalid_token",
  "detail": "The presented access token is missing, expired, revoked, or otherwise invalid."
}
```

## Rate limits

OpenAPI 不发布 rate-limit quotas。启用时 runtime 使用 60 秒 fixed window（在 development/local/test 之外默认启用）：data-plane category 为每分钟 600 requests，memory writes 使用每分钟 180 次的 endpoint policy，memory search/recall/context reads 使用每分钟 300 次的 endpoint policy。Operators 可以通过 MEMORY_OS_RATE_LIMIT_* environment variables 覆盖这些值；不要在 client 中硬编码 quota。

- 429 response：{ detail: Rate limit exceeded, category, policy, limit, window_seconds, retry_after_seconds }。
- 429 headers：Retry-After、X-RateLimit-Limit、X-RateLimit-Remaining、X-RateLimit-Reset 和 X-RateLimit-Policy。
- 启用 limiter 时，成功 responses 也会暴露 X-RateLimit-* 的 limit、remaining、reset 和 policy headers。

