From 173b44abcae72358ac6b0b1fa8ce9f86c0e2616d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?= Date: Mon, 14 Sep 2026 19:20:01 +0800 Subject: [PATCH] feat(settings): refresh DingTalk scan sessions from the data-source page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DingTalk source scanning depends on a shared browser session whose capture file had to be replaced by hand whenever it expired (every scan 401s). - services/dingtalk-login: admin-triggered Playwright sidecar that opens the space page in a persistent headless Chromium, publishes the QR through session polling, verifies the first authenticated XHR against the box API, then writes the capture in place (same inode keeps the worker's ro bind mount current); tokens never leave the sidecar - api: POST/GET/DELETE /api/v1/dingtalk-session authenticated relay; QR is a login artifact, so the whole prefix is admin-only in classifyRole; OpenAPI contract and proxy/503/hostile-ID tests included - web: 系统设置 → 数据源配置 钉钉卡片新增扫码刷新会话(仅管理员可见), QR 弹窗 + 1.5s 轮询 + 成功/过期/失败状态 - compose: sidecar service owns the ONLY rw mount of secrets/; worker keeps ro --- api/openapi.yaml | 63 ++++++++ compose.yaml | 29 ++++ internal/httpapi/auth.go | 6 + internal/httpapi/dingtalk_session.go | 129 ++++++++++++++++ internal/httpapi/dingtalk_session_test.go | 85 +++++++++++ internal/httpapi/server.go | 9 ++ services/dingtalk-login/Dockerfile | 23 +++ services/dingtalk-login/package.json | 9 ++ services/dingtalk-login/server.mjs | 178 ++++++++++++++++++++++ web/src/DingtalkSessionControl.test.tsx | 15 ++ web/src/DingtalkSessionControl.tsx | 72 +++++++++ web/src/SystemSettings.tsx | 4 + web/src/dingtalkSession.ts | 56 +++++++ web/src/systemSettings.css | 5 + 14 files changed, 683 insertions(+) create mode 100644 internal/httpapi/dingtalk_session.go create mode 100644 internal/httpapi/dingtalk_session_test.go create mode 100644 services/dingtalk-login/Dockerfile create mode 100644 services/dingtalk-login/package.json create mode 100644 services/dingtalk-login/server.mjs create mode 100644 web/src/DingtalkSessionControl.test.tsx create mode 100644 web/src/DingtalkSessionControl.tsx create mode 100644 web/src/dingtalkSession.ts diff --git a/api/openapi.yaml b/api/openapi.yaml index 3ed6458..5e95bc8 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -522,6 +522,69 @@ } } }, + "/api/v1/dingtalk-session": { + "post": { + "tags": [ + "Source connections" + ], + "operationId": "startDingtalkSession", + "summary": "发起钉钉扫码登录会话(管理员)", + "responses": { + "201": { + "$ref": "#/components/responses/Envelope" + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "500": { + "$ref": "#/components/responses/InternalError" + } + } + } + }, + "/api/v1/dingtalk-session/{id}": { + "parameters": [ + { + "$ref": "#/components/parameters/ID" + } + ], + "get": { + "tags": [ + "Source connections" + ], + "operationId": "getDingtalkSession", + "summary": "轮询钉钉扫码会话状态(管理员)", + "responses": { + "200": { + "$ref": "#/components/responses/Envelope" + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "500": { + "$ref": "#/components/responses/InternalError" + } + } + }, + "delete": { + "tags": [ + "Source connections" + ], + "operationId": "cancelDingtalkSession", + "summary": "取消钉钉扫码会话(管理员)", + "responses": { + "200": { + "$ref": "#/components/responses/Envelope" + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "500": { + "$ref": "#/components/responses/InternalError" + } + } + } + }, "/api/v1/source-connections": { "get": { "tags": [ diff --git a/compose.yaml b/compose.yaml index 0c0ef91..7d1c6f9 100644 --- a/compose.yaml +++ b/compose.yaml @@ -33,6 +33,7 @@ services: WORKER_LEASE_DURATION: 30s WORKER_RETRY_DELAY: 5s TEST_WEKNORA_BASE_URL: "${TEST_WEKNORA_BASE_URL:-}" + DINGTALK_LOGIN_SIDECAR_URL: "http://dingtalk-login:8091" MINERU_BASE_URL: "${MINERU_BASE_URL:-}" TEST_INTERNAL_WEKNORA_KB_ID: "${TEST_INTERNAL_WEKNORA_KB_ID:-1b52c140-2e18-4676-afc5-4c7d8d190a8c}" TEST_EXTERNAL_WEKNORA_KB_ID: "${TEST_EXTERNAL_WEKNORA_KB_ID:-fd7db6aa-763a-46f1-84d2-ecc7c952a5ea}" @@ -133,6 +134,33 @@ services: - /tmp restart: unless-stopped + dingtalk-login: + # Chromium profile for DingTalk scan sessions. The bind-mounted secrets + # directory is rw ONLY here; the worker keeps reading the capture read-only. + build: + context: ./services/dingtalk-login + image: knowledge-governance-dingtalk-login:local + user: "${APP_UID:-1000}:${APP_GID:-1000}" + environment: + CAPTURE_FILE: /run/source-secrets/dingtalk_capture.json + VERIFY_SPACE: "${DINGTALK_VERIFY_SPACE:-9JOGO6332vlBnm4Q}" + QR_TTL_MS: "300000" + volumes: + - ./secrets:/run/source-secrets + - dingtalk-chromium-profile:/profile + security_opt: + - no-new-privileges:true + tmpfs: + - /tmp + healthcheck: + test: ["CMD", "node", "-e", "require('http').get('http://127.0.0.1:8091/healthz',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"] + interval: 10s + timeout: 5s + retries: 30 + start_period: 15s + restart: unless-stopped + + web: build: context: . @@ -159,6 +187,7 @@ secrets: volumes: governance-pgdata: + dingtalk-chromium-profile: networks: weknora-local: diff --git a/internal/httpapi/auth.go b/internal/httpapi/auth.go index 02ac97f..6d01900 100644 --- a/internal/httpapi/auth.go +++ b/internal/httpapi/auth.go @@ -117,6 +117,12 @@ func classifyRole(method, path string) string { if strings.Contains(path, "/settings/revisions") { return roleAdmin } + // The DingTalk scan session replaces the shared browser credentials: + // admin-only, like every other credential surface. The QR image is a + // login artifact, so even polling it stays admin-only. + if strings.HasPrefix(path, "/api/v1/dingtalk-session") { + return roleAdmin + } // Binding the internal/external knowledge bases re-routes every future // annotation: admin-only, like the roster and production authority. if path == "/api/v1/routing-bindings" && method != http.MethodGet { diff --git a/internal/httpapi/dingtalk_session.go b/internal/httpapi/dingtalk_session.go new file mode 100644 index 0000000..0607932 --- /dev/null +++ b/internal/httpapi/dingtalk_session.go @@ -0,0 +1,129 @@ +package httpapi + +import ( + "bytes" + "encoding/json" + "io" + "log" + "net/http" + "os" + "strings" + "time" +) + +// DingTalk login proxy. The scan-code login itself lives in the +// dingtalk-login sidecar (headless Chromium); the API is the authenticated +// gate and browser relay, so no QR or token crosses the web origin without a +// session. classifyRole keeps every non-GET at engineer+; capture replacement +// remains a deliberate human action. +// +// POST /api/v1/dingtalk-session -> start a login session {space?} +// GET /api/v1/dingtalk-session/{id} -> poll state (qr_png while waiting) +// DELETE /api/v1/dingtalk-session/{id} -> abort a session + +func dingtalkSidecarURL() string { + return strings.TrimRight(strings.TrimSpace(os.Getenv("DINGTALK_LOGIN_SIDECAR_URL")), "/") +} + +func requireDingtalkIdentity(w http.ResponseWriter, r *http.Request) bool { + _, ok := requireSessionIdentity(w, r) + return ok +} + +func startDingtalkSession(w http.ResponseWriter, r *http.Request) { + if !requireDingtalkIdentity(w, r) { + return + } + var body struct { + Space string `json:"space"` + } + if r.Body != nil && r.ContentLength != 0 { + if err := decodeJSONStrict(r, &body); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_request_body"}) + return + } + } + payload, _ := json.Marshal(map[string]string{"space": strings.TrimSpace(body.Space)}) + status, data := proxyDingtalk(http.MethodPost, "/sessions", payload) + log.Printf("dingtalk-login session started by %s (status %d)", actorFor(r), status) + writeProxyResult(w, status, data) +} + +func getDingtalkSession(w http.ResponseWriter, r *http.Request) { + if !requireDingtalkIdentity(w, r) { + return + } + id := safeSessionID(r.PathValue("id")) + if id == "" { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_session_id"}) + return + } + status, data := proxyDingtalk(http.MethodGet, "/sessions/"+id, nil) + writeProxyResult(w, status, data) +} + +func deleteDingtalkSession(w http.ResponseWriter, r *http.Request) { + if !requireDingtalkIdentity(w, r) { + return + } + id := safeSessionID(r.PathValue("id")) + if id == "" { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_session_id"}) + return + } + status, data := proxyDingtalk(http.MethodDelete, "/sessions/"+id, nil) + log.Printf("dingtalk-login session %s closed by %s", id, actorFor(r)) + writeProxyResult(w, status, data) +} + +func safeSessionID(id string) string { + id = strings.TrimSpace(id) + if id == "" || len(id) > 64 { + return "" + } + for _, c := range id { + if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-') { + return "" + } + } + return id +} + +func writeProxyResult(w http.ResponseWriter, status int, data []byte) { + if status == 0 || data == nil { + writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "dingtalk_login_unavailable"}) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = w.Write(data) +} + +func proxyDingtalk(method, path string, body []byte) (int, []byte) { + base := dingtalkSidecarURL() + if base == "" { + return 0, nil + } + var reader io.Reader + if body != nil { + reader = bytes.NewReader(body) + } + req, err := http.NewRequest(method, base+path, reader) + if err != nil { + return 0, nil + } + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + client := &http.Client{Timeout: 15 * time.Second} + resp, err := client.Do(req) + if err != nil { + return 0, nil + } + defer resp.Body.Close() + data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) + if err != nil { + return resp.StatusCode, nil + } + return resp.StatusCode, data +} diff --git a/internal/httpapi/dingtalk_session_test.go b/internal/httpapi/dingtalk_session_test.go new file mode 100644 index 0000000..72eaac9 --- /dev/null +++ b/internal/httpapi/dingtalk_session_test.go @@ -0,0 +1,85 @@ +package httpapi + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestDingtalkSessionProxyRelaysSidecarStates(t *testing.T) { + sidecar := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodPost && r.URL.Path == "/sessions": + w.WriteHeader(http.StatusCreated) + _ = json.NewEncoder(w).Encode(map[string]any{"id": "abc123", "state": "qr", "created_at": 1, "expires_at": 2}) + case r.Method == http.MethodGet && r.URL.Path == "/sessions/abc123": + _ = json.NewEncoder(w).Encode(map[string]any{"id": "abc123", "state": "success"}) + case r.Method == http.MethodGet && r.URL.Path == "/sessions/missing": + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error":"session_not_found"}`)) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer sidecar.Close() + t.Setenv("DINGTALK_LOGIN_SIDECAR_URL", sidecar.URL) + + start := httptest.NewRequest(http.MethodPost, "/api/v1/dingtalk-session", strings.NewReader(`{}`)) + start = start.WithContext(context.WithValue(start.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin})) + rec := httptest.NewRecorder() + startDingtalkSession(rec, start) + if rec.Code != http.StatusCreated { + t.Fatalf("start proxy status = %d body=%s", rec.Code, rec.Body.String()) + } + var created map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &created); err != nil { + t.Fatal(err) + } + if created["state"] != "qr" { + t.Fatalf("relayed state = %v", created["state"]) + } + + poll := httptest.NewRequest(http.MethodGet, "/api/v1/dingtalk-session/abc123", nil) + poll = poll.WithContext(context.WithValue(poll.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin})) + poll.SetPathValue("id", "abc123") + rec = httptest.NewRecorder() + getDingtalkSession(rec, poll) + if !strings.Contains(rec.Body.String(), `"success"`) { + t.Fatalf("poll body = %s", rec.Body.String()) + } + + missing := httptest.NewRequest(http.MethodGet, "/api/v1/dingtalk-session/missing", nil) + missing = missing.WithContext(context.WithValue(missing.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin})) + missing.SetPathValue("id", "missing") + rec = httptest.NewRecorder() + getDingtalkSession(rec, missing) + if rec.Code != http.StatusNotFound { + t.Fatalf("missing status = %d", rec.Code) + } +} + +func TestDingtalkSessionRejectsUnauthenticatedAndHostileIDs(t *testing.T) { + rec := httptest.NewRecorder() + startDingtalkSession(rec, httptest.NewRequest(http.MethodPost, "/api/v1/dingtalk-session", nil)) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("unauthenticated start = %d, want 401", rec.Code) + } + if got := safeSessionID("../etc/passwd"); got != "" { + t.Fatalf("hostile id accepted: %q", got) + } +} + +func TestDingtalkSessionUnavailableWithoutSidecar(t *testing.T) { + t.Setenv("DINGTALK_LOGIN_SIDECAR_URL", "") + req := httptest.NewRequest(http.MethodGet, "/api/v1/dingtalk-session/abc", nil) + req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin})) + req.SetPathValue("id", "abc") + rec := httptest.NewRecorder() + getDingtalkSession(rec, req) + if rec.Code != http.StatusServiceUnavailable { + t.Fatalf("sidecar down status = %d, want 503", rec.Code) + } +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 1d5214c..8e36dc7 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -255,6 +255,15 @@ func NewHandler(config Config) (http.Handler, error) { mux.HandleFunc("GET /api/v1/source-connections", func(w http.ResponseWriter, r *http.Request) { listSourceConnections(w, r, config.Store) }) + mux.HandleFunc("POST /api/v1/dingtalk-session", func(w http.ResponseWriter, r *http.Request) { + startDingtalkSession(w, r) + }) + mux.HandleFunc("GET /api/v1/dingtalk-session/{id}", func(w http.ResponseWriter, r *http.Request) { + getDingtalkSession(w, r) + }) + mux.HandleFunc("DELETE /api/v1/dingtalk-session/{id}", func(w http.ResponseWriter, r *http.Request) { + deleteDingtalkSession(w, r) + }) mux.HandleFunc("POST /api/v1/source-connections/{id}/scan", func(w http.ResponseWriter, r *http.Request) { triggerPPSourceScan(w, r, config) }) diff --git a/services/dingtalk-login/Dockerfile b/services/dingtalk-login/Dockerfile new file mode 100644 index 0000000..e4f860e --- /dev/null +++ b/services/dingtalk-login/Dockerfile @@ -0,0 +1,23 @@ +# DingTalk login sidecar: drives a headless Chromium to capture scan-code +# sessions and atomically refresh the browser capture file that the +# governance scanners read from /run/source-secrets. +FROM docker.m.daocloud.io/library/node:22-bookworm-slim + +ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright \ + PLAYWRIGHT_DOWNLOAD_HOST=https://cdn.npmmirror.com/binaries/playwright \ + NODE_ENV=production + +WORKDIR /app +COPY package.json ./ +RUN npm install --registry=https://registry.npmmirror.com +# Chromium + system deps for Playwright. +RUN apt-get update \ + && PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npx playwright install-deps chromium \ + && rm -rf /var/lib/apt/lists/* +RUN npx playwright install chromium + +COPY server.mjs ./ +RUN mkdir -p /profile && chown node:node /profile +USER node +EXPOSE 8091 +CMD ["node", "server.mjs"] diff --git a/services/dingtalk-login/package.json b/services/dingtalk-login/package.json new file mode 100644 index 0000000..9bd36a4 --- /dev/null +++ b/services/dingtalk-login/package.json @@ -0,0 +1,9 @@ +{ + "name": "dingtalk-login-sidecar", + "private": true, + "type": "module", + "version": "1.0.0", + "dependencies": { + "playwright": "1.55.0" + } +} diff --git a/services/dingtalk-login/server.mjs b/services/dingtalk-login/server.mjs new file mode 100644 index 0000000..524ccda --- /dev/null +++ b/services/dingtalk-login/server.mjs @@ -0,0 +1,178 @@ +// DingTalk login sidecar for the knowledge governance platform. +// Drives a persistent headless Chromium. A login session opens the target +// space page, screenshots the QR code when the browser session is dead, +// watches for a real authenticated XHR to fly, validates it, then atomically +// writes the scanner capture file. Tokens never leave this container except +// inside the written capture file. +import { chromium } from "playwright"; +import fs from "node:fs"; +import path from "node:path"; +import http from "node:http"; +import crypto from "node:crypto"; + +const PORT = Number(process.env.PORT || 8091); +const PROFILE_DIR = process.env.PROFILE_DIR || "/profile"; +const CAPTURE_FILE = process.env.CAPTURE_FILE || "/secrets/dingtalk_capture.json"; +const VERIFY_SPACE = process.env.VERIFY_SPACE || "9JOGO6332vlBnm4Q"; +const QR_TTL_MS = Number(process.env.QR_TTL_MS || 5 * 60 * 1000); +const SCAN_URL = (space) => `https://alidocs.dingtalk.com/i/spaces/${space}/overview`; + +const sessions = new Map(); + +function redacted(s) { + return { + id: s.id, state: s.state, created_at: s.createdAt, expires_at: s.expiresAt, + ...(s.error ? { error: s.error } : {}), + ...(s.qrPng ? { qr_png: s.qrPng } : {}), + }; +} + +function scheduleCleanup(s) { + setTimeout(() => { closeSession(s.id); }, Math.max(0, s.expiresAt - Date.now())).unref?.(); +} + +function closeSession(id) { + const s = sessions.get(id); + if (!s) return; + s.state = "closed"; + sessions.delete(id); + s.context?.close().catch(() => {}); +} + +// Keep at most a couple of live login contexts. +function evictOld() { + const live = [...sessions.values()].sort((a, b) => a.createdAt - b.createdAt); + while (live.length > 3) closeSession(live.shift().id); +} + +function validateHeadersSync(headers) { + return Boolean(headers["a-token"] && headers["cookie"]); +} + +async function validateHeaders(page, headers) { + try { + const result = await page.evaluate(async (h) => { + const r = await fetch(`https://alidocs.dingtalk.com/box/api/v2/dentry/list?dentryUuid=${h.space}&withParentAncestors=true&orderType=SORT_KEY&sortType=desc&listDentrySource=2&pageSize=1`, { + headers: { accept: "application/json", "a-token": h.at, "x-xsrf-token": h.xsrf }, credentials: "include", + }); + const body = await r.text(); + return { status: r.status, ok: r.status === 200 && body.includes("spaceProfile"), name: (body.match(/"name":"([^"]{1,60})"/) || [])[1] }; + }, { space: VERIFY_SPACE, at: headers["a-token"], xsrf: headers["x-xsrf-token"] || "" }); + return result; + } catch (e) { + return { status: -1, ok: false, error: String(e) }; + } +} + +function writeCapture(headers) { + const payload = { + capturedAt: new Date().toISOString(), + method: "GET", + url: `https://alidocs.dingtalk.com/box/api/v2/dentry/list?dentryUuid=${VERIFY_SPACE}`, + headers, + }; + // The scanner reads this file through a single-file bind mount: replacing + // the file (rename) would swap the inode and the reader would keep seeing + // the old session. Write in place instead. + const fd = fs.openSync(CAPTURE_FILE, "w", 0o600); + fs.writeFileSync(fd, JSON.stringify(payload, null, 2)); + fs.fsyncSync(fd); + fs.closeSync(fd); +} + +async function startSession(id, space) { + const s = sessions.get(id); + if (!s) return; + let context; + try { + context = await chromium.launchPersistentContext(PROFILE_DIR, { + headless: true, viewport: { width: 1280, height: 900 }, locale: "zh-CN", + }); + } catch (e) { + s.state = "failed"; s.error = "browser_launch_failed"; return; + } + s.context = context; + const page = context.pages()[0] ?? await context.newPage(); + + let capturedHeaders = null; + const finish = async (headers, via) => { + const v = await validateHeaders(page, headers); + if (v.ok) { + writeCapture(headers); + s.state = "success"; s.spaceName = v.name || ""; s.error = null; + } else { + s.state = "failed"; s.error = "capture_validation_failed"; + } + scheduleCleanup(s); + }; + + page.on("request", (request) => { + const url = request.url(); + if (!url.includes("dingtalk.com")) return; + const h = request.headers(); + if (!h["a-token"] || !h.cookie) return; + if (capturedHeaders) return; + capturedHeaders = { ...h }; + delete capturedHeaders["content-length"]; + delete capturedHeaders["accept-encoding"]; + delete capturedHeaders["host"]; + if (validateHeadersSync(capturedHeaders)) { + s.state = s.state === "qr" ? "scanned" : "reusing"; + if (!s.tokenSeen) { s.tokenSeen = true; finish(capturedHeaders, "request"); } + } + }); + + await page.goto(SCAN_URL(space), { waitUntil: "domcontentloaded", timeout: 45000 }).catch(() => {}); + + if (page.url().includes("login.dingtalk.com") && !capturedHeaders) { + // Session is dead: expose the QR code for scanning. + try { + const qr = page.locator("canvas, [class*=qrcode], [class*=QR], img[src*=qrcode]").first(); + const png = (await qr.count()) ? await qr.screenshot({ timeout: 5000 }) : await page.screenshot({ clip: { x: 340, y: 60, width: 600, height: 640 } }); + s.qrPng = png.toString("base64"); + } catch { + try { s.qrPng = (await page.screenshot()).toString("base64"); } catch { /* keep state=qr anyway */ } + } + s.state = "qr"; + // Poll for the token to appear after a scan (request listener does the rest). + const deadline = Date.now() + QR_TTL_MS; + const timer = setInterval(() => { + if (s.tokenSeen) { clearInterval(timer); return; } + if (Date.now() > deadline) { + clearInterval(timer); + if (!s.tokenSeen) { s.state = "expired"; scheduleCleanup(s); } + } + }, 2000); + timer.unref?.(); + } +} + +const server = http.createServer(async (req, res) => { + const url = new URL(req.url, `http://127.0.0.1:${PORT}`); + const send = (code, obj) => { res.writeHead(code, { "content-type": "application/json" }); res.end(JSON.stringify(obj)); }; + if (req.method === "GET" && url.pathname === "/healthz") return send(200, { status: "ok" }); + const sessionMatch = url.pathname.match(/^\/sessions\/([\w-]+)$/); + if (req.method === "POST" && url.pathname === "/sessions") { + evictOld(); + let body = ""; + for await (const chunk of req) { body += chunk; if (body.length > 4096) break; } + let space = VERIFY_SPACE; + try { const raw = String(JSON.parse(body || "{}").space || "").replace(/[^\w]/g, ""); space = raw || VERIFY_SPACE; } catch { /* default */ } + const id = crypto.randomBytes(9).toString("hex"); + sessions.set(id, { id, state: "starting", space, createdAt: Date.now(), expiresAt: Date.now() + QR_TTL_MS + 60000 }); + startSession(id, space); + return send(201, redacted(sessions.get(id))); + } + if (req.method === "GET" && sessionMatch) { + const s = sessions.get(sessionMatch[1]); + if (!s) return send(404, { error: "session_not_found" }); + return send(200, redacted(s)); + } + if (req.method === "DELETE" && sessionMatch) { + closeSession(sessionMatch[1]); + return send(200, { status: "closed" }); + } + send(404, { error: "not_found" }); +}); + +server.listen(PORT, "0.0.0.0", () => console.log(`dingtalk-login sidecar on :${PORT}`)); diff --git a/web/src/DingtalkSessionControl.test.tsx b/web/src/DingtalkSessionControl.test.tsx new file mode 100644 index 0000000..42a181c --- /dev/null +++ b/web/src/DingtalkSessionControl.test.tsx @@ -0,0 +1,15 @@ +import { renderToStaticMarkup } from 'react-dom/server' +import { describe,expect,it,vi } from 'vitest' +import { DingtalkSessionControl } from './DingtalkSessionControl' + +describe('DingtalkSessionControl',()=>{ + it('renders the admin scan button without firing any request',()=>{ + const fetchMock=vi.fn() + vi.stubGlobal('fetch',fetchMock) + const markup=renderToStaticMarkup() + expect(markup).toContain('扫码刷新会话') + expect(markup).not.toContain('modal-backdrop') + expect(fetchMock).not.toHaveBeenCalled() + vi.unstubAllGlobals() + }) +}) diff --git a/web/src/DingtalkSessionControl.tsx b/web/src/DingtalkSessionControl.tsx new file mode 100644 index 0000000..8b26860 --- /dev/null +++ b/web/src/DingtalkSessionControl.tsx @@ -0,0 +1,72 @@ +import { useEffect, useRef, useState } from 'react' + +import { cancelDingtalkSession, fetchDingtalkSession, startDingtalkSession } from './dingtalkSession' +import type { DingtalkSessionView } from './dingtalkSession' + +// Admin-only card control: "扫码刷新会话" opens a login session against the +// dingtalk-login sidecar, shows its QR, and reports the capture result. The +// token never reaches this component — only state and the QR image. + +const finished = new Set(['success', 'expired', 'failed', 'closed']) + +export function DingtalkSessionControl() { + const [session, setSession] = useState(null) + const [failure, setFailure] = useState(null) + const [starting, setStarting] = useState(false) + const idRef = useRef(null) + + useEffect(() => () => { if (idRef.current) void cancelDingtalkSession(idRef.current) }, []) + + useEffect(() => { + if (!session || finished.has(session.state)) return + const timer = setInterval(() => { + fetchDingtalkSession(session.id).then(setSession).catch(() => undefined) + }, 1500) + return () => clearInterval(timer) + }, [session?.id, session?.state]) + + const start = async () => { + setStarting(true); setFailure(null) + try { + const fresh = await startDingtalkSession() + idRef.current = fresh.id + setSession(fresh) + } catch (cause) { + setFailure(cause instanceof Error ? cause.message : '发起扫码会话失败') + } finally { + setStarting(false) + } + } + + const close = () => { + if (idRef.current) void cancelDingtalkSession(idRef.current) + idRef.current = null + setSession(null) + } + + const stateLabel: Record = { + starting: '正在打开登录页…', qr: '请用钉钉 App 扫码登录', scanned: '已扫码,正在获取会话…', + reusing: '检测到有效浏览器会话,正在验证…', success: '✅ 钉钉扫码会话已刷新,扫描任务可继续使用', + expired: '二维码已过期,请重新发起', failed: '会话验证失败,请重试或联系管理员', closed: '会话已关闭', + } + + return
+ + {failure ?

{failure}

: null} + {session ?
+
+

刷新钉钉扫码会话

+

{stateLabel[session.state] ?? session.state}

+ {session.qr_png && session.state === 'qr' ? 钉钉登录二维码 : null} + {session.error ?

{session.error}

: null} +
+ {finished.has(session.state) + ? + : } +
+
+
: null} +
+} diff --git a/web/src/SystemSettings.tsx b/web/src/SystemSettings.tsx index 0f066d3..0228e58 100644 --- a/web/src/SystemSettings.tsx +++ b/web/src/SystemSettings.tsx @@ -1,6 +1,7 @@ import { useCallback, useEffect, useState } from 'react' import { MembersSection } from './MembersSection' +import { DingtalkSessionControl } from './DingtalkSessionControl' import { RoutingBindingsSection } from './RoutingBindingsSection' import { useOptionalAuth } from './auth' import { fetchMonitorOverview } from './monitor' @@ -61,6 +62,8 @@ function formatHorizon(value: string | null): string { } function SourceSettingsCard({ connection, onSourcesChanged }: { connection: SourceConnectionListItem; onSourcesChanged: () => void }) { + const auth = useOptionalAuth() + const isAdmin = auth?.identity?.role === 'admin' const [interval, setInterval] = useState(() => { if (!connection.next_refresh_at) return 0 const remaining = new Date(connection.next_refresh_at).getTime() - Date.now() @@ -117,6 +120,7 @@ function SourceSettingsCard({ connection, onSourcesChanged }: { connection: Sour ?
:
} + {connection.source_type === "dingtalk" && isAdmin ? : null} {message ?

{message}

: null} diff --git a/web/src/dingtalkSession.ts b/web/src/dingtalkSession.ts new file mode 100644 index 0000000..934de04 --- /dev/null +++ b/web/src/dingtalkSession.ts @@ -0,0 +1,56 @@ +import { newOperationID } from './operationKey' + +// Client for the admin-only DingTalk scan-code session (系统设置 → 数据源配置). +// The API proxies to the dingtalk-login sidecar; this module never sees the +// token itself — only the base64 QR image and a terminal state. + +export type DingtalkSessionState = 'starting' | 'qr' | 'scanned' | 'reusing' | 'success' | 'expired' | 'failed' | 'closed' + +export interface DingtalkSessionView { + id: string + state: DingtalkSessionState + created_at: number + expires_at: number + qr_png?: string + error?: string +} + +const sessionStates = new Set(['starting', 'qr', 'scanned', 'reusing', 'success', 'expired', 'failed', 'closed']) + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +export async function startDingtalkSession(space?: string): Promise { + const response = await fetch('/api/v1/dingtalk-session', { + method: 'POST', + headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Governance-Action': 'dingtalk-session', 'Idempotency-Key': newOperationID() }, + body: JSON.stringify(space ? { space } : {}), + }) + if (!response.ok) throw new Error(`发起钉钉扫码会话失败(HTTP ${response.status})`) + return parseSession(await response.json()) +} + +export async function fetchDingtalkSession(id: string, signal?: AbortSignal): Promise { + const response = await fetch(`/api/v1/dingtalk-session/${encodeURIComponent(id)}`, { headers: { Accept: 'application/json' }, signal }) + if (!response.ok) throw new Error(`读取钉钉扫码会话失败(HTTP ${response.status})`) + return parseSession(await response.json()) +} + +export async function cancelDingtalkSession(id: string): Promise { + await fetch(`/api/v1/dingtalk-session/${encodeURIComponent(id)}`, { method: 'DELETE', headers: { Accept: 'application/json' } }).catch(() => undefined) +} + +function parseSession(value: unknown): DingtalkSessionView { + if (!isRecord(value) || typeof value.id !== 'string' || typeof value.state !== 'string' || !sessionStates.has(value.state)) { + throw new Error('invalid dingtalk session response') + } + return { + id: value.id, + state: value.state as DingtalkSessionState, + created_at: typeof value.created_at === 'number' ? value.created_at : 0, + expires_at: typeof value.expires_at === 'number' ? value.expires_at : 0, + qr_png: typeof value.qr_png === 'string' ? value.qr_png : undefined, + error: typeof value.error === 'string' ? value.error : undefined, + } +} diff --git a/web/src/systemSettings.css b/web/src/systemSettings.css index 553ed38..cb3ae41 100644 --- a/web/src/systemSettings.css +++ b/web/src/systemSettings.css @@ -27,3 +27,8 @@ button.link{background:none;border:none;color:var(--c-run);cursor:pointer;text-d .modal-actions{display:flex;gap:10px;justify-content:flex-end;margin-top:14px} @media (max-width:900px){.settings-layout{grid-template-columns:1fr}.settings-nav{position:static;flex-direction:row;flex-wrap:wrap}} .kb-binding-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:12px 0}.kb-binding-side{display:grid;gap:4px;border:1px solid var(--border-base);border-radius:9px;padding:11px;background:var(--bg-soft)}.kb-binding-side.bound{border-color:var(--c-done)}.kb-binding-side.warn{border-color:var(--c-fail)}.kb-binding-side b{color:var(--ink-base);font-size:11px}.kb-binding-side span{color:var(--c-done);font-size:11px;word-break:break-all}.kb-binding-side.warn span{color:var(--c-fail)}.kb-binding-side small{color:var(--ink-mute);font-size:9px}.kb-binding-editor{display:grid;gap:10px;border-top:1px dashed var(--border-base);margin-top:8px;padding-top:12px}.kb-binding-editor label{display:grid;gap:6px;color:var(--ink-mute);font-size:10px}.kb-binding-editor select,.kb-binding-editor input{border:1px solid var(--border-strong);border-radius:7px;padding:8px;background:var(--bg-panel);color:var(--ink-base)}.kb-binding-editor button{justify-self:start;padding:7px 10px}@media(max-width:650px){.kb-binding-grid{grid-template-columns:1fr}}.hint{color:var(--ink-mute);font-size:10px;margin:4px 0} +.dingtalk-session-control{display:flex;flex-direction:column;gap:4px;align-self:end} +.dingtalk-qr-card{max-width:360px;text-align:center} +.dingtalk-qr-hint{color:var(--ink-mute);font-size:13px;min-height:20px} +.dingtalk-qr-image{display:block;margin:10px auto;width:240px;height:240px;image-rendering:pixelated;border:1px solid var(--border-base);border-radius:10px;background:#fff} +.dingtalk-qr-card .modal-actions{justify-content:center}