# 鉴权与 API Key

每个请求都带上 API Key：服务端代码放在 `Authorization: Bearer <Key>` 请求头里；浏览器里的 WebSocket 不能设置请求头，改用 `api_key` 查询参数。

> Source: https://tokenearly.com/developers/authentication · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json

## 示例

下面每个示例都调用 `GET /v1/me`，它返回这把 Key 能读的主题、限额与 IP 白名单，适合用来验证 Key 是否配置正确。

**cURL**

```bash
curl "https://api.tokenearly.com/v1/me" \
  -H "Authorization: Bearer te_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Python**

```python
import os, requests

KEY = os.environ["TOKENEARLY_API_KEY"]          # te_live_...
resp = requests.get(
    "https://api.tokenearly.com/v1/me",
    headers={"Authorization": f"Bearer {KEY}"},
    timeout=10,
)
print(resp.status_code, resp.json())
```

**Node.js**

```javascript
// Node 18+ (built-in fetch)
async function main() {
  const resp = await fetch("https://api.tokenearly.com/v1/me", {
    headers: { Authorization: `Bearer ${process.env.TOKENEARLY_API_KEY}` },
  });
  console.log(resp.status, await resp.json());
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
```

**X-API-Key**

```bash
curl "https://api.tokenearly.com/v1/me" \
  -H "X-API-Key: te_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**WebSocket**

```python
import asyncio, os
import websockets  # pip install websockets

async def main():
    async with websockets.connect(
        "wss://api.tokenearly.com/v1/stream?topics=announcement.*,news.*",
        additional_headers={"Authorization": f"Bearer {os.environ['TOKENEARLY_API_KEY']}"},
    ) as ws:
        print(await ws.recv())   # {"op": "welcome", ...}

asyncio.run(main())
```

**Browser**

```javascript
// Browsers cannot set headers on WebSocket: pass the key as a query parameter.
// Only do this in tools you control; never ship a real key in public front-end code.
const ws = new WebSocket("wss://api.tokenearly.com/v1/stream?topics=announcement.*,news.*&api_key=te_live_...");
ws.onmessage = (e) => console.log(JSON.parse(e.data));
```

Key 缺失或无效时返回 401：

**401 响应**

```json
{
  "error": {
    "code": "invalid_api_key",
    "message": "This API key does not exist or has been revoked.",
    "docs": "https://tokenearly.com/en/developers/errors"
  }
}
```

## 三种传法

| 方式 | 示例 | 适用 |
|---|---|---|
| Authorization | `Authorization: Bearer te_live_…` | 推荐，REST、WebSocket、MCP 都支持 |
| X-API-Key | `X-API-Key: te_live_…` | 无法设置 Bearer 的工具 |
| api_key | `wss://…/v1/stream?api_key=te_live_…` | 仅限浏览器 WebSocket（浏览器不能设置请求头） |

## 创建 Key

1. 登录后打开[控制台 → 开发者 API](https://tokenearly.com/dashboard?tab=developer-api)。
2. 点「创建 API Key」，起个名字；需要的话填上 IP 白名单（可选）。
3. 复制弹窗里的 Key。它只显示这一次，我们只保存它的哈希值。

每个账号默认可建 1 把 Key，要换 Key 时点「重置」。Key 可以读取套餐开放的全部主题，具体要哪些主题在请求或连接时用 `topics` 参数选择；用 [GET /v1/me](https://tokenearly.com/developers/rest/me) 随时查看实际生效的主题。

Key 归账号所有，只是账号的钥匙：正式 Key 可读的主题和[我的推送](https://tokenearly.com/developers/my-alerts)（开关、历史与游标）都跟账号走，换 Key 后照旧。实时流订阅了哪些主题由客户端每次连接时用 `topics` 指定，不保存在 Key 上，换 Key 后用同样的参数重连即可。IP 白名单是每把 Key 各自设置的：重置会保留，新建的 Key 需要重新填。

### 重置 Key

Key 泄露、丢失或要定期更换时，在控制台点这把 Key 的「重置」（试用 Key 也可以）：生成一把新 Key，旧 Key 立即失效——REST 与 MCP 返回 401 `invalid_api_key`，正在用旧 Key 的实时流连接收到 `op = "error"` 后以 4001 断开，不要自动重连，换成新 Key 再连。Key ID、名称、IP 白名单、限额和到期时间都不变；试用 Key 重置不消耗申请次数，也不延长有效期。

### Key 的有效期

正式 Key 本身不过期，能不能用取决于账号的会员：含开发者 API 的会员有效期内一直可用，会员到期后所有正式 Key 以 403 `plan_required`（实时流 4003）被拒；续费后同一把 Key 立即恢复，不用重建。到期时间看 [GET /v1/me](https://tokenearly.com/developers/rest/me) 的 `access_expires_at` 或控制台。到期前 7、3、1 天和到期后，我们会发邮件、推送到你设置的通知渠道，并通过[变更通知](https://tokenearly.com/developers/rest/notices)（`access_expiring` / `access_expired`）告诉接入程序。试用 Key 不跟随会员，按自身的 `expires_at`（与 `access_expires_at` 相同）到期，到期后返回的是 401 `key_expired`（实时流 4001），不能续期：重新申请试用 Key，或开通后创建正式 Key。

> Key 等同于密码：不要写进前端代码、不要提交到代码仓库。泄露后在控制台重置或吊销，旧 Key 立即失效，用它的实时流连接也会立即断开。

## IP 白名单（可选）

在控制台给 Key 填上服务器的出口 IP，之后只有这些地址能用这把 Key，Key 即使泄露也无法在别处使用。不填 = 不限来源。随时可以修改，修改后一分钟内对已建立的实时流连接生效。

| 写法 | 含义 |
|---|---|
| `203.0.113.5` | 单个 IPv4 地址 |
| `203.0.113.0/24` | 一个网段（CIDR） |
| `2001:db8::1` | IPv6 地址或网段 |

REST 与 MCP 从白名单外的地址调用时返回 403 `ip_not_allowed`；WebSocket 先发 `op = "error"` 再以关闭码 4003 断开。

**403 响应**

```json
{
  "error": {
    "code": "ip_not_allowed",
    "message": "Requests from 198.51.100.7 are not in this key's IP allowlist.",
    "docs": "https://tokenearly.com/en/developers/errors"
  }
}
```

## 边界行为

| 情况 | 行为 |
|---|---|
| 同时带 `Authorization: Bearer` 与 `X-API-Key` | 以 `Authorization` 为准，忽略 `X-API-Key` |
| `Authorization` 不是 Bearer（例如 Basic） | 忽略它，改读 `X-API-Key` / `api_key` |
| 优先级 | `Authorization: Bearer` > `X-API-Key` > `api_key`。`api_key` 查询参数只在 WebSocket 生效，REST 上会被忽略（返回 401 `missing_api_key`）；Bearer 里的 Key 错了不会再去试 `api_key`，直接 4001 |
| `bearer` 小写、Key 前后多空格 | 都接受 |

## 试用 Key

还没开通开发者 API 的账号，可以在控制台申请试用 Key，先把代码跑通。

| 项目 | 试用 Key |
|---|---|
| 申请条件 | 已验证邮箱的正式账号（游客账号不行） |
| 有效期 | 12 小时，到期自动失效 |
| 次数 | 每个账号每 30 天 6 次；同一时间只有一把生效 |
| 数据 | 全部主题，实时推送；历史可查 7 天 |
| 限频与连接 | 与正式 Key 默认值相同：每 3 秒 1 次，同时 1 条连接 |
| 到期后 | REST 返回 401 `key_expired`，实时连接以关闭码 4001 断开 |

> 试用 Key 仅供开发测试，不得用于生产或商业用途。正式接入请开通后创建正式 Key。
