fix(settings): add DingTalk spaces and render the real login QR
Address two gaps in the first DingTalk-session UI: - add an explicit admin-only '+ 新增钉钉知识库' action on the data-source panel; it accepts an alidocs space URL, resolves the live name/root through the authenticated sidecar, writes the inventory root atomically, upserts a deterministic source connection, and enqueues its first catalog refresh - read DingTalk's real QR canvas pixels rather than taking a DOM screenshot; select by dark-pixel content, composite onto a white quiet zone, and render at 320x320 so the dialog contains a large complete code, not a page thumbnail The live refresh path resolves registered roots from the connection locator, while existing name-based DingTalk sources remain compatible.
This commit is contained in:
@@ -1,18 +1,17 @@
|
||||
// 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.
|
||||
// Drives a persistent headless Chromium for scan-code login, and uses the
|
||||
// resulting capture (a-token + cookie headers, exactly what the scanner
|
||||
// replays) to resolve and register knowledge-base spaces. Tokens never leave
|
||||
// this container except inside the 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 STATE_FILE = process.env.DINGTALK_STATE_FILE || "";
|
||||
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`;
|
||||
@@ -39,29 +38,19 @@ function closeSession(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"]);
|
||||
}
|
||||
// ---------- capture ----------
|
||||
|
||||
async function validateHeaders(page, headers) {
|
||||
function loadCapture() {
|
||||
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) };
|
||||
}
|
||||
const capture = JSON.parse(fs.readFileSync(CAPTURE_FILE, "utf8"));
|
||||
const h = capture.headers || {};
|
||||
return h["a-token"] ? h : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
function writeCapture(headers) {
|
||||
@@ -80,6 +69,81 @@ function writeCapture(headers) {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
|
||||
// ---------- box API via the captured browser headers ----------
|
||||
|
||||
async function boxApi(headers, path) {
|
||||
const res = await fetch("https://alidocs.dingtalk.com" + path, {
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
"a-token": headers["a-token"],
|
||||
"x-xsrf-token": headers["x-xsrf-token"] || "",
|
||||
cookie: headers.cookie || "",
|
||||
"user-agent": headers["user-agent"] || "Mozilla/5.0",
|
||||
referer: "https://alidocs.dingtalk.com/",
|
||||
},
|
||||
});
|
||||
let body = null;
|
||||
try { body = await res.json(); } catch { /* non-json */ }
|
||||
return { status: res.status, body };
|
||||
}
|
||||
|
||||
function extractSpace(value) {
|
||||
const text = String(value || "").trim();
|
||||
const m = text.match(/\/spaces\/([A-Za-z0-9_-]+)/) || (/^[A-Za-z0-9_-]{8,64}$/.test(text) ? [null, text] : null);
|
||||
return m ? m[1] : null;
|
||||
}
|
||||
|
||||
async function resolveSpace(spaceId) {
|
||||
const headers = loadCapture();
|
||||
if (!headers) return { error: "login_required" };
|
||||
const { status, body } = await boxApi(headers,
|
||||
`/box/api/v2/dentry/list?dentryUuid=${encodeURIComponent(spaceId)}&withParentAncestors=true&orderType=SORT_KEY&sortType=desc&listDentrySource=2&pageSize=5`);
|
||||
if (status === 401 || (body && body.code === "52600001")) return { error: "login_required" };
|
||||
const sp = body && body.data && body.data.spaceProfile;
|
||||
if (status !== 200 || !sp || !sp.rootDentryUuid || !sp.name) return { error: "space_not_found", http_status: status };
|
||||
return { space_id: spaceId, name: String(sp.name).slice(0, 120), root: String(sp.rootDentryUuid) };
|
||||
}
|
||||
|
||||
function loadState() {
|
||||
if (!STATE_FILE) throw new Error("state file not configured");
|
||||
return JSON.parse(fs.readFileSync(STATE_FILE, "utf8"));
|
||||
}
|
||||
|
||||
async function addSpace(spaceId, label) {
|
||||
const resolved = await resolveSpace(spaceId);
|
||||
if (resolved.error) return resolved;
|
||||
const state = loadState();
|
||||
const roots = state.roots || (state.roots = {});
|
||||
const existing = Object.entries(roots).find(([, r]) => r.configured_root_id === resolved.root);
|
||||
const rootKey = /^[a-z][a-z0-9_-]{1,31}$/.test(label || "") ? label : existing ? existing[0] : "space-" + crypto.createHash("sha256").update(spaceId).digest("hex").slice(0, 10);
|
||||
const clash = Object.entries(roots).find(([k, r]) => r.live_space_name === resolved.name && k !== rootKey);
|
||||
if (clash) return { error: "name_conflict", message: `已登记同名空间「${resolved.name}」` };
|
||||
if (!roots[rootKey]) {
|
||||
roots[rootKey] = {
|
||||
configured_root_id: resolved.root,
|
||||
// Seed the live name so the refresh job matches this root immediately;
|
||||
// the scanner confirms/overwrites it from the same spaceProfile.
|
||||
live_space_name: resolved.name,
|
||||
queue: [resolved.root],
|
||||
scanned_folders: [],
|
||||
nodes: {},
|
||||
errors: [],
|
||||
};
|
||||
} else {
|
||||
roots[rootKey].live_space_name = resolved.name;
|
||||
roots[rootKey].configured_root_id = resolved.root;
|
||||
}
|
||||
// The inventory state is reached through a DIRECTORY bind mount: readers
|
||||
// open it by path, so an atomic temp+rename swap is safe and avoids
|
||||
// exposing half-written JSON to a refresh that starts mid-write.
|
||||
const tmp = STATE_FILE + ".tmp";
|
||||
fs.writeFileSync(tmp, JSON.stringify(state, null, 2));
|
||||
fs.renameSync(tmp, STATE_FILE);
|
||||
return { key: rootKey, name: resolved.name, root: resolved.root, reused: Boolean(existing) };
|
||||
}
|
||||
|
||||
// ---------- login sessions ----------
|
||||
|
||||
async function startSession(id, space) {
|
||||
const s = sessions.get(id);
|
||||
if (!s) return;
|
||||
@@ -87,22 +151,24 @@ async function startSession(id, space) {
|
||||
try {
|
||||
context = await chromium.launchPersistentContext(PROFILE_DIR, {
|
||||
headless: true, viewport: { width: 1280, height: 900 }, locale: "zh-CN",
|
||||
deviceScaleFactor: 3, // crisp QR: canvas screenshots inherit DPR
|
||||
});
|
||||
} catch (e) {
|
||||
} catch {
|
||||
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) {
|
||||
const finish = async (headers) => {
|
||||
const probe = await boxApi(headers, `/box/api/v2/dentry/list?dentryUuid=${VERIFY_SPACE}&pageSize=1&orderType=SORT_KEY&sortType=desc&listDentrySource=2&withParentAncestors=true`);
|
||||
if (probe.status === 200 && probe.body && probe.body.data && probe.body.data.spaceProfile) {
|
||||
writeCapture(headers);
|
||||
s.state = "success"; s.spaceName = v.name || ""; s.error = null;
|
||||
s.state = "success"; s.error = null;
|
||||
} else {
|
||||
s.state = "failed"; s.error = "capture_validation_failed";
|
||||
}
|
||||
s.expiresAt = Math.max(s.expiresAt, Date.now() + 30000);
|
||||
scheduleCleanup(s);
|
||||
};
|
||||
|
||||
@@ -110,67 +176,117 @@ async function startSession(id, space) {
|
||||
const url = request.url();
|
||||
if (!url.includes("dingtalk.com")) return;
|
||||
const h = request.headers();
|
||||
if (!h["a-token"] || !h.cookie) return;
|
||||
if (capturedHeaders) return;
|
||||
if (!h["a-token"] || !h.cookie || 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"); }
|
||||
}
|
||||
s.state = s.state === "qr" ? "scanned" : "reusing";
|
||||
finish(capturedHeaders);
|
||||
});
|
||||
|
||||
// Read the QR directly from DingTalk's canvas. Do NOT screenshot the DOM:
|
||||
// Playwright element screenshots on a high-DPR page can apply the crop in
|
||||
// device pixels twice, producing exactly the clipped page thumbnail the
|
||||
// user reported. canvas.toDataURL() returns the complete PNG pixels.
|
||||
const grabQR = async () => {
|
||||
try {
|
||||
return await page.evaluate(() => {
|
||||
let best = null, bestDark = 0;
|
||||
for (const el of document.querySelectorAll('canvas')) {
|
||||
const r = el.getBoundingClientRect();
|
||||
if (r.width < 100 || r.width > 460 || Math.abs(r.width - r.height) > 24) continue;
|
||||
try {
|
||||
const pixels = el.getContext('2d').getImageData(0, 0, el.width, el.height).data;
|
||||
let dark = 0;
|
||||
for (let i = 0; i < pixels.length; i += 4) {
|
||||
if (pixels[i + 3] > 0 && pixels[i] + pixels[i + 1] + pixels[i + 2] < 384) dark++;
|
||||
}
|
||||
if (dark > bestDark) { best = el; bestDark = dark; }
|
||||
} catch { /* unreadable canvas: not suitable */ }
|
||||
}
|
||||
if (!best || bestDark < 500) return null;
|
||||
// DingTalk's QR canvas has a transparent background and no guaranteed
|
||||
// quiet zone. Composite it onto white with 20px padding so phone
|
||||
// scanners and ordinary QR decoders get a complete code.
|
||||
const padding = 20;
|
||||
const out = document.createElement('canvas');
|
||||
out.width = best.width + padding * 2;
|
||||
out.height = best.height + padding * 2;
|
||||
const ctx = out.getContext('2d');
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.fillRect(0, 0, out.width, out.height);
|
||||
ctx.drawImage(best, padding, padding);
|
||||
const url = out.toDataURL('image/png');
|
||||
return url.startsWith('data:image/png;base64,') ? url.slice('data:image/png;base64,'.length) : null;
|
||||
});
|
||||
} catch { return null; }
|
||||
};
|
||||
|
||||
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.qrPng = await grabQR();
|
||||
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; }
|
||||
const regrab = setInterval(async () => {
|
||||
// Keep the freshest frame while waiting for the scan.
|
||||
if (capturedHeaders) return;
|
||||
try { const png = await grabQR(); if (png) s.qrPng = png; } catch { /* ignore */ }
|
||||
if (Date.now() > deadline) {
|
||||
clearInterval(timer);
|
||||
if (!s.tokenSeen) { s.state = "expired"; scheduleCleanup(s); }
|
||||
clearInterval(regrab);
|
||||
if (!capturedHeaders) { s.state = "expired"; scheduleCleanup(s); }
|
||||
}
|
||||
}, 2000);
|
||||
timer.unref?.();
|
||||
}, 8000);
|
||||
regrab.unref?.();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- HTTP ----------
|
||||
|
||||
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();
|
||||
const readJson = async () => {
|
||||
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" });
|
||||
for await (const chunk of req) { body += chunk; if (body.length > 8192) break; }
|
||||
try { return JSON.parse(body || "{}"); } catch { return {}; }
|
||||
};
|
||||
try {
|
||||
if (req.method === "GET" && url.pathname === "/healthz") return send(200, { status: "ok", state_configured: Boolean(STATE_FILE) });
|
||||
if (req.method === "POST" && url.pathname === "/sessions") {
|
||||
evictOld();
|
||||
const body = await readJson();
|
||||
const space = extractSpace(body.space) || VERIFY_SPACE;
|
||||
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)));
|
||||
}
|
||||
const sessionMatch = url.pathname.match(/^\/sessions\/([\w-]+)$/);
|
||||
if (sessionMatch) {
|
||||
const s = sessions.get(sessionMatch[1]);
|
||||
if (!s) return send(404, { error: "session_not_found" });
|
||||
if (req.method === "GET") return send(200, redacted(s));
|
||||
if (req.method === "DELETE") { closeSession(sessionMatch[1]); return send(200, { status: "closed" }); }
|
||||
}
|
||||
if (req.method === "POST" && (url.pathname === "/spaces/resolve" || url.pathname === "/spaces/add")) {
|
||||
const body = await readJson();
|
||||
const space = extractSpace(body.url || body.space);
|
||||
if (!space) return send(400, { error: "invalid_space_url" });
|
||||
if (url.pathname.endsWith("resolve")) {
|
||||
const r = await resolveSpace(space);
|
||||
return r.error ? send(r.error === "login_required" ? 409 : 404, r) : send(200, r);
|
||||
}
|
||||
const r = await addSpace(space, body.label);
|
||||
if (r.error) {
|
||||
const code = r.error === "login_required" ? 409 : r.error === "name_conflict" ? 409 : 404;
|
||||
return send(code, r);
|
||||
}
|
||||
return send(200, r);
|
||||
}
|
||||
} catch (e) {
|
||||
return send(500, { error: "sidecar_internal" });
|
||||
}
|
||||
send(404, { error: "not_found" });
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user