dsh-brain/lib/cloudsync-routes.js

282 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { describeError, isSecureLoginTarget } from "./api.js";
import { fail, json, jsonBody, readBody, sameOrigin } from "./http.js";
/** Path constants — kept in sync with the ROUTES map in routes.ts by hand. */
const PATHS = {
login: '/dsh-brain/login',
test: '/dsh-brain/test',
flush: '/dsh-brain/flush',
sync: '/dsh-brain/sync',
};
/** Last test run, kept in memory so the card can show "最后检查". */
let lastCheck = null;
/** The root status view reads the same probe memory; one source of truth. */
export function getLastCheck() {
return lastCheck;
}
/** Labels attached to the tokens this plugin asks the dashboard to mint. */
const TOKEN_LABELS = {
activity: 'DSH desktop 活动上报',
memory: 'DSH desktop 记忆读写',
summary: 'DSH desktop 对话摘要',
};
/** Map one failed credential probe onto a check state. */
function checkState(error) {
if (error.status === 0)
return 'unreachable';
if (error.status === 401)
return 'invalid';
if (error.status === 403)
return 'forbidden';
return 'error';
}
/** `POST /dsh-brain/test` — read-only checks, one per credential. */
async function serveTest(deps, req, res) {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
if (!sameOrigin(req)) {
fail(res, 403, 'origin-rejected');
return;
}
const client = deps.client();
const checks = [];
const settings = deps.store.settings();
const reach = await client.reach();
checks.push({
id: 'network',
label: '服务地址',
state: reach.ok ? 'ok' : 'unreachable',
message: deps.store.describe().baseUrlConfigured === false ? '服务地址还是打包默认值,请先填写真实地址。' : reach.message,
});
const activityToken = deps.store.activityToken();
if (activityToken === '') {
checks.push({ id: 'activity', label: '活动上报权限(activity:write)', state: 'unconfigured', message: '未配置令牌' });
}
else {
const probe = await client.probeActivity(activityToken);
checks.push({
id: 'activity',
label: '活动上报权限(activity:write)',
state: probe.ok ? 'ok' : checkState(probe.error),
message: probe.ok ? '鉴权通过(只验证权限,不代表已写入一条上报)' : describeError(probe.error),
});
}
const memoryToken = deps.store.memoryToken();
if (memoryToken === '') {
checks.push({ id: 'memory', label: '记忆读写权限(memory:write)', state: 'unconfigured', message: '未配置令牌' });
}
else {
const probe = await client.projects();
checks.push({
id: 'memory',
label: '记忆读写权限(memory:write)',
state: probe.ok ? 'ok' : checkState(probe.error),
message: probe.ok ? `鉴权通过(${(probe.data.projects ?? []).length} 个项目)` : describeError(probe.error),
});
}
const summaryToken = deps.store.summaryToken();
if (!settings.summaryEnabled) {
checks.push({ id: 'summary', label: '摘要权限(summary:write)', state: 'unconfigured', message: '自动摘要已关闭' });
}
else if (summaryToken === '') {
checks.push({ id: 'summary', label: '摘要权限(summary:write)', state: 'unconfigured', message: '未配置摘要令牌(可选)' });
}
else {
const probe = await client.probeSummary(summaryToken);
checks.push({
id: 'summary',
label: '摘要权限(summary:write)',
state: probe.ok ? 'ok' : checkState(probe.error),
message: probe.ok ? '鉴权通过(只进待确认队列)' : describeError(probe.error),
});
}
lastCheck = { at: Date.now(), checks };
json(res, 200, {
ok: true,
checkedAt: lastCheck.at,
checks,
// Kept for the older card/page shape; both views read the same probes.
activity: { ok: checks[1]?.state === 'ok', message: checks[1]?.message ?? '' },
memory: { ok: checks[2]?.state === 'ok', message: checks[2]?.message ?? '' },
summary: { ok: checks[3]?.state === 'ok', message: checks[3]?.message ?? '' },
});
}
/** `POST /dsh-brain/flush`. */
async function serveFlush(deps, req, res) {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
if (!sameOrigin(req)) {
fail(res, 403, 'origin-rejected');
return;
}
const result = await deps.reporter.flush();
json(res, 200, { ok: true, ...result });
}
/**
* `POST /dsh-brain/login` — sign in with the cloud account and exchange it
* for the scoped tokens.
*
* The password is used once, in memory, and never written anywhere: the flow is
* password → short-lived session cookie → tokens → cookie dropped. Only the
* tokens are persisted, so a later password change does not break the plugin
* and revoking a token does not reveal the password.
*/
async function serveLogin(deps, req, res) {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
if (!sameOrigin(req)) {
fail(res, 403, 'origin-rejected');
return;
}
const target = deps.store.settings().baseUrl;
if (!isSecureLoginTarget(target)) {
// Refuse to put a password on a plaintext channel that is not loopback.
json(res, 400, { ok: false, error: '服务地址不是 HTTPS,拒绝在上面发送密码,请先把服务地址改成 https://' });
return;
}
let raw;
try {
raw = await readBody(req);
}
catch {
fail(res, 413, 'request-too-large');
return;
}
let body;
try {
const parsed = JSON.parse(raw);
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
throw new Error('object required');
body = parsed;
}
catch {
fail(res, 400, 'invalid-json');
return;
}
const username = typeof body.username === 'string' ? body.username.trim() : '';
const password = typeof body.password === 'string' ? body.password : '';
if (username === '' || password === '') {
json(res, 400, { ok: false, error: '请填写用户名和密码' });
return;
}
if (username.length > 64 || password.length > 256) {
json(res, 400, { ok: false, error: '用户名或密码过长' });
return;
}
const client = deps.client();
const session = await client.login(username, password);
if (!session.ok) {
const status = session.error.status === 429 ? 429 : 401;
json(res, status, { ok: false, error: describeError(session.error) });
return;
}
const activity = await client.mintToken(session.data.sessionCookie, 'activity:write', TOKEN_LABELS.activity);
const memory = await client.mintToken(session.data.sessionCookie, 'memory:write', TOKEN_LABELS.memory);
const summary = await client.mintToken(session.data.sessionCookie, 'summary:write', TOKEN_LABELS.summary);
if (!activity.ok && !memory.ok) {
const first = activity.ok ? memory : activity;
const reason = first.ok ? '无法创建令牌' : describeError(first.error);
json(res, 400, { ok: false, error: `登录成功,但创建令牌失败:${reason}` });
return;
}
const patch = {};
if (activity.ok && typeof activity.data.token === 'string')
patch.activityToken = activity.data.token;
if (memory.ok && typeof memory.data.token === 'string')
patch.memoryToken = memory.data.token;
if (summary.ok && typeof summary.data.token === 'string')
patch.summaryToken = summary.data.token;
const applied = deps.store.patch(patch);
if (!applied.ok) {
json(res, 500, { ok: false, error: applied.error });
return;
}
const failed = activity.ok ? memory : activity;
const partial = !activity.ok || !memory.ok;
json(res, 200, {
...deps.statusView(),
login: {
ok: true,
partial,
user: {
username: typeof session.data.user.username === 'string' ? session.data.user.username : username,
role: session.data.user.role,
},
activity: activity.ok,
memory: memory.ok,
summary: summary.ok,
warning: failed.ok ? undefined : `部分令牌没有创建成功:${describeError(failed.error)}`,
},
});
}
/**
* Sync surface:
* `GET /dsh-brain/sync/status` latest stats + both sides of each conflict
* `POST /dsh-brain/sync/run` trigger one pass now
* `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual }
*/
async function serveSync(deps, req, res) {
const sync = deps.sync;
if (sync === undefined) {
fail(res, 404, 'sync-unavailable');
return;
}
const url = new URL(req.url ?? '/', 'http://localhost');
const suffix = url.pathname.slice(PATHS.sync.length);
try {
if (suffix === '' || suffix === '/' || suffix === '/status') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
json(res, 200, { ok: true, stats: sync.stats(), conflicts: await sync.conflictDetails() });
return;
}
if (suffix === '/run') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const stats = await sync.syncOnce();
json(res, 200, { ok: true, stats, conflicts: await sync.conflictDetails() });
return;
}
if (suffix === '/resolve') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res);
if (body === undefined)
return;
const result = await sync.resolveConflict(body.name, body.action);
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() });
return;
}
fail(res, 404, 'unknown-sync-route');
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
const known = ['invalid_name', 'invalid_action', 'no_local_copy', 'no_cloud_copy', 'stale_revision', 'sync_running', 'manifest_mismatch'];
const code = known.includes(message) ? message : 'internal';
const status = code === 'internal' ? 500
: code === 'invalid_name' || code === 'invalid_action' ? 400
: 409;
json(res, status, { ok: false, code, error: message });
}
}
/** Cloud-sync routes; the root aggregator decides the registration order. */
export function createCloudSyncRoutes(deps) {
return [
{ kind: 'exact', path: PATHS.login, handler: (req, res) => serveLogin(deps, req, res) },
{ kind: 'exact', path: PATHS.test, handler: (req, res) => serveTest(deps, req, res) },
{ kind: 'exact', path: PATHS.flush, handler: (req, res) => serveFlush(deps, req, res) },
{ kind: 'prefix', path: PATHS.sync, handler: (req, res) => serveSync(deps, req, res) },
];
}