# HSystem 快速範例（純前端，OAuth + PKCE）

這個資料夾是一份「改一行就能跑」的最小整合：登入 → 換 token → 讀寫 Profile。

## 三步跑起來

1. 改 `config.js` 的 `clientId`（其他不用動）。
2. 到開發者控制台的「身份驗證」設定，把 `http://localhost:8080/callback.html` 加進允許的回呼網址／來源。
3. 在這個資料夾開一個本機伺服器，然後開 <http://localhost:8080/>：

   ```bash
   python -m http.server 8080
   # 或 npx serve -l 8080
   ```

> 不要用 `file://` 直接開：PKCE 需要 `crypto.subtle`，而它只在 https 或 localhost 這類安全環境才有。

## 檔案

| 檔案 | 做什麼 |
| --- | --- |
| `config.js` | `apiBase` 與 `clientId`。只改這一個。 |
| `index.html` | 產生 PKCE、導到 `/oauth/authorize`、顯示登入狀態。 |
| `callback.html` | 用 `code` + `code_verifier` 換 `access_token`，存進 `sessionStorage`。 |
| `profile.html` | 解出 token 裡的 `sub`，`GET`／`PUT /v1/profile/{userId}`。 |

## 跑完應該看到

- 按下「以 HSystem 登入」→ 網址跳到 `api.hsystem.halphastech.com/oauth/authorize`，出現 HSystem 託管登入頁。
- 登入完回到 `callback.html`，顯示「已取得 access_token」。
- `profile.html` 按下「讀取 Profile」：有資料就顯示 JSON；第一次使用回 404 `沒有快取資料`，那也是正常的（按下「寫入示範資料」就有了）。

## 不要做的事

- **不要把 `client_secret` 放進這些檔案。** 純前端只用 `client_id` + PKCE。
- **不要改 `sessionStorage` 的 key 名稱**，三個頁面靠 `hs_pkce_verifier`／`hs_access_token` 串起來。
- **不要拿 Profile 的 `data` 當權限判斷**：使用者可以改自己的 `data`。

## 對應文件

- [第一次呼叫（30 分鐘）](https://docs.hsystem.halphastech.com/guides/01-first-call)
- [OAuth 登入（完整流程）](https://docs.hsystem.halphastech.com/guides/00-intro)
- [Callback 片段](https://docs.hsystem.halphastech.com/guides/15-auth-callback)
- [用戶資料](https://docs.hsystem.halphastech.com/guides/30-profile)
- [憑證與認證](https://docs.hsystem.halphastech.com/credentials)
