> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hitheo.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 401 未授權

> Theo API 首次請求出現 401 錯誤的常見原因及修復方法。

如果你對 Theo API 的第一次請求返回 `401 Unauthorized`，幾乎總是下面幾種原因之一。請按順序逐一排查。

## 1. apex → www 重定向（最常見）

`https://hitheo.ai` 會以 307 重定向到 `https://www.hitheo.ai`。大多數 HTTP 客戶端——包括 Node 18 內置的 `fetch`、未加 `--location-trusted` 的 curl，以及若干語言運行時——出於安全考慮會在 3xx 響應上剝離 `Authorization` 頭。這會導致重定向後的請求變成未認證請求，服務器因此正確地返回 `401 invalid_api_key`。
**修復方法：** 直接使用規範的 `www` 主機。自 `@hitheo/sdk@0.2.0` 起，SDK 默認使用 `https://www.hitheo.ai`；如果你手動固定了 `baseUrl`，請更新它：

```typescript theme={null}
// Before
new Theo({ apiKey, baseUrl: "https://hitheo.ai" })

// After
new Theo({ apiKey, baseUrl: "https://www.hitheo.ai" })
// or: omit baseUrl entirely to pick up the default.
```

對於原始 curl：

```bash theme={null}
# Use www directly
curl -H "Authorization: Bearer $THEO_API_KEY" https://www.hitheo.ai/api/v1/models
```

CLI 的診斷命令會自動檢測到這一問題：

```bash theme={null}
theo status   # probes both apex and www, warns when your baseUrl is a redirect target
theo verify   # machine-readable JSON diagnostic you can pipe into CI
```

## 2. 缺失或格式錯誤的 API 密鑰

除 `GET /api/v1/health` 之外，每個請求都需要一個 `Authorization: Bearer theo_sk_...` 頭。請檢查：

* 頭名稱必須恰好是 `Authorization`，而不是多了一個冒號的 `authorization:`，也不是 `X-API-Key`。
* 令牌前綴必須是 `theo_sk_`（不存在 `theo_sk_test_` 這種變體——所有密鑰都是生產密鑰）。
* 令牌前後不能有空白字符——`.env` 文件末尾遺留的換行符是常見原因。
* 密鑰沒有被撤銷。請檢查 [API Keys 控制台](https://api.hitheo.ai/dashboard/api-keys)。

## 3. 密鑰的作用域不正確

API 密鑰攜帶作用域（`completions`、`skills`、`tools`、`connectors`、`billing`）。缺少 `completions` 作用域的密鑰會返回 `403 missing_scope`，而不是 `401`。如果你看到的確實是 `403`：請重新簽發一個具備所需作用域的密鑰，或聯繫密鑰創建者對其進行更新。

## 4. 密鑰已過期（寬限期已結束）

當你輪換密鑰時，舊密鑰會進入一個寬限窗口（可配置，默認 60 分鐘），隨後被撤銷。使用已過期密鑰發出的請求會返回 `401 key_expired`。請在控制台或通過 `POST /api/v1/keys/rotate` 完成輪換，並將新令牌替換到你的密鑰存儲中。

## 5. 時鐘偏差導致 webhook 的 HMAC 校驗失敗

這與 API 密鑰認證無關，但有時會被誤報為「webhook 上的 401」：webhook 簽名校驗使用的是 `Theo-Signature` 頭，它是對請求體做 HMAC-SHA256 計算得到的。如果你的服務器時鐘偏差超過 5 分鐘，簽名就會校驗不通過。可運行 `ntpdate -q pool.ntp.org` 進行檢查。

## 仍未解決？

* 運行 `theo verify`（或在 SDK 中調用 `await theo.verify()`），並將輸出提供給支持團隊。
* 在工單中附上響應頭 `X-Request-Id`——每個 v1 響應都會攜帶該頭，成功響應還會在 JSON 響應體中以 `request_id` 字段暴露它。支持團隊可據此在日誌中查找該請求。
* 查看 [status.hitheo.ai](https://status.hitheo.ai) 是否有正在發生的事件。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.