commit 05c320e11b5e0df9e53692cc862b0c86265a8f7f Author: 走狗 Date: Fri Oct 16 17:34:42 2026 +0800 feat: prepare pm-board preview for deployment diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..0613c79 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +.git +.gitea +.env* +!.env.example +.DS_Store +node_modules +npm-debug.log* +tests +PREVIEW-VERIFICATION.md + diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml new file mode 100644 index 0000000..6061ab6 --- /dev/null +++ b/.gitea/workflows/ci.yaml @@ -0,0 +1,189 @@ +# 由 vibe-deploy 的 containerize skill 產生。 +# +# 這份 workflow 不含任何 Secret,也不含任何基礎設施位址(除了下方的 +# DEPLOYMENT_API)。Registry 位址、帳號與 image 名稱都由 Deployment API 在驗證 +# 這個 job 之後回傳——因為 Gitea 的 Actions job token 對 Container Registry 沒有 +# 任何權限。細節見 deploy-site/references/platform-contract.md。 +# +# 要重新產生這個檔案,重跑 containerize skill。不要就地修改平台互動的部分: +# 契約變動時,改的是 skill 裡的範本。 +name: CI + +on: + # push 只限分支,推 tag 不觸發;Pull Request 照樣建置與測試。tag 指向的 commit 已經在 + # 推分支時測過、部署過,再跑一次只會和分支那次同時搶 runner。 + push: + branches: ['**'] + pull_request: + +env: + DEPLOYMENT_API: http://192.168.8.64:3000 + # 每次執行唯一。同一個 commit 同時跑兩次時,容器與映像不會撞名,收拾時也只刪自己的。 + # 推到 Registry 的 tag 仍是完整 SHA,部署契約不變。 + CI_NAME: ci-${{ gitea.run_id }} + +jobs: + build: + runs-on: ubuntu-latest + # job token 只需要讀取自己的 repository。packages: write 對 Registry 沒有 + # 作用,不要加。 + permissions: + contents: read + steps: + - name: 取出程式碼 + uses: actions/checkout@v4 + + - name: 測試 + run: npm test + + - name: 建置映像 + run: | + echo "CI_NAME=$CI_NAME" + docker build -t "$CI_NAME" . + + - name: 冒煙測試:容器要真的能服務請求 + run: | + set -eu + name="$CI_NAME-smoke" + docker rm -f "$name" >/dev/null 2>&1 || true + docker run -d --name "$name" "$CI_NAME" + + # 等 Dockerfile 的 HEALTHCHECK 轉綠。那條檢查在容器內執行,會實際打 + # health endpoint,所以資料庫或可寫入路徑有問題也會在這裡被抓到。 + status=starting + for _ in $(seq 1 30); do + status=$(docker inspect -f '{{.State.Health.Status}}' "$name") + [ "$status" = healthy ] && break + [ "$status" = unhealthy ] && break + sleep 2 + done + + if [ "$status" != healthy ]; then + echo "容器未進入 healthy,最後狀態:$status" + docker logs "$name" + exit 1 + fi + echo "容器 healthy" + + - name: 收拾冒煙測試容器 + if: always() + run: docker rm -f "$CI_NAME-smoke" >/dev/null 2>&1 || true + + # 以下只在推送到預設分支時執行。Pull Request 與其他分支只做建置與測試。 + # 分支名稱取自 repository 的實際預設分支,不寫死 main——公司有 repository + # 用的是 master。 + - name: 向 Deployment API 取得 Registry 憑證 + id: credentials + if: gitea.event_name == 'push' && gitea.ref == format('refs/heads/{0}', gitea.event.repository.default_branch) + run: | + set -eu + code=$(curl -sS -m 15 -o /tmp/registry-credentials.json -w '%{http_code}' \ + -X POST "${DEPLOYMENT_API}/v1/registry-credentials" \ + -H "Authorization: Bearer ${{ secrets.GITEA_TOKEN }}" \ + -H 'Content-Type: application/json' \ + -d "{\"repository\":\"${{ gitea.repository }}\",\"commitSha\":\"${{ gitea.sha }}\"}") + if [ "$code" != 200 ]; then + echo "取得憑證失敗:HTTP $code" + # 回應可能含錯誤說明,但絕不含憑證以外的機敏資料時才印。 + python3 -c "import json;print(json.load(open('/tmp/registry-credentials.json')).get('error'))" || true + exit 1 + fi + + field() { python3 -c "import json;print(json.load(open('/tmp/registry-credentials.json'))['$1'])"; } + # image 由 API 指定,CI 不自行組合位址。 + echo "registry=$(field registry)" >> "$GITEA_OUTPUT" + echo "image=$(field image)" >> "$GITEA_OUTPUT" + + - name: 發布不可變映像 + if: gitea.event_name == 'push' && gitea.ref == format('refs/heads/{0}', gitea.event.repository.default_branch) + run: | + set -eu + registry='${{ steps.credentials.outputs.registry }}' + image='${{ steps.credentials.outputs.image }}' + + python3 -c "import json;print(json.load(open('/tmp/registry-credentials.json'))['password'])" \ + | docker login "$registry" \ + -u "$(python3 -c "import json;print(json.load(open('/tmp/registry-credentials.json'))['username'])")" \ + --password-stdin + + # 部署只引用不可變的完整 SHA。 + docker tag "$CI_NAME" "${image}:${{ gitea.sha }}" + docker push -q "${image}:${{ gitea.sha }}" + + docker logout "$registry" >/dev/null 2>&1 || true + rm -f /tmp/registry-credentials.json + + # API 可能要等同一個應用程式的其他請求(最多 60 秒),再花最多 45 秒設定公司登入 + # 與物件儲存,所以單次等 135 秒。只有三個錯誤碼代表「稍後重送就會成功」,依 API + # 給的 Retry-After 重試:最多三次請求,從第一次起算共 6 分鐘。其他錯誤一次就停。 + # 重送同一個 commit 是安全的:API 會沿用既有的部署紀錄。 + - name: 建立部署 + if: gitea.event_name == 'push' && gitea.ref == format('refs/heads/{0}', gitea.event.repository.default_branch) + env: + DEPLOY_TOKEN: ${{ secrets.GITEA_TOKEN }} + DEPLOY_REPOSITORY: ${{ gitea.repository }} + DEPLOY_COMMIT: ${{ gitea.sha }} + run: | + python3 - <<'PY' + import json, os, re, socket, sys, time, urllib.error, urllib.request + + RETRYABLE = {"application_busy", "s3_credential_change_blocked", "application_provisioning_timeout"} + TIMEOUT = float(os.environ.get("DEPLOY_REQUEST_TIMEOUT", "135")) + BUDGET = float(os.environ.get("DEPLOY_RETRY_BUDGET", "360")) + MAX_REQUESTS = 3 + + url = os.environ["DEPLOYMENT_API"].rstrip("/") + "/v1/deployments" + body = json.dumps({"repository": os.environ["DEPLOY_REPOSITORY"], + "commitSha": os.environ["DEPLOY_COMMIT"]}).encode() + timeouts = (TimeoutError, socket.timeout) + # 內網位址是明文 HTTP:環境變數裡的 proxy 會看到 token,所以不用 proxy。 + # HTTPS 時 proxy 只轉送加密的通道,照環境設定走。 + handlers = [] if url.startswith("https://") else [urllib.request.ProxyHandler({})] + opener = urllib.request.build_opener(*handlers) + started = time.monotonic() + for attempt in range(1, MAX_REQUESTS + 1): + request = urllib.request.Request(url, data=body, method="POST", headers={ + "Authorization": "Bearer " + os.environ["DEPLOY_TOKEN"], + "Content-Type": "application/json", + }) + try: + with opener.open(request, timeout=TIMEOUT) as response: + status, raw, headers = response.status, response.read(), response.headers + except urllib.error.HTTPError as error: + status, raw, headers = error.code, error.read(65536), error.headers + except (urllib.error.URLError, OSError) as error: + reason = getattr(error, "reason", error) + if isinstance(reason, timeouts) or isinstance(error, timeouts): + sys.exit(f"建立部署逾時:Deployment API 在 {TIMEOUT:g} 秒內沒有回應,可能仍在處理。" + "重跑這個 job 即可,同一個 commit 會沿用既有的部署紀錄") + sys.exit(f"連不到 Deployment API:{type(reason).__name__}") + + text = raw.decode("utf-8", "replace") + print(text) + # 201 建立、200 表示同一個 SHA 已經有部署紀錄,兩者都算成功。 + if status in (200, 201): + sys.exit(0) + try: + code = json.loads(text)["error"]["code"] + except (ValueError, KeyError, TypeError): + code = None + if code not in RETRYABLE: + sys.exit(f"建立部署失敗:HTTP {status}") + wait = (headers.get("Retry-After") or "").strip() + # 正整數秒;0 等於不等待就重送。 + if not re.fullmatch(r"[1-9][0-9]{0,3}", wait): + sys.exit(f"建立部署失敗:API 回 {code},但沒有合法的 Retry-After,不重試") + wait = int(wait) + if attempt == MAX_REQUESTS or time.monotonic() - started + wait + TIMEOUT > BUDGET: + sys.exit(f"建立部署失敗:{code}。另一個部署正在使用這個應用程式的設定," + "重試後仍未完成;請稍後重跑這個 job") + print(f"API 回 {code},{wait} 秒後重試(第 {attempt}/{MAX_REQUESTS - 1} 次重試)", flush=True) + time.sleep(wait) + PY + + - name: 清理 + if: always() + run: | + rm -f /tmp/registry-credentials.json + # 映像以執行編號命名,不刪會在 runner 共用的 Docker 上累積。發布已推到 Registry。 + docker rmi "$CI_NAME" >/dev/null 2>&1 || true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2975538 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.DS_Store +.env +.env.* +!.env.example +node_modules/ +npm-debug.log* + diff --git a/2022_Moonshine_Logo_MS_logo_w_EN.png b/2022_Moonshine_Logo_MS_logo_w_EN.png new file mode 100644 index 0000000..8708103 Binary files /dev/null and b/2022_Moonshine_Logo_MS_logo_w_EN.png differ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..5c09a75 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,20 @@ +FROM node:22-alpine + +ENV NODE_ENV=production \ + HOST=0.0.0.0 \ + PORT=8080 + +WORKDIR /app + +COPY --chown=node:node package.json server.js index.html 2022_Moonshine_Logo_MS_logo_w_EN.png ./ +COPY --chown=node:node data ./data + +USER node + +EXPOSE 8080 + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=6 \ + CMD wget -qO- http://127.0.0.1:8080/api/health >/dev/null || exit 1 + +CMD ["node", "server.js"] + diff --git a/PREVIEW-VERIFICATION.md b/PREVIEW-VERIFICATION.md new file mode 100644 index 0000000..92b8af1 --- /dev/null +++ b/PREVIEW-VERIFICATION.md @@ -0,0 +1,37 @@ +# 合成資料預覽驗證 + +本次修正後已以三個全新瀏覽器工作階段完成驗證:1440、1024、1280px,視窗高度均為 900px。 + +| 檢查 | 第一輪 | 第二輪 | 第三輪 | +| --- | --- | --- | --- | +| 10 個導覽頁及人員完整名單 | 通過 | 通過 | 通過 | +| 發票、業務、藝術家、CODA 展開明細 | 通過 | 通過 | 通過 | +| 主內容橫向溢出、選單選取、無效數值 | 通過 | 通過 | 通過 | +| 合成成本 17,812,800 元 | 通過 | 通過 | 通過 | +| 七月調薪與同月後建事件覆蓋 | 通過 | 通過 | 通過 | +| 新增、編輯、刪除調薪,底薪保持原值 | 通過 | 通過 | 通過 | +| 未來年度調薪不提前生效 | 通過 | 通過 | 通過 | +| 試算人員/參數隔離、0% 權重 | 通過 | 通過 | 通過 | +| 重新載入還原 12 人合成資料 | 通過 | 通過 | 通過 | +| 瀏覽器執行錯誤 | 0 | 0 | 0 | +| Dashboard 從長頁面切回頂端、3張KPI及3個圖表存在 | 通過 | 通過 | 通過 | +| Dashboard 圖表卡片內容未裁切 | 通過 | 通過 | 通過 | + +Dashboard 回報後追加修正:移除固定高度及圖表內容的隱藏溢出,改以內容自然撐高;切換頁面重設主內容捲動位置。上述追加檢查已隨完整三輪重新執行。 + +## 本次發現並修正 + +- 試算退出後參數仍留在預覽資料:進入試算時保存參數,退出還原。 +- 0% 權重與減免比例被預設值取代:明確區分零與未提供值。 +- 1280px 組織/參數頁溢出:調整響應式切換範圍。 +- 調薪新增/編輯直接覆寫底薪:保留底薪,改由事件依生效年月套用;刪除事件後重新計算。 +- 調薪下拉選單排序改動原始人員陣列:改用陣列副本。 +- 快照讀取共用原始物件:載入時複製,避免後續修改污染快照。 + +## 重跑方式 + +啟動預覽伺服器後,執行 `node scripts/verify-preview.mjs`。需要 Playwright 與已安裝的 Chrome;可用 `PLAYWRIGHT_MODULE` 指定 Playwright 模組路徑,`PREVIEW_URL` 指定預覽網址。結果與每輪截圖寫入獨立暫存目錄,路徑會顯示於輸出。任一檢查失敗會回傳失敗狀態。 + +## 驗證範圍 + +本紀錄針對目前的合成預覽,不代表真實 HR API、登入權限或所有歷史資料情境已通過驗收。匯入/匯出、所有金額進位與分攤尾差、月/季/半年報表亦不在這次三輪的驗證範圍。 diff --git a/README.md b/README.md new file mode 100644 index 0000000..025bf16 --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# pm-board + +MoonShine 成本與發票目標預覽站。現階段只使用去識別化的合成資料;正式 HR Sync 串接會在 API 規格與授權確認後加入。 + +## 本機預覽 + +```sh +npm start +``` + +開啟 `http://127.0.0.1:8080`。本機未提供 OIDC 設定時會進入合成資料預覽模式。 + +## 正式環境 + +正式環境由 MoonShine 部署平台提供 `OIDC_ISSUER`、`OIDC_CLIENT_ID`、`OIDC_CLIENT_SECRET`。網站要求公司登入,登入時會指定 `prompt=login`,並要求 `employee_number` scope。 + diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..ca021a9 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,12 @@ +services: + app: + build: + context: . + ports: + - "8080:8080" + environment: + NODE_ENV: development + HOST: 0.0.0.0 + PORT: 8080 + DATA_SOURCE: synthetic + diff --git a/data/demo.json b/data/demo.json new file mode 100644 index 0000000..7062666 --- /dev/null +++ b/data/demo.json @@ -0,0 +1,48 @@ +{ + "source": "synthetic-demo", + "generatedAt": "2026-10-16T00:00:00.000Z", + "globalParams": { + "utilization": 1, + "utilizationP": 1, + "utilizationA": 1, + "workingDays": 22, + "opMultiplier": 2, + "pcDept": "製程部", + "supportConversionRate": 0.5, + "rdGroups": [], + "rdIndividuals": [], + "rdReductionPct": 0.35, + "managerReductionPct": 0.6, + "pManagerReductionPct": 0.6, + "pPCReductionPct": 0.6, + "externalProjectOutsourcing": 30000000, + "employeeTripInvoices": 15000000, + "grossMarginPct": 0.85, + "invoiceWeightP": 0.4, + "invoiceWeightA": 0.25, + "invoiceWeightSurplus": 0.35, + "targetAPRatio": 6, + "annualWorkDays": 250, + "raiseEvents": [], + "orgStructure": { + "前製部": ["前製部_導演組", "前製部_設計組"], + "廣告部": ["廣告部_A組", "廣告部_B組"], + "視效部": ["視效部_合成組", "視效部_特效組"], + "動畫部": ["動畫部_動畫組", "動畫部_前製組"] + } + }, + "baseData": [ + {"row": 1001, "name": "示範員工01", "title": "專案管理", "dept": "前製部", "group": "", "role": "P - 專案管理", "isManager": true, "salary": "78000", "dayrate": "", "h1Start": 1, "h1End": 6, "h2Start": 7, "h2End": 12, "workRateUsed": 1}, + {"row": 1002, "name": "示範員工02", "title": "藝術家", "dept": "前製部", "group": "前製部_導演組", "role": "A - 藝術家", "isManager": false, "salary": "62000", "dayrate": "", "h1Start": 1, "h1End": 6, "h2Start": 7, "h2End": 12, "workRateUsed": 1}, + {"row": 1003, "name": "示範員工03", "title": "藝術家", "dept": "前製部", "group": "前製部_設計組", "role": "A - 藝術家", "isManager": false, "salary": "54000", "dayrate": "", "h1Start": 2, "h1End": 6, "h2Start": 7, "h2End": 12, "workRateUsed": 1}, + {"row": 1004, "name": "示範員工04", "title": "專案管理", "dept": "廣告部", "group": "", "role": "P - 專案管理", "isManager": false, "salary": "72000", "dayrate": "", "h1Start": 1, "h1End": 6, "h2Start": 7, "h2End": 12, "workRateUsed": 1}, + {"row": 1005, "name": "示範員工05", "title": "藝術家", "dept": "廣告部", "group": "廣告部_A組", "role": "A - 藝術家", "isManager": false, "salary": "58000", "dayrate": "", "h1Start": 1, "h1End": 6, "h2Start": 7, "h2End": 12, "workRateUsed": 1}, + {"row": 1006, "name": "示範員工06", "title": "外包藝術家", "dept": "廣告部", "group": "廣告部_B組", "role": "O - 外包", "isManager": false, "salary": "", "dayrate": "3200", "h1Start": 3, "h1End": 6, "h2Start": 7, "h2End": 10, "workRateUsed": 1.5}, + {"row": 1007, "name": "示範員工07", "title": "專案管理", "dept": "視效部", "group": "", "role": "P - 專案管理", "isManager": false, "salary": "75000", "dayrate": "", "h1Start": 1, "h1End": 6, "h2Start": 7, "h2End": 12, "workRateUsed": 1}, + {"row": 1008, "name": "示範員工08", "title": "藝術家", "dept": "視效部", "group": "視效部_合成組", "role": "A - 藝術家", "isManager": false, "salary": "68000", "dayrate": "", "h1Start": 1, "h1End": 6, "h2Start": 7, "h2End": 12, "workRateUsed": 1}, + {"row": 1009, "name": "示範員工09", "title": "外包藝術家", "dept": "視效部", "group": "視效部_特效組", "role": "O - 外包", "isManager": false, "salary": "", "dayrate": "4000", "h1Start": 1, "h1End": 6, "h2Start": 7, "h2End": 9, "workRateUsed": 1.5}, + {"row": 1010, "name": "示範員工10", "title": "專案管理", "dept": "動畫部", "group": "", "role": "P - 專案管理", "isManager": false, "salary": "70000", "dayrate": "", "h1Start": 1, "h1End": 6, "h2Start": 7, "h2End": 12, "workRateUsed": 1}, + {"row": 1011, "name": "示範員工11", "title": "藝術家", "dept": "動畫部", "group": "動畫部_動畫組", "role": "A - 藝術家", "isManager": false, "salary": "60000", "dayrate": "", "h1Start": 1, "h1End": 6, "h2Start": 7, "h2End": 12, "workRateUsed": 1}, + {"row": 1012, "name": "示範員工12", "title": "藝術家", "dept": "製程部", "group": "製作組", "role": "A - 藝術家", "isManager": false, "salary": "65000", "dayrate": "", "h1Start": 1, "h1End": 6, "h2Start": 7, "h2End": 12, "workRateUsed": 1} + ] +} diff --git a/index.html b/index.html new file mode 100644 index 0000000..7b85706 --- /dev/null +++ b/index.html @@ -0,0 +1,5591 @@ + + + + + + + Studio Cost Model Pro - Animation KPI System + + + + + + +
+
🧪 試算模式中  |  資料不會被儲存,盡情亂改!
+ +
+
+ + + + +
+ + +
+ +
+ 正在從預覽伺服器載入合成資料… +
+
+ +
+ +
+

📊 營運概況 Dashboard

+ +
+
+ + +
+ +
+ + +
+
+

+ 📈 部門 CODA 成本佔比

+
+ +
+
+
+

+ 👥 人力分佈

+
+
+
+

+ 🧾 各部門年度發票目標

+
+
+
+
+ + +
+
+ + +
+
+
+

📈 薪資版本與年度調薪

+

管理年度調薪事件,系統會依部門自動結算該年度增額成本。

+ +
+
+ + +
+
+ +
+ +
+ +
+

📅 年度調薪軌跡 (Raise Events)

+
+ + + + + + + + + + + + +
生效日期 (月份)事件說明受影響人數操作
+
+
+
+ + +
+
+

人員概況 - 部門成本分佈

+ +
+ +
+

各部門人力預算佔比 (Department Cost % )

+
+ +
+
+ +
+ +
+
+ + +
+
+
+

人員主表 (全部門)

+
+ +
+
+
+
+
+ +
+ + +
+ + + + + +
+
+
+ + + + + + + + + + + + + + + + + + + + +
姓名 職稱 部門 組別 職能 管理職 月/日薪 H1 起H1 迄H2 起H2 迄狀態個人總成本 操作
+
+
+ + +
+
+

業務管理 - 全體 P 系列預算

+
+
P 年度薪資承擔額(依管理/PC比例)
+
NT$ 0
+
+
+
+ +
+
+ + +
+
+

藝術家 (四大製作部)

+
+
製作部門藝術家成本(含支援分攤)
+
NT$ 0
+
+
+
+ +
+
+ + +
+
+
+

⚙️ 系統核心參數設定

+

調整全公司營運基準、倍率、以及各項自動計算參數。變動將立即影響所有視圖。

+
+
+ +
+ +
+
+ + +
+
+
+

部門 CODA 總覽

+

P 系列預算 + A/O + 藝術家預算(含製程部分攤)= 各部門最終 CODA

+
+
+
全公司總 CODA
+
NT$ 0
+
+
+
+ +
+
+ + +
+
+ +
+
+ + +
+

小組影響力分析

+
+ + + + + + + + + + + +
部門組別小組總人數小組總成本佔部門原始成本(含外包)
+
+
+ + +
+
+
+

📈 薪資版本與調薪控制

+

建立批次調薪事件,系統將自動於指定月份後採用新薪資疊加計算全年度成本。

+
+
+ +
+
+ +
+ + + + + + + + + + + + +
批次名稱建立時間受影響人數操作
+
+ +
+
+

📁 歷史快照管理

+

保存當下之所有系統狀態(含人員名單與薪資等),以便未來讀取與比對。

+
+
+ +
+
+ +
+ + + + + + + + + + + +
快照名稱保存時間操作
+
+
+ +
+
+ + + + + + + + + + + + + diff --git a/package.json b/package.json new file mode 100644 index 0000000..55dbecc --- /dev/null +++ b/package.json @@ -0,0 +1,11 @@ +{ + "name": "moonshine-cost-model-preview", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "start": "node server.js", + "preview": "node server.js", + "test": "node --test tests/*.test.mjs" + } +} diff --git a/server.js b/server.js new file mode 100644 index 0000000..9a54797 --- /dev/null +++ b/server.js @@ -0,0 +1,280 @@ +import { createHash, createPublicKey, randomBytes, verify } from 'node:crypto'; +import { createServer } from 'node:http'; +import { readFile } from 'node:fs/promises'; +import { extname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = fileURLToPath(new URL('.', import.meta.url)); +const port = Number(process.env.PORT || 8080); +const host = process.env.HOST || (process.env.NODE_ENV === 'production' ? '0.0.0.0' : '127.0.0.1'); +const isProduction = process.env.NODE_ENV === 'production'; +const demoPath = resolve(root, 'data/demo.json'); +const oidc = { + issuer: process.env.OIDC_ISSUER?.replace(/\/+$/, ''), + clientId: process.env.OIDC_CLIENT_ID, + clientSecret: process.env.OIDC_CLIENT_SECRET, +}; +const oidcConfigured = Boolean(oidc.issuer && oidc.clientId && oidc.clientSecret); +const pendingLogins = new Map(); +const sessions = new Map(); +let discoveryCache; +let jwksCache; + +const allowedStaticFiles = new Map([ + ['/2022_Moonshine_Logo_MS_logo_w_EN.png', ['2022_Moonshine_Logo_MS_logo_w_EN.png', 'image/png']], +]); + +function sendJson(response, status, body) { + response.writeHead(status, { + 'Content-Type': 'application/json; charset=utf-8', + 'Cache-Control': 'no-store', + 'X-Content-Type-Options': 'nosniff', + }); + response.end(JSON.stringify(body)); +} + +function sendText(response, status, body) { + response.writeHead(status, { + 'Content-Type': 'text/plain; charset=utf-8', + 'Cache-Control': 'no-store', + 'X-Content-Type-Options': 'nosniff', + }); + response.end(body); +} + +function redirect(response, location, cookies = []) { + response.writeHead(302, { + Location: location, + 'Cache-Control': 'no-store', + ...(cookies.length ? { 'Set-Cookie': cookies } : {}), + }); + response.end(); +} + +function parseCookies(request) { + return Object.fromEntries((request.headers.cookie || '').split(';').flatMap((part) => { + const index = part.indexOf('='); + if (index < 0) return []; + return [[part.slice(0, index).trim(), decodeURIComponent(part.slice(index + 1).trim())]]; + })); +} + +function cookie(name, value, maxAge) { + return `${name}=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${isProduction ? '; Secure' : ''}`; +} + +function pruneExpired() { + const now = Date.now(); + for (const [key, value] of pendingLogins) if (value.expiresAt <= now) pendingLogins.delete(key); + for (const [key, value] of sessions) if (value.expiresAt <= now) sessions.delete(key); +} + +function getSession(request) { + pruneExpired(); + const sessionId = parseCookies(request).pm_board_session; + return sessionId ? sessions.get(sessionId) : undefined; +} + +function externalOrigin(request) { + const forwardedProto = String(request.headers['x-forwarded-proto'] || '').split(',')[0].trim(); + const protocol = forwardedProto || (isProduction ? 'https' : 'http'); + return `${protocol}://${request.headers.host}`; +} + +async function getDiscovery() { + if (discoveryCache) return discoveryCache; + const response = await fetch(`${oidc.issuer}/.well-known/openid-configuration`, { signal: AbortSignal.timeout(8000) }); + if (!response.ok) throw new Error(`OIDC discovery failed (${response.status})`); + discoveryCache = await response.json(); + return discoveryCache; +} + +function decodeSegment(segment) { + return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8')); +} + +async function validateIdToken(token, expectedNonce) { + const parts = token.split('.'); + if (parts.length !== 3) throw new Error('Invalid ID token'); + const header = decodeSegment(parts[0]); + const payload = decodeSegment(parts[1]); + const discovery = await getDiscovery(); + + if (!jwksCache) { + const response = await fetch(discovery.jwks_uri, { signal: AbortSignal.timeout(8000) }); + if (!response.ok) throw new Error(`OIDC keys failed (${response.status})`); + jwksCache = await response.json(); + } + + const jwk = jwksCache.keys?.find((key) => key.kid === header.kid && key.kty === 'RSA'); + if (!jwk || header.alg !== 'RS256') throw new Error('Unsupported ID token key'); + const validSignature = verify( + 'RSA-SHA256', + Buffer.from(`${parts[0]}.${parts[1]}`), + createPublicKey({ key: jwk, format: 'jwk' }), + Buffer.from(parts[2], 'base64url'), + ); + const audience = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; + const now = Math.floor(Date.now() / 1000); + if (!validSignature || payload.iss?.replace(/\/+$/, '') !== oidc.issuer || !audience.includes(oidc.clientId)) { + throw new Error('ID token verification failed'); + } + if (!payload.exp || payload.exp <= now || payload.nonce !== expectedNonce) throw new Error('Expired or mismatched ID token'); + if (!payload.employee_number) throw new Error('Employee number is missing'); + return payload; +} + +async function beginLogin(request, response) { + const discovery = await getDiscovery(); + const state = randomBytes(24).toString('base64url'); + const nonce = randomBytes(24).toString('base64url'); + const verifier = randomBytes(48).toString('base64url'); + const challenge = createHash('sha256').update(verifier).digest('base64url'); + pendingLogins.set(state, { nonce, verifier, expiresAt: Date.now() + 10 * 60 * 1000 }); + const callback = `${externalOrigin(request)}/api/auth/callback/authentik`; + const url = new URL(discovery.authorization_endpoint); + url.search = new URLSearchParams({ + client_id: oidc.clientId, + redirect_uri: callback, + response_type: 'code', + scope: 'openid profile email employee_number', + state, + nonce, + code_challenge: challenge, + code_challenge_method: 'S256', + prompt: 'login', + }); + redirect(response, url.toString(), [cookie('pm_board_login', state, 600)]); +} + +async function finishLogin(request, response, url) { + const state = url.searchParams.get('state'); + const code = url.searchParams.get('code'); + const cookies = parseCookies(request); + const pending = state ? pendingLogins.get(state) : undefined; + pendingLogins.delete(state); + if (!state || !code || cookies.pm_board_login !== state || !pending || pending.expiresAt <= Date.now()) { + return sendText(response, 400, '登入驗證已失效,請重新登入。'); + } + + const discovery = await getDiscovery(); + const callback = `${externalOrigin(request)}/api/auth/callback/authentik`; + const tokenResponse = await fetch(discovery.token_endpoint, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'authorization_code', + code, + redirect_uri: callback, + client_id: oidc.clientId, + client_secret: oidc.clientSecret, + code_verifier: pending.verifier, + }), + signal: AbortSignal.timeout(8000), + }); + if (!tokenResponse.ok) return sendText(response, 401, '公司登入失敗,請重新嘗試。'); + const tokens = await tokenResponse.json(); + const claims = await validateIdToken(tokens.id_token, pending.nonce); + const sessionId = randomBytes(32).toString('base64url'); + sessions.set(sessionId, { claims, expiresAt: Date.now() + 8 * 60 * 60 * 1000 }); + redirect(response, '/', [cookie('pm_board_session', sessionId, 8 * 60 * 60), cookie('pm_board_login', '', 0)]); +} + +function requireAuth(request, response, api = false) { + if (!oidcConfigured) { + if (!isProduction) return { claims: { employee_number: 'preview' } }; + if (api) sendJson(response, 503, { error: 'Company login is not configured.' }); + else sendText(response, 503, '公司登入尚未完成設定。'); + return null; + } + const session = getSession(request); + if (session) return session; + if (api) sendJson(response, 401, { error: 'Authentication required.', login: '/api/auth/login' }); + else redirect(response, '/api/auth/login'); + return null; +} + +const server = createServer(async (request, response) => { + const url = new URL(request.url || '/', `http://${request.headers.host || 'localhost'}`); + + try { + if (request.method === 'GET' && url.pathname === '/api/health') { + return sendJson(response, 200, { status: 'ok' }); + } + + if (request.method === 'GET' && url.pathname === '/api/auth/login') { + if (!oidcConfigured) return sendText(response, 503, '公司登入尚未完成設定。'); + return await beginLogin(request, response); + } + + if (request.method === 'GET' && url.pathname === '/api/auth/callback/authentik') { + if (!oidcConfigured) return sendText(response, 503, '公司登入尚未完成設定。'); + return await finishLogin(request, response, url); + } + + if (request.method === 'POST' && url.pathname === '/api/auth/logout') { + const sessionId = parseCookies(request).pm_board_session; + if (sessionId) sessions.delete(sessionId); + redirect(response, '/', [cookie('pm_board_session', '', 0)]); + return; + } + + if (request.method === 'GET' && url.pathname === '/api/auth/me') { + const session = requireAuth(request, response, true); + if (!session) return; + return sendJson(response, 200, { + employeeNumber: session.claims.employee_number, + name: session.claims.name || session.claims.preferred_username || '', + }); + } + + if (request.method === 'GET' && url.pathname === '/api/bootstrap') { + if (!requireAuth(request, response, true)) return; + if ((process.env.DATA_SOURCE || 'synthetic') !== 'synthetic') { + return sendJson(response, 503, { + error: 'The HR data provider is not configured. Synthetic preview is the only enabled source.', + source: 'unavailable', + }); + } + const demo = JSON.parse(await readFile(demoPath, 'utf8')); + return sendJson(response, 200, demo); + } + + if (request.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) { + if (!requireAuth(request, response)) return; + const content = await readFile(resolve(root, 'index.html')); + response.writeHead(200, { + 'Content-Type': 'text/html; charset=utf-8', + 'Cache-Control': 'no-store', + 'X-Content-Type-Options': 'nosniff', + 'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self' https://auth.moonshine-studio.net", + }); + return response.end(content); + } + + if (request.method === 'GET' && allowedStaticFiles.has(url.pathname)) { + const [filename, contentType] = allowedStaticFiles.get(url.pathname); + const content = await readFile(resolve(root, filename)); + response.writeHead(200, { + 'Content-Type': contentType, + 'Cache-Control': 'no-cache', + 'X-Content-Type-Options': 'nosniff', + }); + return response.end(content); + } + + if (request.method === 'GET' && extname(url.pathname) === '') { + return sendJson(response, 404, { error: 'Not found.' }); + } + + return sendJson(response, 404, { error: 'Not found.' }); + } catch (error) { + console.error('Request failed:', error.message); + return sendJson(response, 500, { error: 'Request failed.' }); + } +}); + +server.listen(port, host, () => { + console.log(`Cost model preview listening on http://${host}:${port}`); + if (isProduction && !oidcConfigured) console.warn('Company login is not configured; protected routes are closed.'); +}); diff --git a/tests/server.test.mjs b/tests/server.test.mjs new file mode 100644 index 0000000..f62acf4 --- /dev/null +++ b/tests/server.test.mjs @@ -0,0 +1,55 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import test from 'node:test'; + +const node = process.execPath; + +async function waitFor(url) { + for (let attempt = 0; attempt < 40; attempt += 1) { + try { + const response = await fetch(url); + if (response.ok) return response; + } catch {} + await new Promise((resolve) => setTimeout(resolve, 100)); + } + throw new Error(`Server did not start: ${url}`); +} + +function start(env) { + return spawn(node, ['server.js'], { env: { ...process.env, ...env }, stdio: 'ignore' }); +} + +test('development preview serves synthetic data and health', async (t) => { + const child = start({ PORT: '18081', HOST: '127.0.0.1', NODE_ENV: 'development' }); + t.after(() => child.kill()); + await waitFor('http://127.0.0.1:18081/api/health'); + assert.equal((await fetch('http://127.0.0.1:18081/')).status, 200); + const bootstrap = await fetch('http://127.0.0.1:18081/api/bootstrap'); + assert.equal(bootstrap.status, 200); + assert.equal((await bootstrap.json()).source, 'synthetic-demo'); +}); + +test('production fails closed when OIDC settings are unavailable', async (t) => { + const child = start({ PORT: '18082', HOST: '127.0.0.1', NODE_ENV: 'production', OIDC_ISSUER: '', OIDC_CLIENT_ID: '', OIDC_CLIENT_SECRET: '' }); + t.after(() => child.kill()); + await waitFor('http://127.0.0.1:18082/api/health'); + assert.equal((await fetch('http://127.0.0.1:18082/', { redirect: 'manual' })).status, 503); + assert.equal((await fetch('http://127.0.0.1:18082/api/bootstrap')).status, 503); +}); + +test('configured production redirects pages and protects APIs', async (t) => { + const child = start({ + PORT: '18083', + HOST: '127.0.0.1', + NODE_ENV: 'production', + OIDC_ISSUER: 'https://auth.example.test/application/o/pm-board/', + OIDC_CLIENT_ID: 'test-client', + OIDC_CLIENT_SECRET: 'test-secret', + }); + t.after(() => child.kill()); + await waitFor('http://127.0.0.1:18083/api/health'); + const page = await fetch('http://127.0.0.1:18083/', { redirect: 'manual' }); + assert.equal(page.status, 302); + assert.equal(page.headers.get('location'), '/api/auth/login'); + assert.equal((await fetch('http://127.0.0.1:18083/api/bootstrap')).status, 401); +}); diff --git a/vibe.yaml b/vibe.yaml new file mode 100644 index 0000000..e8cc8cb --- /dev/null +++ b/vibe.yaml @@ -0,0 +1,11 @@ +version: 1 +container: + port: 8080 +healthcheck: + path: /api/health +persistence: + enabled: false +auth: + mode: oidc + callback_path: /api/auth/callback/authentik +