335 lines
14 KiB
TypeScript
335 lines
14 KiB
TypeScript
/**
|
||
* Cloud-sync bundle — HTTP surface (host half).
|
||
*
|
||
* 连接、鉴权、登录、活动上报与 Skill 同步的路由。该模块只依赖自己的窄接口;
|
||
* 组合根(routes.ts)注入 statusView 聚合视图与同步引擎。
|
||
*/
|
||
import type { IncomingMessage, ServerResponse } from 'node:http'
|
||
import type { CloudClient } from './api.ts'
|
||
import { describeError, isSecureLoginTarget } from './api.ts'
|
||
import type { SettingsStore } from './store.ts'
|
||
import type { Reporter } from './reporter.ts'
|
||
import type { SkillSync } from './skill-sync.ts'
|
||
import type { CloudMemoryWebRoute } from './context-types.ts'
|
||
import { fail, json, jsonBody, readBody, sameOrigin } from './http.ts'
|
||
|
||
/** 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',
|
||
} as const
|
||
|
||
/** Everything the cloud-sync routes need from the plugin core. */
|
||
export interface CloudSyncRouteDeps {
|
||
store: SettingsStore
|
||
client: () => CloudClient
|
||
reporter: Reporter
|
||
/** The sync engine itself, for conflict details and interactive resolution. */
|
||
sync?: SkillSync
|
||
/** Composed by the root routes module: the full status view incl. capabilities. */
|
||
statusView: () => Record<string, unknown>
|
||
}
|
||
|
||
/** One credential check as the card renders it. */
|
||
type CheckState = 'ok' | 'unconfigured' | 'invalid' | 'forbidden' | 'unreachable' | 'error'
|
||
|
||
interface CheckItem {
|
||
id: string
|
||
label: string
|
||
state: CheckState
|
||
message: string
|
||
}
|
||
|
||
/** Last test run, kept in memory so the card can show "最后检查". */
|
||
let lastCheck: { at: number; checks: CheckItem[] } | null = null
|
||
|
||
/** The root status view reads the same probe memory; one source of truth. */
|
||
export function getLastCheck(): { at: number; checks: CheckItem[] } | null {
|
||
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: { status: number; code: string }): CheckState {
|
||
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: CloudSyncRouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||
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: CheckItem[] = []
|
||
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: CloudSyncRouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||
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: CloudSyncRouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||
if (req.method !== 'POST') {
|
||
fail(res, 405, 'method-not-allowed')
|
||
return
|
||
}
|
||
if (!sameOrigin(req)) {
|
||
fail(res, 403, 'origin-rejected')
|
||
return
|
||
}
|
||
// Snapshot the complete connection before any credential leaves the
|
||
// process. Every auth call in this flow is pinned to this target, and the
|
||
// final patch is refused if the configured address changed meanwhile.
|
||
const settings = deps.store.settings()
|
||
const target = { baseUrl: settings.baseUrl, timeoutMs: settings.requestTimeoutMs }
|
||
if (!isSecureLoginTarget(target.baseUrl)) {
|
||
// Refuse to put a password on a plaintext channel that is not loopback.
|
||
json(res, 400, { ok: false, error: '服务地址不是 HTTPS,拒绝在上面发送密码,请先把服务地址改成 https://' })
|
||
return
|
||
}
|
||
let raw: string
|
||
try {
|
||
raw = await readBody(req)
|
||
} catch {
|
||
fail(res, 413, 'request-too-large')
|
||
return
|
||
}
|
||
let body: Record<string, unknown>
|
||
try {
|
||
const parsed: unknown = JSON.parse(raw)
|
||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('object required')
|
||
body = parsed as Record<string, unknown>
|
||
} 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, target)
|
||
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, target)
|
||
const memory = await client.mintToken(session.data.sessionCookie, 'memory:write', TOKEN_LABELS.memory, target)
|
||
const summary = await client.mintToken(session.data.sessionCookie, 'summary:write', TOKEN_LABELS.summary, target)
|
||
if (!activity.ok && !memory.ok) {
|
||
json(res, 400, { ok: false, error: `登录成功,但创建令牌失败:${describeError(activity.error)}` })
|
||
return
|
||
}
|
||
// Atomic account switch: a scope whose mint failed must not keep the token
|
||
// of the PREVIOUS account — clearing beats carrying a stale credential the
|
||
// user just replaced. (Writing a token clears the clear-marker, so ordering
|
||
// inside one patch is irrelevant.)
|
||
const patch: Record<string, unknown> = {}
|
||
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
|
||
if (!activity.ok || typeof activity.data.token !== 'string') patch.clearActivityToken = true
|
||
if (!memory.ok || typeof memory.data.token !== 'string') patch.clearMemoryToken = true
|
||
if (!summary.ok || typeof summary.data.token !== 'string') patch.clearSummaryToken = true
|
||
// A settings edit while login/mintToken was in flight could otherwise bind
|
||
// fresh tokens minted for the OLD service to the NEW address. Refuse the
|
||
// patch outright: no token at all is safer than a wrong-attribution token.
|
||
if (deps.store.settings().baseUrl !== target.baseUrl) {
|
||
json(res, 409, { ok: false, error: '登录过程中服务地址已变更,本次登录结果已丢弃,请确认服务地址后重新登录' })
|
||
return
|
||
}
|
||
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 }
|
||
* `POST /dsh-brain/sync/resolve-all` { action: keep_local | take_cloud }
|
||
*/
|
||
|
||
async function serveSync(deps: CloudSyncRouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||
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') {
|
||
// Mutating route: the method, origin and content-type gates live in
|
||
// jsonBody so a cross-site form/text POST cannot trigger a sync pass.
|
||
const body = await jsonBody(req, res)
|
||
if (body === undefined) 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, body.conflictId)
|
||
json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() })
|
||
return
|
||
}
|
||
if (suffix === '/resolve-all') {
|
||
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.resolveConflicts(body.action, body.conflictIds)
|
||
json(res, 200, { ok: true, ...result, stats: sync.stats(), 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: CloudSyncRouteDeps): CloudMemoryWebRoute[] {
|
||
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) },
|
||
]
|
||
}
|