@artenx/dshb 0.1.40 → 0.1.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/auth/reset-cli.js +0 -0
- package/lib/{catalog-B3pDDoR4.js → catalog-BPkswHoz.js} +4 -2
- package/lib/catalog-BPkswHoz.js.map +1 -0
- package/lib/client.js +120 -536
- package/lib/client.js.map +1 -1
- package/lib/{connection-sIX25pkS.d.ts → connection-CDJM9aUw.d.ts} +10 -3
- package/lib/core/index.js +349 -10
- package/lib/core/index.js.map +1 -1
- package/lib/core/routes.d.ts +1 -1
- package/lib/core/sync/coordinator.d.ts +5 -5
- package/lib/core/sync/coordinator.js +3 -11
- package/lib/core/sync/coordinator.js.map +1 -1
- package/lib/core/sync/host-key.d.ts +1 -1
- package/lib/core/sync/internal-routes.d.ts +3 -3
- package/lib/core/sync/internal-routes.js +2 -2
- package/lib/core/sync/model.d.ts +1 -1
- package/lib/core/sync/model.js.map +1 -1
- package/lib/core/sync/node-sync.d.ts +1 -1
- package/lib/core/sync/offline-archive.d.ts +4 -4
- package/lib/core/sync/offline-archive.js +2 -2
- package/lib/core/sync/offline-routes.js +1 -1
- package/lib/core/sync/peer-manager.d.ts +2 -2
- package/lib/core/sync/routes.d.ts +2 -3
- package/lib/core/sync/routes.js +1 -17
- package/lib/core/sync/routes.js.map +1 -1
- package/lib/core/sync/session-journal.d.ts +1 -1
- package/lib/core/sync/session-journal.js +10 -0
- package/lib/core/sync/session-journal.js.map +1 -1
- package/lib/core/sync/session-routes.d.ts +1 -1
- package/lib/core/sync/session-routes.js +1 -25
- package/lib/core/sync/session-routes.js.map +1 -1
- package/lib/core/sync/session-sync.d.ts +1 -1
- package/lib/core/sync/session-sync.js +1 -1
- package/lib/core/sync/ssh-transport.d.ts +1 -1
- package/lib/core/sync/ssh-transport.js +1 -1
- package/lib/core/sync/stores.d.ts +1 -1
- package/lib/core/sync/stores.js +3 -19
- package/lib/core/sync/stores.js.map +1 -1
- package/lib/core/workspaces.d.ts +1 -1
- package/lib/exec-ssh/connection-pool.d.ts +1 -1
- package/lib/exec-ssh/connection.d.ts +2 -2
- package/lib/exec-ssh/connection.js +29 -12
- package/lib/exec-ssh/connection.js.map +1 -1
- package/lib/exec-ssh/executor.d.ts +10 -1
- package/lib/exec-ssh/executor.js +91 -42
- package/lib/exec-ssh/executor.js.map +1 -1
- package/lib/exec-ssh/index.d.ts +1 -1
- package/lib/{host-key-Dh2YTRX7.d.ts → host-key-CjO13Ds4.d.ts} +2 -2
- package/lib/{model-D1T078kt.d.ts → model-CX2TlH2E.d.ts} +2 -6
- package/lib/{node-sync-WdEv-ek7.d.ts → node-sync-qnJ7u0TU.d.ts} +3 -3
- package/lib/{session-journal-CTblFLJg.d.ts → session-journal-ftjZuIxo.d.ts} +4 -2
- package/lib/{session-sync-flNnd2JQ.d.ts → session-sync-AlV-M72t.d.ts} +7 -10
- package/lib/{session-sync-BZSp_o4n.js → session-sync-BV1CSYic.js} +14 -11
- package/lib/{session-sync-BZSp_o4n.js.map → session-sync-BV1CSYic.js.map} +1 -1
- package/lib/{ssh-transport-DQPMNwh1.d.ts → ssh-transport-a3qXoscG.d.ts} +5 -5
- package/lib/{stores-CUY_YFD-.d.ts → stores-BwQLabuJ.d.ts} +2 -2
- package/package.json +6 -6
- package/LICENSE +0 -21
- package/lib/catalog-B3pDDoR4.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { n as SyncStateStore } from "../../stores-
|
|
2
|
-
import { s as SyncNodeService } from "../../node-sync-
|
|
3
|
-
import { h as SyncSessionService } from "../../session-sync-
|
|
1
|
+
import { n as SyncStateStore } from "../../stores-BwQLabuJ.js";
|
|
2
|
+
import { s as SyncNodeService } from "../../node-sync-qnJ7u0TU.js";
|
|
3
|
+
import { h as SyncSessionService } from "../../session-sync-AlV-M72t.js";
|
|
4
4
|
import { Context } from "@deepseek-ai/cordis";
|
|
5
5
|
//#region src/core/sync/internal-routes.d.ts
|
|
6
6
|
declare function registerSyncInternalRoutes(ctx: Context, state: SyncStateStore, nodeSync?: SyncNodeService, sessionSync?: SyncSessionService): void;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { isLoopbackRequest } from "../../auth/loopback.js";
|
|
2
2
|
import { SyncNodeManifestError } from "./node-sync.js";
|
|
3
3
|
import { SYNC_CATALOG_CAPABILITY, SYNC_SESSION_BUNDLE_OBJECTS_CAPABILITY, SYNC_SESSION_EVENT_TAIL_CAPABILITY, SYNC_SESSION_MANIFEST_CAPABILITY, SYNC_SESSION_OBJECT_STREAM_CAPABILITY } from "./protocol.js";
|
|
4
|
-
import { d as validateObjectPayload, n as SyncSessionError } from "../../session-sync-
|
|
5
|
-
import { t as exportSyncCatalog } from "../../catalog-
|
|
4
|
+
import { d as validateObjectPayload, n as SyncSessionError } from "../../session-sync-BV1CSYic.js";
|
|
5
|
+
import { t as exportSyncCatalog } from "../../catalog-BPkswHoz.js";
|
|
6
6
|
//#region src/core/sync/internal-routes.ts
|
|
7
7
|
const MAX_APPLY_BODY_BYTES = 134217728;
|
|
8
8
|
function sendJson(res, status, body) {
|
package/lib/core/sync/model.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as parseSyncPeer, D as syncWorkspaceKey, E as syncRecordKey, S as isRecord, T as parseSyncSelection, _ as SyncSessionArchive, a as SyncDirection, b as SyncWorkspaceOrigin, c as SyncMode, d as SyncPeerDraft, f as SyncPeerProgress, g as SyncSelection, h as SyncSchedule, i as SyncCatalogWorkspace, l as SyncOrigin, m as SyncRecordMetadata, n as SyncCatalogNode, o as SyncEntityKind, p as SyncProvenance, r as SyncCatalogSession, s as SyncImportMethod, t as SyncCatalog, u as SyncPeer, v as SyncState, w as parseSyncPeerDraft, x as isNonNegativeSafeInteger, y as SyncWorkspaceMapping } from "../../model-
|
|
1
|
+
import { C as parseSyncPeer, D as syncWorkspaceKey, E as syncRecordKey, S as isRecord, T as parseSyncSelection, _ as SyncSessionArchive, a as SyncDirection, b as SyncWorkspaceOrigin, c as SyncMode, d as SyncPeerDraft, f as SyncPeerProgress, g as SyncSelection, h as SyncSchedule, i as SyncCatalogWorkspace, l as SyncOrigin, m as SyncRecordMetadata, n as SyncCatalogNode, o as SyncEntityKind, p as SyncProvenance, r as SyncCatalogSession, s as SyncImportMethod, t as SyncCatalog, u as SyncPeer, v as SyncState, w as parseSyncPeerDraft, x as isNonNegativeSafeInteger, y as SyncWorkspaceMapping } from "../../model-CX2TlH2E.js";
|
|
2
2
|
export { SyncCatalog, SyncCatalogNode, SyncCatalogSession, SyncCatalogWorkspace, SyncDirection, SyncEntityKind, SyncImportMethod, SyncMode, SyncOrigin, SyncPeer, SyncPeerDraft, SyncPeerProgress, SyncProvenance, SyncRecordMetadata, SyncSchedule, SyncSelection, SyncSessionArchive, SyncState, SyncWorkspaceMapping, SyncWorkspaceOrigin, isNonNegativeSafeInteger, isRecord, parseSyncPeer, parseSyncPeerDraft, parseSyncSelection, syncRecordKey, syncWorkspaceKey };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.js","names":[],"sources":["../../../src/core/sync/model.ts"],"sourcesContent":["import { posix } from 'node:path'\nimport type { SyncRevision } from './revision.js'\n\nexport type SyncDirection = 'pull' | 'bidirectional'\nexport type SyncSchedule = 'manual' | 'every-5m'\nexport type SyncEntityKind = 'node' | 'session'\nexport type SyncImportMethod = 'peer' | 'offline'\n/** 全量同步传输会话内容;元数据同步只同步目录,点击会话时经 wss 实时操作远端。 */\nexport type SyncMode = 'full' | 'metadata'\n\nexport interface SyncOrigin {\n originInstanceId: string\n originEntityId: string\n}\n\nexport interface SyncPeer {\n id: string\n name: string\n host: string\n port: number\n username: string\n authKind: 'password' | 'key'\n remoteDshHome?: string\n remoteProfile?: string\n remoteWebPort?: number\n direction: SyncDirection\n schedule: SyncSchedule\n mode: SyncMode\n syncSessions: boolean\n selection?: SyncSelection\n enabled: boolean\n hostKeyFingerprint?: string\n}\n\nexport interface SyncWorkspaceOrigin extends SyncOrigin {\n remotePath: string\n}\n\nexport interface SyncSelection {\n mode: 'all' | 'selected'\n nodes: SyncOrigin[]\n workspaces: SyncWorkspaceOrigin[]\n sessions: SyncOrigin[]\n}\n\nexport interface SyncCatalogNode {\n origin: SyncOrigin\n name: string\n type: 'remote-ssh' | 'remote-docker'\n}\n\nexport interface SyncCatalogWorkspace {\n origin: SyncOrigin\n nodeOrigin: SyncOrigin\n remotePath: string\n title: string\n}\n\nexport interface SyncCatalogSession {\n origin: SyncOrigin\n workspaceOrigin?: SyncOrigin\n workspaceRemotePath?: string\n nodeOrigin?: SyncOrigin\n sessionId: string\n sizeBytes?: number\n branchId?: string\n deleted?: boolean\n}\n\nexport interface SyncCatalog {\n protocolVersion: 1\n instanceId: string\n nodes: SyncCatalogNode[]\n workspaces: SyncCatalogWorkspace[]\n sessions: SyncCatalogSession[]\n}\n\nexport interface SyncPeer {\n id: string\n name: string\n host: string\n port: number\n username: string\n authKind: 'password' | 'key'\n remoteDshHome?: string\n remoteProfile?: string\n remoteWebPort?: number\n direction: SyncDirection\n schedule: SyncSchedule\n syncSessions: boolean\n selection?: SyncSelection\n enabled: boolean\n hostKeyFingerprint?: string\n}\n\nexport type SyncPeerDraft = Omit<SyncPeer, 'id' | 'hostKeyFingerprint'>\n\nexport interface SyncProvenance extends SyncOrigin {\n localEntityId: string\n importedVia?: SyncImportMethod\n sourceName?: string\n}\n\nexport interface SyncRecordMetadata extends SyncProvenance {\n kind: SyncEntityKind\n revision: SyncRevision\n contentDigest: string\n stateDigest?: string\n workspaceOrigin?: SyncOrigin\n deleted?: boolean\n pendingRemoval?: boolean\n credentialsRequired?: boolean\n}\n\nexport interface SyncPeerProgress {\n lastRunAt?: string\n lastRunStatus?: 'running' | 'succeeded' | 'failed' | 'stopped'\n lastSuccessAt?: string\n lastManifestDigest?: string\n watermark?: string\n lastErrorCode?: string\n lastErrorMessage?: string\n lastResult?: {\n imported: number\n exported: number\n skipped: number\n pendingRemoval: number\n importedSessions: number\n exportedSessions: number\n skippedSessions: number\n /** 元数据同步最近一次目录计数(可选,旧状态缺省)。 */\n catalogNodes?: number\n catalogWorkspaces?: number\n catalogSessions?: number\n }\n}\n\nexport interface SyncWorkspaceMapping {\n originInstanceId: string\n originWorkspaceId: string\n localWorkspaceId: string\n localPath: string\n localNodeId: string\n remotePath: string\n title: string\n revision: SyncRevision\n contentDigest: string\n}\n\nexport interface SyncSessionArchive {\n branchId: string\n originInstanceId: string\n originSessionId: string\n localSessionId: string\n revision: SyncRevision\n contentDigest: string\n stateDigest: string\n workspacePosition: number\n workspaceId?: string\n workspaceOrigin?: SyncOrigin\n archivedAt: string\n}\n\nexport interface SyncState {\n version: 1\n clock: { physicalTimeMs: number; logicalCounter: number }\n peers: Record<string, SyncPeerProgress>\n records: Record<string, SyncRecordMetadata>\n workspaces: Record<string, SyncWorkspaceMapping>\n archives: Record<string, SyncSessionArchive>\n /** 元数据同步的远端目录缓存:peer ID → 最近一次拉取的目录快照。 */\n catalogs: Record<string, { fetchedAt: string; catalog: SyncCatalog }>\n}\n\nconst PEER_FIELDS = new Set([\n 'id',\n 'name',\n 'host',\n 'port',\n 'username',\n 'authKind',\n 'remoteDshHome',\n 'remoteProfile',\n 'remoteWebPort',\n 'direction',\n 'schedule',\n 'mode',\n 'syncSessions',\n 'selection',\n 'enabled',\n 'hostKeyFingerprint',\n])\n\nconst PEER_DRAFT_FIELDS = new Set([...PEER_FIELDS].filter((field) => field !== 'id' && field !== 'hostKeyFingerprint'))\n\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n return value as Record<string, unknown>\n}\n\nfunction text(value: unknown, label: string, maxLength: number): string {\n if (typeof value !== 'string') throw new Error(`${label} must be a string`)\n const result = value.trim()\n if (!result || result.length > maxLength || /[\\u0000-\\u001f\\u007f]/.test(result)) {\n throw new Error(`${label} is invalid`)\n }\n return result\n}\n\nfunction optionalText(value: unknown, label: string, maxLength: number): string | undefined {\n return value === undefined ? undefined : text(value, label, maxLength)\n}\n\nfunction port(value: unknown, label: string): number {\n if (!Number.isSafeInteger(value) || (value as number) < 1 || (value as number) > 65535) {\n throw new Error(`${label} must be an integer between 1 and 65535`)\n }\n return value as number\n}\n\nfunction parseOrigin(value: unknown, label: string): SyncOrigin {\n const input = record(value, label)\n if (Object.keys(input).some((key) => key !== 'originInstanceId' && key !== 'originEntityId')) {\n throw new Error(`${label} contains unsupported fields`)\n }\n return {\n originInstanceId: text(input.originInstanceId, `${label}.originInstanceId`, 512),\n originEntityId: text(input.originEntityId, `${label}.originEntityId`, 512),\n }\n}\n\nexport function parseSyncSelection(value: unknown): SyncSelection {\n const input = record(value, 'selection')\n if (Object.keys(input).some((key) => !['mode', 'nodes', 'workspaces', 'sessions'].includes(key))) {\n throw new Error('selection contains unsupported fields')\n }\n if (input.mode !== 'all' && input.mode !== 'selected') throw new Error('selection mode is invalid')\n const parseOrigins = (value: unknown, label: string): SyncOrigin[] => {\n if (value === undefined) return []\n if (!Array.isArray(value) || value.length > 10_000) throw new Error(`${label} must be an array of at most 10000 items`)\n const origins = value.map((item, index) => parseOrigin(item, `${label}[${index}]`))\n const keys = origins.map((origin) => JSON.stringify([origin.originInstanceId, origin.originEntityId]))\n if (new Set(keys).size !== keys.length) throw new Error(`${label} contains duplicate origins`)\n return origins\n }\n const nodes = parseOrigins(input.nodes, 'selection.nodes')\n const rawWorkspaces = input.workspaces\n if (rawWorkspaces !== undefined && (!Array.isArray(rawWorkspaces) || rawWorkspaces.length > 10_000)) {\n throw new Error('selection.workspaces must be an array of at most 10000 items')\n }\n const workspaces = (rawWorkspaces ?? []).map((value, index) => {\n const workspace = record(value, `selection.workspaces[${index}]`)\n if (Object.keys(workspace).some((key) => !['originInstanceId', 'originEntityId', 'remotePath'].includes(key)) ||\n typeof workspace.remotePath !== 'string' || workspace.remotePath.length > 4096 || !posix.isAbsolute(workspace.remotePath) ||\n posix.normalize(workspace.remotePath) !== workspace.remotePath) {\n throw new Error(`selection.workspaces[${index}] is invalid`)\n }\n const { remotePath, ...origin } = workspace\n return { ...parseOrigin(origin, `selection.workspaces[${index}]`), remotePath: remotePath as string }\n })\n const workspaceKeys = workspaces.map((workspace) => JSON.stringify([\n workspace.originInstanceId, workspace.originEntityId, workspace.remotePath,\n ]))\n if (new Set(workspaceKeys).size !== workspaceKeys.length) throw new Error('selection.workspaces contains duplicate origins')\n const sessions = parseOrigins(input.sessions, 'selection.sessions')\n if (input.mode === 'all' && (nodes.length > 0 || workspaces.length > 0 || sessions.length > 0)) {\n throw new Error('all selection cannot contain explicit origins')\n }\n return { mode: input.mode, nodes, workspaces, sessions }\n}\n\nexport function parseSyncPeer(value: unknown): SyncPeer {\n const input = record(value, 'sync peer')\n for (const key of Object.keys(input)) {\n if (!PEER_FIELDS.has(key)) throw new Error(`sync peer contains unsupported field: ${key}`)\n }\n\n const id = text(input.id, 'id', 128)\n if (!/^[a-z][a-z0-9-]*$/.test(id)) throw new Error('id is invalid')\n\n const name = text(input.name, 'name', 128)\n const host = text(input.host, 'host', 255)\n if (/\\s/.test(host)) throw new Error('host is invalid')\n\n const username = text(input.username, 'username', 128)\n if (/\\s/.test(username)) throw new Error('username is invalid')\n\n if (input.authKind !== 'password' && input.authKind !== 'key') {\n throw new Error('authKind must be password or key')\n }\n if (input.direction !== 'pull' && input.direction !== 'bidirectional') {\n throw new Error('direction must be pull or bidirectional')\n }\n if (input.schedule !== 'manual' && input.schedule !== 'every-5m') {\n throw new Error('schedule must be manual or every-5m')\n }\n if (input.mode !== undefined && input.mode !== 'full' && input.mode !== 'metadata') {\n throw new Error('mode must be full or metadata')\n }\n if (typeof input.syncSessions !== 'boolean' || typeof input.enabled !== 'boolean') {\n throw new Error('syncSessions and enabled must be booleans')\n }\n\n const remoteDshHome = optionalText(input.remoteDshHome, 'remoteDshHome', 4096)\n if (remoteDshHome !== undefined) {\n if (!posix.isAbsolute(remoteDshHome) || remoteDshHome.split('/').includes('..') || remoteDshHome.includes('\\\\')) {\n throw new Error('remoteDshHome must be a normalized absolute path')\n }\n }\n\n const remoteProfile = optionalText(input.remoteProfile, 'remoteProfile', 256)\n const hostKeyFingerprint = optionalText(input.hostKeyFingerprint, 'hostKeyFingerprint', 512)\n\n return {\n id,\n name,\n host,\n port: port(input.port, 'port'),\n username,\n authKind: input.authKind,\n ...(remoteDshHome === undefined ? {} : { remoteDshHome: posix.normalize(remoteDshHome) }),\n ...(remoteProfile === undefined ? {} : { remoteProfile }),\n ...(input.remoteWebPort === undefined ? {} : { remoteWebPort: port(input.remoteWebPort, 'remoteWebPort') }),\n direction: input.direction,\n schedule: input.schedule,\n // 旧 peer 数据没有 mode 字段:缺省按全量同步处理,保持既有行为不变。\n mode: input.mode === undefined ? 'full' : input.mode,\n syncSessions: input.syncSessions,\n ...(input.selection === undefined ? {} : { selection: parseSyncSelection(input.selection) }),\n enabled: input.enabled,\n ...(hostKeyFingerprint === undefined ? {} : { hostKeyFingerprint }),\n }\n}\n\nexport function parseSyncPeerDraft(value: unknown): SyncPeerDraft {\n const input = record(value, 'sync peer draft')\n for (const key of Object.keys(input)) {\n if (!PEER_DRAFT_FIELDS.has(key)) throw new Error(`sync peer draft contains unsupported field: ${key}`)\n }\n const { id, ...draft } = parseSyncPeer({ ...input, id: `p-${'0'.repeat(24)}` })\n void id\n return draft\n}\n\nexport function syncRecordKey(kind: SyncEntityKind, origin: SyncOrigin): string {\n return JSON.stringify([kind, origin.originInstanceId, origin.originEntityId])\n}\n\nexport function syncWorkspaceKey(originInstanceId: string, originWorkspaceId: string, remotePath: string): string {\n return JSON.stringify([originInstanceId, originWorkspaceId, remotePath])\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nexport function isNonNegativeSafeInteger(value: unknown): value is number {\n return Number.isSafeInteger(value) && (value as number) >= 0\n}\n"],"mappings":";;AA8KA,MAAM,8BAAc,IAAI,IA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,CAAC,IAAI,EAAE,WAAW,mBAAmB,MAAM,SAAS,EAAE;EAC1F,SAAS,MAAM;EACf,GAAI,uBAAuB,KAAA,IAAY,CAAC,IAAI,EAAE,mBAAmB;CACnE;AACF;AAEA,SAAgB,mBAAmB,OAA+B;CAChE,MAAM,QAAQ,OAAO,OAAO,iBAAiB;CAC7C,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GACjC,IAAI,CAAC,kBAAkB,IAAI,GAAG,GAAG,MAAM,IAAI,MAAM,+CAA+C,KAAK;CAEvG,MAAM,EAAE,IAAI,GAAG,UAAU,cAAc;EAAE,GAAG;EAAO,IAAI,KAAK,IAAI,OAAO,EAAE;CAAI,CAAC;CAE9E,OAAO;AACT;AAEA,SAAgB,cAAc,MAAsB,QAA4B;CAC9E,OAAO,KAAK,UAAU;EAAC;EAAM,OAAO;EAAkB,OAAO;CAAc,CAAC;AAC9E;AAEA,SAAgB,iBAAiB,kBAA0B,mBAA2B,YAA4B;CAChH,OAAO,KAAK,UAAU;EAAC;EAAkB;EAAmB;CAAU,CAAC;AACzE;AAEA,SAAgB,SAAS,OAAkD;CACzE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAgB,yBAAyB,OAAiC;CACxE,OAAO,OAAO,cAAc,KAAK,KAAM,SAAoB;AAC7D"}
|
|
1
|
+
{"version":3,"file":"model.js","names":[],"sources":["../../../src/core/sync/model.ts"],"sourcesContent":["import { posix } from 'node:path'\nimport type { SyncRevision } from './revision.js'\n\nexport type SyncDirection = 'pull' | 'bidirectional'\nexport type SyncSchedule = 'manual' | 'every-5m'\nexport type SyncEntityKind = 'node' | 'session'\nexport type SyncImportMethod = 'peer' | 'offline'\n/** 全量同步传输会话内容;元数据同步只同步目录,点击会话时经 wss 实时操作远端。 */\nexport type SyncMode = 'full' | 'metadata'\n\nexport interface SyncOrigin {\n originInstanceId: string\n originEntityId: string\n}\n\nexport interface SyncPeer {\n id: string\n name: string\n host: string\n port: number\n username: string\n authKind: 'password' | 'key'\n remoteDshHome?: string\n remoteProfile?: string\n remoteWebPort?: number\n direction: SyncDirection\n schedule: SyncSchedule\n mode: SyncMode\n syncSessions: boolean\n selection?: SyncSelection\n enabled: boolean\n hostKeyFingerprint?: string\n}\n\nexport interface SyncWorkspaceOrigin extends SyncOrigin {\n remotePath: string\n}\n\nexport interface SyncSelection {\n mode: 'all' | 'selected'\n nodes: SyncOrigin[]\n workspaces: SyncWorkspaceOrigin[]\n sessions: SyncOrigin[]\n}\n\nexport interface SyncCatalogNode {\n origin: SyncOrigin\n name: string\n type: 'remote-ssh' | 'remote-docker'\n}\n\nexport interface SyncCatalogWorkspace {\n origin: SyncOrigin\n nodeOrigin: SyncOrigin\n remotePath: string\n title: string\n}\n\nexport interface SyncCatalogSession {\n origin: SyncOrigin\n workspaceOrigin?: SyncOrigin\n workspaceRemotePath?: string\n nodeOrigin?: SyncOrigin\n sessionId: string\n title?: string\n sizeBytes?: number\n branchId?: string\n deleted?: boolean\n}\n\nexport interface SyncCatalog {\n protocolVersion: 1\n instanceId: string\n nodes: SyncCatalogNode[]\n workspaces: SyncCatalogWorkspace[]\n sessions: SyncCatalogSession[]\n}\n\nexport interface SyncPeer {\n id: string\n name: string\n host: string\n port: number\n username: string\n authKind: 'password' | 'key'\n remoteDshHome?: string\n remoteProfile?: string\n remoteWebPort?: number\n direction: SyncDirection\n schedule: SyncSchedule\n syncSessions: boolean\n selection?: SyncSelection\n enabled: boolean\n hostKeyFingerprint?: string\n}\n\nexport type SyncPeerDraft = Omit<SyncPeer, 'id' | 'hostKeyFingerprint'>\n\nexport interface SyncProvenance extends SyncOrigin {\n localEntityId: string\n importedVia?: SyncImportMethod\n sourceName?: string\n}\n\nexport interface SyncRecordMetadata extends SyncProvenance {\n kind: SyncEntityKind\n revision: SyncRevision\n contentDigest: string\n stateDigest?: string\n workspaceOrigin?: SyncOrigin\n deleted?: boolean\n pendingRemoval?: boolean\n credentialsRequired?: boolean\n}\n\nexport interface SyncPeerProgress {\n lastRunAt?: string\n lastRunStatus?: 'running' | 'succeeded' | 'failed' | 'stopped'\n lastSuccessAt?: string\n lastManifestDigest?: string\n watermark?: string\n lastErrorCode?: string\n lastErrorMessage?: string\n lastResult?: {\n imported: number\n exported: number\n skipped: number\n pendingRemoval: number\n importedSessions: number\n exportedSessions: number\n skippedSessions: number\n /** 元数据同步最近一次目录计数(可选,旧状态缺省)。 */\n catalogNodes?: number\n catalogWorkspaces?: number\n catalogSessions?: number\n }\n}\n\nexport interface SyncWorkspaceMapping {\n originInstanceId: string\n originWorkspaceId: string\n localWorkspaceId: string\n localPath: string\n localNodeId: string\n remotePath: string\n title: string\n revision: SyncRevision\n contentDigest: string\n}\n\nexport interface SyncSessionArchive {\n branchId: string\n originInstanceId: string\n originSessionId: string\n localSessionId: string\n revision: SyncRevision\n contentDigest: string\n stateDigest: string\n workspacePosition: number\n workspaceId?: string\n workspaceOrigin?: SyncOrigin\n archivedAt: string\n}\n\nexport interface SyncState {\n version: 1\n clock: { physicalTimeMs: number; logicalCounter: number }\n peers: Record<string, SyncPeerProgress>\n records: Record<string, SyncRecordMetadata>\n workspaces: Record<string, SyncWorkspaceMapping>\n archives: Record<string, SyncSessionArchive>\n}\n\nconst PEER_FIELDS = new Set([\n 'id',\n 'name',\n 'host',\n 'port',\n 'username',\n 'authKind',\n 'remoteDshHome',\n 'remoteProfile',\n 'remoteWebPort',\n 'direction',\n 'schedule',\n 'mode',\n 'syncSessions',\n 'selection',\n 'enabled',\n 'hostKeyFingerprint',\n])\n\nconst PEER_DRAFT_FIELDS = new Set([...PEER_FIELDS].filter((field) => field !== 'id' && field !== 'hostKeyFingerprint'))\n\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n return value as Record<string, unknown>\n}\n\nfunction text(value: unknown, label: string, maxLength: number): string {\n if (typeof value !== 'string') throw new Error(`${label} must be a string`)\n const result = value.trim()\n if (!result || result.length > maxLength || /[\\u0000-\\u001f\\u007f]/.test(result)) {\n throw new Error(`${label} is invalid`)\n }\n return result\n}\n\nfunction optionalText(value: unknown, label: string, maxLength: number): string | undefined {\n return value === undefined ? undefined : text(value, label, maxLength)\n}\n\nfunction port(value: unknown, label: string): number {\n if (!Number.isSafeInteger(value) || (value as number) < 1 || (value as number) > 65535) {\n throw new Error(`${label} must be an integer between 1 and 65535`)\n }\n return value as number\n}\n\nfunction parseOrigin(value: unknown, label: string): SyncOrigin {\n const input = record(value, label)\n if (Object.keys(input).some((key) => key !== 'originInstanceId' && key !== 'originEntityId')) {\n throw new Error(`${label} contains unsupported fields`)\n }\n return {\n originInstanceId: text(input.originInstanceId, `${label}.originInstanceId`, 512),\n originEntityId: text(input.originEntityId, `${label}.originEntityId`, 512),\n }\n}\n\nexport function parseSyncSelection(value: unknown): SyncSelection {\n const input = record(value, 'selection')\n if (Object.keys(input).some((key) => !['mode', 'nodes', 'workspaces', 'sessions'].includes(key))) {\n throw new Error('selection contains unsupported fields')\n }\n if (input.mode !== 'all' && input.mode !== 'selected') throw new Error('selection mode is invalid')\n const parseOrigins = (value: unknown, label: string): SyncOrigin[] => {\n if (value === undefined) return []\n if (!Array.isArray(value) || value.length > 10_000) throw new Error(`${label} must be an array of at most 10000 items`)\n const origins = value.map((item, index) => parseOrigin(item, `${label}[${index}]`))\n const keys = origins.map((origin) => JSON.stringify([origin.originInstanceId, origin.originEntityId]))\n if (new Set(keys).size !== keys.length) throw new Error(`${label} contains duplicate origins`)\n return origins\n }\n const nodes = parseOrigins(input.nodes, 'selection.nodes')\n const rawWorkspaces = input.workspaces\n if (rawWorkspaces !== undefined && (!Array.isArray(rawWorkspaces) || rawWorkspaces.length > 10_000)) {\n throw new Error('selection.workspaces must be an array of at most 10000 items')\n }\n const workspaces = (rawWorkspaces ?? []).map((value, index) => {\n const workspace = record(value, `selection.workspaces[${index}]`)\n if (Object.keys(workspace).some((key) => !['originInstanceId', 'originEntityId', 'remotePath'].includes(key)) ||\n typeof workspace.remotePath !== 'string' || workspace.remotePath.length > 4096 || !posix.isAbsolute(workspace.remotePath) ||\n posix.normalize(workspace.remotePath) !== workspace.remotePath) {\n throw new Error(`selection.workspaces[${index}] is invalid`)\n }\n const { remotePath, ...origin } = workspace\n return { ...parseOrigin(origin, `selection.workspaces[${index}]`), remotePath: remotePath as string }\n })\n const workspaceKeys = workspaces.map((workspace) => JSON.stringify([\n workspace.originInstanceId, workspace.originEntityId, workspace.remotePath,\n ]))\n if (new Set(workspaceKeys).size !== workspaceKeys.length) throw new Error('selection.workspaces contains duplicate origins')\n const sessions = parseOrigins(input.sessions, 'selection.sessions')\n if (input.mode === 'all' && (nodes.length > 0 || workspaces.length > 0 || sessions.length > 0)) {\n throw new Error('all selection cannot contain explicit origins')\n }\n return { mode: input.mode, nodes, workspaces, sessions }\n}\n\nexport function parseSyncPeer(value: unknown): SyncPeer {\n const input = record(value, 'sync peer')\n for (const key of Object.keys(input)) {\n if (!PEER_FIELDS.has(key)) throw new Error(`sync peer contains unsupported field: ${key}`)\n }\n\n const id = text(input.id, 'id', 128)\n if (!/^[a-z][a-z0-9-]*$/.test(id)) throw new Error('id is invalid')\n\n const name = text(input.name, 'name', 128)\n const host = text(input.host, 'host', 255)\n if (/\\s/.test(host)) throw new Error('host is invalid')\n\n const username = text(input.username, 'username', 128)\n if (/\\s/.test(username)) throw new Error('username is invalid')\n\n if (input.authKind !== 'password' && input.authKind !== 'key') {\n throw new Error('authKind must be password or key')\n }\n if (input.direction !== 'pull' && input.direction !== 'bidirectional') {\n throw new Error('direction must be pull or bidirectional')\n }\n if (input.schedule !== 'manual' && input.schedule !== 'every-5m') {\n throw new Error('schedule must be manual or every-5m')\n }\n if (input.mode !== undefined && input.mode !== 'full' && input.mode !== 'metadata') {\n throw new Error('mode must be full or metadata')\n }\n if (typeof input.syncSessions !== 'boolean' || typeof input.enabled !== 'boolean') {\n throw new Error('syncSessions and enabled must be booleans')\n }\n\n const remoteDshHome = optionalText(input.remoteDshHome, 'remoteDshHome', 4096)\n if (remoteDshHome !== undefined) {\n if (!posix.isAbsolute(remoteDshHome) || remoteDshHome.split('/').includes('..') || remoteDshHome.includes('\\\\')) {\n throw new Error('remoteDshHome must be a normalized absolute path')\n }\n }\n\n const remoteProfile = optionalText(input.remoteProfile, 'remoteProfile', 256)\n const hostKeyFingerprint = optionalText(input.hostKeyFingerprint, 'hostKeyFingerprint', 512)\n\n return {\n id,\n name,\n host,\n port: port(input.port, 'port'),\n username,\n authKind: input.authKind,\n ...(remoteDshHome === undefined ? {} : { remoteDshHome: posix.normalize(remoteDshHome) }),\n ...(remoteProfile === undefined ? {} : { remoteProfile }),\n ...(input.remoteWebPort === undefined ? {} : { remoteWebPort: port(input.remoteWebPort, 'remoteWebPort') }),\n direction: input.direction,\n schedule: input.schedule,\n // 旧 peer 数据没有 mode 字段:缺省按全量同步处理,保持既有行为不变。\n mode: input.mode === undefined ? 'full' : input.mode,\n syncSessions: input.syncSessions,\n ...(input.selection === undefined ? {} : { selection: parseSyncSelection(input.selection) }),\n enabled: input.enabled,\n ...(hostKeyFingerprint === undefined ? {} : { hostKeyFingerprint }),\n }\n}\n\nexport function parseSyncPeerDraft(value: unknown): SyncPeerDraft {\n const input = record(value, 'sync peer draft')\n for (const key of Object.keys(input)) {\n if (!PEER_DRAFT_FIELDS.has(key)) throw new Error(`sync peer draft contains unsupported field: ${key}`)\n }\n const { id, ...draft } = parseSyncPeer({ ...input, id: `p-${'0'.repeat(24)}` })\n void id\n return draft\n}\n\nexport function syncRecordKey(kind: SyncEntityKind, origin: SyncOrigin): string {\n return JSON.stringify([kind, origin.originInstanceId, origin.originEntityId])\n}\n\nexport function syncWorkspaceKey(originInstanceId: string, originWorkspaceId: string, remotePath: string): string {\n return JSON.stringify([originInstanceId, originWorkspaceId, remotePath])\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nexport function isNonNegativeSafeInteger(value: unknown): value is number {\n return Number.isSafeInteger(value) && (value as number) >= 0\n}\n"],"mappings":";;AA6KA,MAAM,8BAAc,IAAI,IAAI;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,oBAAoB,IAAI,IAAI,CAAC,GAAG,WAAW,CAAC,CAAC,QAAQ,UAAU,UAAU,QAAQ,UAAU,oBAAoB,CAAC;AAEtH,SAAS,OAAO,OAAgB,OAAwC;CACtE,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GACpE,MAAM,IAAI,MAAM,GAAG,MAAM,mBAAmB;CAE9C,OAAO;AACT;AAEA,SAAS,KAAK,OAAgB,OAAe,WAA2B;CACtE,IAAI,OAAO,UAAU,UAAU,MAAM,IAAI,MAAM,GAAG,MAAM,kBAAkB;CAC1E,MAAM,SAAS,MAAM,KAAK;CAC1B,IAAI,CAAC,UAAU,OAAO,SAAS,aAAa,wBAAwB,KAAK,MAAM,GAC7E,MAAM,IAAI,MAAM,GAAG,MAAM,YAAY;CAEvC,OAAO;AACT;AAEA,SAAS,aAAa,OAAgB,OAAe,WAAuC;CAC1F,OAAO,UAAU,KAAA,IAAY,KAAA,IAAY,KAAK,OAAO,OAAO,SAAS;AACvE;AAEA,SAAS,KAAK,OAAgB,OAAuB;CACnD,IAAI,CAAC,OAAO,cAAc,KAAK,KAAM,QAAmB,KAAM,QAAmB,OAC/E,MAAM,IAAI,MAAM,GAAG,MAAM,wCAAwC;CAEnE,OAAO;AACT;AAEA,SAAS,YAAY,OAAgB,OAA2B;CAC9D,MAAM,QAAQ,OAAO,OAAO,KAAK;CACjC,IAAI,OAAO,KAAK,KAAK,CAAC,CAAC,MAAM,QAAQ,QAAQ,sBAAsB,QAAQ,gBAAgB,GACzF,MAAM,IAAI,MAAM,GAAG,MAAM,6BAA6B;CAExD,OAAO;EACL,kBAAk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AU,MAAM;EAEhB,MAAM,MAAM,SAAS,KAAA,IAAY,SAAS,MAAM;EAChD,cAAc,MAAM;EACpB,GAAI,MAAM,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,mBAAmB,MAAM,SAAS,EAAE;EAC1F,SAAS,MAAM;EACf,GAAI,uBAAuB,KAAA,IAAY,CAAC,IAAI,EAAE,mBAAmB;CACnE;AACF;AAEA,SAAgB,mBAAmB,OAA+B;CAChE,MAAM,QAAQ,OAAO,OAAO,iBAAiB;CAC7C,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GACjC,IAAI,CAAC,kBAAkB,IAAI,GAAG,GAAG,MAAM,IAAI,MAAM,+CAA+C,KAAK;CAEvG,MAAM,EAAE,IAAI,GAAG,UAAU,cAAc;EAAE,GAAG;EAAO,IAAI,KAAK,IAAI,OAAO,EAAE;CAAI,CAAC;CAE9E,OAAO;AACT;AAEA,SAAgB,cAAc,MAAsB,QAA4B;CAC9E,OAAO,KAAK,UAAU;EAAC;EAAM,OAAO;EAAkB,OAAO;CAAc,CAAC;AAC9E;AAEA,SAAgB,iBAAiB,kBAA0B,mBAA2B,YAA4B;CAChH,OAAO,KAAK,UAAU;EAAC;EAAkB;EAAmB;CAAU,CAAC;AACzE;AAEA,SAAgB,SAAS,OAAkD;CACzE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAgB,yBAAyB,OAAiC;CACxE,OAAO,OAAO,cAAc,KAAK,KAAM,SAAoB;AAC7D"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as SyncNodeManifestError, c as SyncNodeView, i as SyncNodeManifest, n as SyncNodeEntry, o as SyncNodeProfile, r as SyncNodeInUseError, s as SyncNodeService, t as SyncNodeApplyResult } from "../../node-sync-
|
|
1
|
+
import { a as SyncNodeManifestError, c as SyncNodeView, i as SyncNodeManifest, n as SyncNodeEntry, o as SyncNodeProfile, r as SyncNodeInUseError, s as SyncNodeService, t as SyncNodeApplyResult } from "../../node-sync-qnJ7u0TU.js";
|
|
2
2
|
export { SyncNodeApplyResult, SyncNodeEntry, SyncNodeInUseError, SyncNodeManifest, SyncNodeManifestError, SyncNodeProfile, SyncNodeService, SyncNodeView };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { g as SyncSelection, t as SyncCatalog } from "../../model-
|
|
2
|
-
import { n as SyncStateStore } from "../../stores-
|
|
3
|
-
import { s as SyncNodeService } from "../../node-sync-
|
|
4
|
-
import { h as SyncSessionService } from "../../session-sync-
|
|
1
|
+
import { g as SyncSelection, t as SyncCatalog } from "../../model-CX2TlH2E.js";
|
|
2
|
+
import { n as SyncStateStore } from "../../stores-BwQLabuJ.js";
|
|
3
|
+
import { s as SyncNodeService } from "../../node-sync-qnJ7u0TU.js";
|
|
4
|
+
import { h as SyncSessionService } from "../../session-sync-AlV-M72t.js";
|
|
5
5
|
//#region src/core/sync/offline-archive.d.ts
|
|
6
6
|
declare const MAX_OFFLINE_ARCHIVE_BYTES: number;
|
|
7
7
|
declare class SyncOfflineArchiveError extends Error {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { f as validateSyncSessionBundle, n as SyncSessionError, o as makeSyncSessionBundle } from "../../session-sync-
|
|
2
|
-
import { t as exportSyncCatalog } from "../../catalog-
|
|
1
|
+
import { f as validateSyncSessionBundle, n as SyncSessionError, o as makeSyncSessionBundle } from "../../session-sync-BV1CSYic.js";
|
|
2
|
+
import { t as exportSyncCatalog } from "../../catalog-BPkswHoz.js";
|
|
3
3
|
import { i as syncOriginKey, n as selectionIncludesNode, r as selectionIncludesSession, t as resolveSyncSelection } from "../../selection-BABQH1Rt.js";
|
|
4
4
|
import { SyncOfflineArchiveJournalStore } from "./offline-journal.js";
|
|
5
5
|
import { homedir } from "node:os";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { parseSyncSelection } from "./model.js";
|
|
2
|
-
import { n as SyncSessionError } from "../../session-sync-
|
|
2
|
+
import { n as SyncSessionError } from "../../session-sync-BV1CSYic.js";
|
|
3
3
|
import { SyncOfflineArchiveError } from "./offline-archive.js";
|
|
4
4
|
import { createReadStream } from "node:fs";
|
|
5
5
|
import { randomBytes } from "node:crypto";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { f as SyncPeerProgress, u as SyncPeer } from "../../model-
|
|
2
|
-
import { n as SyncStateStore, t as SyncPeerStore } from "../../stores-
|
|
1
|
+
import { f as SyncPeerProgress, u as SyncPeer } from "../../model-CX2TlH2E.js";
|
|
2
|
+
import { n as SyncStateStore, t as SyncPeerStore } from "../../stores-BwQLabuJ.js";
|
|
3
3
|
import { CredentialKey } from "@deepseek-ai/dsh-credentials";
|
|
4
4
|
//#region src/core/sync/peer-manager.d.ts
|
|
5
5
|
interface SyncPeerSecrets {
|
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { n as SyncStateStore } from "../../stores-CUY_YFD-.js";
|
|
2
1
|
import { SyncPeerManager } from "./peer-manager.js";
|
|
3
|
-
import { m as SyncSshTransport } from "../../ssh-transport-
|
|
2
|
+
import { m as SyncSshTransport } from "../../ssh-transport-a3qXoscG.js";
|
|
4
3
|
import { SyncCoordinator } from "./coordinator.js";
|
|
5
4
|
import { Context } from "@deepseek-ai/cordis";
|
|
6
5
|
//#region src/core/sync/routes.d.ts
|
|
7
|
-
declare function registerSyncPeerRoutes(ctx: Context, manager: SyncPeerManager, transport?: SyncSshTransport, coordinator?: SyncCoordinator
|
|
6
|
+
declare function registerSyncPeerRoutes(ctx: Context, manager: SyncPeerManager, transport?: SyncSshTransport, coordinator?: SyncCoordinator): void;
|
|
8
7
|
//#endregion
|
|
9
8
|
export { registerSyncPeerRoutes };
|
|
10
9
|
//# sourceMappingURL=routes.d.ts.map
|
package/lib/core/sync/routes.js
CHANGED
|
@@ -131,7 +131,7 @@ function sendRunFailure(res, error) {
|
|
|
131
131
|
error: "sync run failed"
|
|
132
132
|
});
|
|
133
133
|
}
|
|
134
|
-
function registerSyncPeerRoutes(ctx, manager, transport, coordinator
|
|
134
|
+
function registerSyncPeerRoutes(ctx, manager, transport, coordinator) {
|
|
135
135
|
ctx.effect(() => ctx.webServer.register({
|
|
136
136
|
kind: "prefix",
|
|
137
137
|
path: "/api/dshb/sync/peers",
|
|
@@ -248,22 +248,6 @@ function registerSyncPeerRoutes(ctx, manager, transport, coordinator, state) {
|
|
|
248
248
|
return;
|
|
249
249
|
}
|
|
250
250
|
if (action === "catalog" && req.method === "GET") {
|
|
251
|
-
if (typeof req.url === "string" && new URL(req.url, "http://x").searchParams.get("cached") === "1") {
|
|
252
|
-
const entry = state?.read().catalogs[peerId];
|
|
253
|
-
if (!entry) {
|
|
254
|
-
sendJson(res, 404, {
|
|
255
|
-
ok: false,
|
|
256
|
-
error: "尚未同步过目录"
|
|
257
|
-
});
|
|
258
|
-
return;
|
|
259
|
-
}
|
|
260
|
-
sendJson(res, 200, {
|
|
261
|
-
ok: true,
|
|
262
|
-
catalog: entry.catalog,
|
|
263
|
-
fetchedAt: entry.fetchedAt
|
|
264
|
-
});
|
|
265
|
-
return;
|
|
266
|
-
}
|
|
267
251
|
if (!transport) {
|
|
268
252
|
sendJson(res, 503, {
|
|
269
253
|
ok: false,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.js","names":[],"sources":["../../../src/core/sync/routes.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-host-webserver'\nimport { SyncHostKeyChallengeError, SyncHostKeyChallengeExpiredError } from './host-key.js'\nimport { SyncPeerInputError, SyncPeerManager, SyncPeerNotFoundError } from './peer-manager.js'\nimport { SyncRemoteProbe, SyncSshProbeError, SyncSshTransport } from './ssh-transport.js'\nimport { SyncCoordinator, SyncCoordinatorError } from './coordinator.js'\nimport type { SyncStateStore } from './stores.js'\n\nconst MAX_BODY_BYTES = 2 * 1024 * 1024\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { 'content-type': 'application/json' })\n res.end(JSON.stringify(body))\n}\n\nfunction readBody(req: IncomingMessage): Promise<Record<string, unknown> | null> {\n return new Promise((resolve) => {\n const contentType = req.headers['content-type']?.split(';', 1)[0]?.trim().toLowerCase()\n if (contentType !== 'application/json') {\n resolve(null)\n return\n }\n\n const chunks: Buffer[] = []\n let size = 0\n let settled = false\n const fail = (): void => {\n if (settled) return\n settled = true\n resolve(null)\n }\n req.on('data', (chunk: Buffer) => {\n if (settled) return\n size += chunk.length\n if (size > MAX_BODY_BYTES) {\n fail()\n req.destroy()\n return\n }\n chunks.push(chunk)\n })\n req.on('end', () => {\n if (settled) return\n try {\n const value: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'))\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n fail()\n return\n }\n settled = true\n resolve(value as Record<string, unknown>)\n } catch {\n fail()\n }\n })\n req.on('error', fail)\n })\n}\n\nfunction pathSegments(req: IncomingMessage): string[] {\n return new URL(req.url ?? '/', 'http://x').pathname.split('/').filter(Boolean)\n}\n\nfunction splitBody(body: Record<string, unknown>): { fields: Record<string, unknown>; secrets: unknown } {\n const { secrets, ...fields } = body\n return { fields, secrets }\n}\n\nfunction sendFailure(res: ServerResponse, error: unknown): void {\n if (error instanceof SyncPeerInputError) {\n sendJson(res, 400, { ok: false, error: error.message })\n return\n }\n if (error instanceof SyncPeerNotFoundError) {\n sendJson(res, 404, { ok: false, error: 'sync peer not found' })\n return\n }\n sendJson(res, 500, { ok: false, error: 'sync peer operation failed' })\n}\n\nfunction sendProbeFailure(res: ServerResponse, error: unknown): void {\n if (error instanceof SyncHostKeyChallengeError) {\n sendJson(res, 409, {\n ok: false,\n code: `host-key-${error.decision}`,\n fingerprint: error.fingerprint,\n ...(error.expected ? { expected: error.expected } : {}),\n })\n return\n }\n if (error instanceof SyncHostKeyChallengeExpiredError) {\n sendJson(res, 409, { ok: false, code: 'host-key-challenge-expired', error: error.message })\n return\n }\n if (error instanceof SyncPeerNotFoundError) {\n sendJson(res, 404, { ok: false, error: 'sync peer not found' })\n return\n }\n if (error instanceof SyncSshProbeError) {\n const status = error.category === 'auth' ? 502 : error.category === 'protocol' || error.category === 'hostkey' ? 409 : 503\n sendJson(res, status, { ok: false, code: `ssh-${error.category}`, error: error.message })\n return\n }\n sendJson(res, 500, { ok: false, error: 'sync peer probe failed' })\n}\n\nfunction sendRunFailure(res: ServerResponse, error: unknown): void {\n if (error instanceof SyncCoordinatorError) {\n const status = error.code === 'peer-not-found' ? 404\n : error.code === 'peer-disabled' || error.code === 'sessions-unavailable' || error.code === 'revision-conflict' ? 409\n : error.code === 'session-bundle-too-large' || error.code === 'session-too-large' ? 413\n : error.code === 'session-workspace-unmapped' || error.code === 'session-format' || error.code === 'session-revision-conflict' || error.code === 'session-same-instance' ? 409\n : error.code.startsWith('ssh-') ? 502 : 500\n sendJson(res, status, { ok: false, code: error.code, error: error.message })\n return\n }\n sendJson(res, 500, { ok: false, error: 'sync run failed' })\n}\n\nexport function registerSyncPeerRoutes(\n ctx: Context,\n manager: SyncPeerManager,\n transport?: SyncSshTransport,\n coordinator?: SyncCoordinator,\n state?: SyncStateStore,\n): void {\n ctx.effect(() =>\n ctx.webServer.register({\n kind: 'prefix',\n path: '/api/dshb/sync/peers',\n handler: async (req, res) => {\n const segments = pathSegments(req)\n const peerId = segments[4]\n const action = segments[5]\n if (segments.length > 6) {\n sendJson(res, 404, { ok: false, error: 'not found' })\n return\n }\n\n if (req.method === 'GET' && peerId === undefined) {\n try {\n sendJson(res, 200, { ok: true, peers: await manager.list() })\n } catch {\n sendJson(res, 500, { ok: false, error: 'sync peer list unavailable' })\n }\n return\n }\n\n if (req.method === 'POST' && peerId === 'probe-remote') {\n // 远端配置探测:① peerId 模式——用已保存对端的存储凭据;② 显式模式——\n // 用表单填写的 SSH 连接信息(新建对端场景)。\n const body = await readBody(req)\n if (!body || (typeof body.peerId !== 'string'\n && (typeof body.host !== 'string' || !body.host.trim()\n || typeof body.username !== 'string' || !body.username.trim()\n || !Number.isInteger(body.port) || (body.port as number) < 1 || (body.port as number) > 65535\n || (body.authKind !== 'password' && body.authKind !== 'key')))) {\n sendJson(res, 400, { ok: false, error: 'either peerId or host/port/username/authKind are required' })\n return\n }\n try {\n const probe = new SyncRemoteProbe()\n let result\n if (typeof body.peerId === 'string' && body.peerId !== 'new') {\n const { peer, secrets } = await manager.connectionData(body.peerId)\n result = await probe.probeRemote(\n { host: peer.host, port: peer.port, username: peer.username, authKind: peer.authKind },\n secrets,\n peer.remoteWebPort,\n )\n } else {\n const secrets = (body.secrets ?? {}) as Record<string, unknown>\n if (body.authKind === 'password' && typeof secrets.password !== 'string') {\n sendJson(res, 400, { ok: false, error: 'SSH password is required for probing' })\n return\n }\n if (body.authKind === 'key' && typeof secrets.privateKey !== 'string') {\n sendJson(res, 400, { ok: false, error: 'SSH private key is required for probing' })\n return\n }\n const authKind = body.authKind === 'key' ? 'key' : 'password'\n result = await probe.probeRemote(\n { host: (body.host as string).trim(), port: body.port as number, username: (body.username as string).trim(), authKind },\n secrets as { password?: string; privateKey?: string; passphrase?: string },\n )\n }\n sendJson(res, 200, { ok: true, probe: result })\n } catch (error) {\n if (error instanceof SyncPeerNotFoundError) {\n sendJson(res, 404, { ok: false, error: '同步节点已不存在' })\n return\n }\n sendProbeFailure(res, error)\n }\n return\n }\n if (req.method === 'POST' && peerId === undefined) {\n const body = await readBody(req)\n if (!body) {\n sendJson(res, 400, { ok: false, error: 'request body must be JSON' })\n return\n }\n const { fields, secrets } = splitBody(body)\n try {\n sendJson(res, 201, { ok: true, peer: await manager.create(fields, secrets) })\n } catch (error) {\n sendFailure(res, error)\n }\n return\n }\n\n if (!peerId) {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n\n if (action === 'catalog' && req.method === 'GET') {\n // ?cached=1 读取元数据同步最近一次落盘目录;默认实时拉取远端。\n if (typeof req.url === 'string' && new URL(req.url, 'http://x').searchParams.get('cached') === '1') {\n const entry = state?.read().catalogs[peerId]\n if (!entry) {\n sendJson(res, 404, { ok: false, error: '尚未同步过目录' })\n return\n }\n sendJson(res, 200, { ok: true, catalog: entry.catalog, fetchedAt: entry.fetchedAt })\n return\n }\n if (!transport) {\n sendJson(res, 503, { ok: false, error: 'SSH sync transport unavailable' })\n return\n }\n try {\n if (!await manager.get(peerId)) {\n sendJson(res, 404, { ok: false, error: 'sync peer not found' })\n return\n }\n sendJson(res, 200, { ok: true, catalog: await transport.fetchCatalog(peerId) })\n } catch (error) {\n sendProbeFailure(res, error)\n }\n return\n }\n\n if (action !== undefined) {\n if (segments.length !== 6 || req.method !== 'POST') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n if (!transport) {\n sendJson(res, 503, { ok: false, error: 'SSH sync transport unavailable' })\n return\n }\n if (action === 'probe') {\n try {\n const handshake = await transport.probe(peerId)\n sendJson(res, 200, { ok: true, handshake })\n } catch (error) {\n sendProbeFailure(res, error)\n }\n return\n }\n if (action === 'trust-host-key') {\n try {\n await transport.trustObservedHostKey(peerId)\n const peer = await manager.get(peerId)\n sendJson(res, 200, { ok: true, peer })\n } catch (error) {\n sendProbeFailure(res, error)\n }\n return\n }\n if (action === 'run') {\n if (!coordinator) {\n sendJson(res, 503, { ok: false, error: 'sync coordinator unavailable' })\n return\n }\n try {\n const peer = await manager.get(peerId)\n if (!peer) {\n sendJson(res, 404, { ok: false, error: 'sync peer not found' })\n return\n }\n if (!peer.enabled) {\n sendJson(res, 409, { ok: false, code: 'peer-disabled', error: '此同步节点已停用' })\n return\n }\n void coordinator.run(peerId).catch(() => undefined)\n sendJson(res, 202, { ok: true, accepted: true })\n } catch (error) {\n sendRunFailure(res, error)\n }\n return\n }\n if (action === 'stop') {\n // 停止运行中的同步:在最近的安全边界中止,丢弃未完成批次,水位不变。\n if (!coordinator) {\n sendJson(res, 503, { ok: false, error: 'sync coordinator unavailable' })\n return\n }\n try {\n await manager.get(peerId)\n sendJson(res, 200, { ok: true, stopped: coordinator.stop(peerId) })\n } catch (error) {\n sendRunFailure(res, error)\n }\n return\n }\n sendJson(res, 404, { ok: false, error: 'not found' })\n return\n }\n\n if (req.method === 'GET') {\n try {\n const peer = await manager.get(peerId)\n if (!peer) {\n sendJson(res, 404, { ok: false, error: 'sync peer not found' })\n return\n }\n sendJson(res, 200, { ok: true, peer })\n } catch {\n sendJson(res, 500, { ok: false, error: 'sync peer lookup failed' })\n }\n return\n }\n\n if (req.method === 'PATCH') {\n const body = await readBody(req)\n if (!body) {\n sendJson(res, 400, { ok: false, error: 'request body must be JSON' })\n return\n }\n const { fields, secrets } = splitBody(body)\n try {\n sendJson(res, 200, { ok: true, peer: await manager.update(peerId, fields, secrets) })\n } catch (error) {\n sendFailure(res, error)\n }\n return\n }\n\n if (req.method === 'DELETE') {\n try {\n if (!(await manager.remove(peerId))) {\n sendJson(res, 404, { ok: false, error: 'sync peer not found' })\n return\n }\n sendJson(res, 200, { ok: true })\n } catch {\n sendJson(res, 500, { ok: false, error: 'sync peer removal failed' })\n }\n return\n }\n\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n },\n }),\n )\n}\n"],"mappings":";;;;;AASA,MAAM,iBAAiB;AAEvB,SAAS,SAAS,KAAqB,QAAgB,MAAqB;CAC1E,IAAI,UAAU,QAAQ,EAAE,gBAAgB,mBAAmB,CAAC;CAC5D,IAAI,IAAI,KAAK,UAAU,IAAI,CAAC;AAC9B;AAEA,SAAS,SAAS,KAA+D;CAC/E,OAAO,IAAI,SAAS,YAAY;EAE9B,IADoB,IAAI,QAAQ,eAAe,EAAE,MAAM,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC,YAAY,MAClE,oBAAoB;GACtC,QAAQ,IAAI;GACZ;EACF;EAEA,MAAM,SAAmB,CAAC;EAC1B,IAAI,OAAO;EACX,IAAI,UAAU;EACd,MAAM,aAAmB;GACvB,IAAI,SAAS;GACb,UAAU;GACV,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AAS;IAC1B,MAAM,OAAO,MAAM,SAAS,GAAG;IAC/B,IAAI,CAAC,MAAM;KACT,SAAS,KAAK,KAAK;MAAE,IAAI;MAAO,OAAO;KAA4B,CAAC;KACpE;IACF;IACA,MAAM,EAAE,QAAQ,YAAY,UAAU,IAAI;IAC1C,IAAI;KACF,SAAS,KAAK,KAAK;MAAE,IAAI;MAAM,MAAM,MAAM,QAAQ,OAAO,QAAQ,QAAQ,OAAO;KAAE,CAAC;IACtF,SAAS,OAAO;KACd,YAAY,KAAK,KAAK;IACxB;IACA;GACF;GAEA,IAAI,IAAI,WAAW,UAAU;IAC3B,IAAI;KACF,IAAI,CAAE,MAAM,QAAQ,OAAO,MAAM,GAAI;MACnC,SAAS,KAAK,KAAK;OAAE,IAAI;OAAO,OAAO;MAAsB,CAAC;MAC9D;KACF;KACA,SAAS,KAAK,KAAK,EAAE,IAAI,KAAK,CAAC;IACjC,QAAQ;KACN,SAAS,KAAK,KAAK;MAAE,IAAI;MAAO,OAAO;KAA2B,CAAC;IACrE;IACA;GACF;GAEA,SAAS,KAAK,KAAK;IAAE,IAAI;IAAO,OAAO;GAAqB,CAAC;EAC/D;CACF,CAAC,CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"routes.js","names":[],"sources":["../../../src/core/sync/routes.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-host-webserver'\nimport { SyncHostKeyChallengeError, SyncHostKeyChallengeExpiredError } from './host-key.js'\nimport { SyncPeerInputError, SyncPeerManager, SyncPeerNotFoundError } from './peer-manager.js'\nimport { SyncRemoteProbe, SyncSshProbeError, SyncSshTransport } from './ssh-transport.js'\nimport { SyncCoordinator, SyncCoordinatorError } from './coordinator.js'\n\nconst MAX_BODY_BYTES = 2 * 1024 * 1024\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { 'content-type': 'application/json' })\n res.end(JSON.stringify(body))\n}\n\nfunction readBody(req: IncomingMessage): Promise<Record<string, unknown> | null> {\n return new Promise((resolve) => {\n const contentType = req.headers['content-type']?.split(';', 1)[0]?.trim().toLowerCase()\n if (contentType !== 'application/json') {\n resolve(null)\n return\n }\n\n const chunks: Buffer[] = []\n let size = 0\n let settled = false\n const fail = (): void => {\n if (settled) return\n settled = true\n resolve(null)\n }\n req.on('data', (chunk: Buffer) => {\n if (settled) return\n size += chunk.length\n if (size > MAX_BODY_BYTES) {\n fail()\n req.destroy()\n return\n }\n chunks.push(chunk)\n })\n req.on('end', () => {\n if (settled) return\n try {\n const value: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'))\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n fail()\n return\n }\n settled = true\n resolve(value as Record<string, unknown>)\n } catch {\n fail()\n }\n })\n req.on('error', fail)\n })\n}\n\nfunction pathSegments(req: IncomingMessage): string[] {\n return new URL(req.url ?? '/', 'http://x').pathname.split('/').filter(Boolean)\n}\n\nfunction splitBody(body: Record<string, unknown>): { fields: Record<string, unknown>; secrets: unknown } {\n const { secrets, ...fields } = body\n return { fields, secrets }\n}\n\nfunction sendFailure(res: ServerResponse, error: unknown): void {\n if (error instanceof SyncPeerInputError) {\n sendJson(res, 400, { ok: false, error: error.message })\n return\n }\n if (error instanceof SyncPeerNotFoundError) {\n sendJson(res, 404, { ok: false, error: 'sync peer not found' })\n return\n }\n sendJson(res, 500, { ok: false, error: 'sync peer operation failed' })\n}\n\nfunction sendProbeFailure(res: ServerResponse, error: unknown): void {\n if (error instanceof SyncHostKeyChallengeError) {\n sendJson(res, 409, {\n ok: false,\n code: `host-key-${error.decision}`,\n fingerprint: error.fingerprint,\n ...(error.expected ? { expected: error.expected } : {}),\n })\n return\n }\n if (error instanceof SyncHostKeyChallengeExpiredError) {\n sendJson(res, 409, { ok: false, code: 'host-key-challenge-expired', error: error.message })\n return\n }\n if (error instanceof SyncPeerNotFoundError) {\n sendJson(res, 404, { ok: false, error: 'sync peer not found' })\n return\n }\n if (error instanceof SyncSshProbeError) {\n const status = error.category === 'auth' ? 502 : error.category === 'protocol' || error.category === 'hostkey' ? 409 : 503\n sendJson(res, status, { ok: false, code: `ssh-${error.category}`, error: error.message })\n return\n }\n sendJson(res, 500, { ok: false, error: 'sync peer probe failed' })\n}\n\nfunction sendRunFailure(res: ServerResponse, error: unknown): void {\n if (error instanceof SyncCoordinatorError) {\n const status = error.code === 'peer-not-found' ? 404\n : error.code === 'peer-disabled' || error.code === 'sessions-unavailable' || error.code === 'revision-conflict' ? 409\n : error.code === 'session-bundle-too-large' || error.code === 'session-too-large' ? 413\n : error.code === 'session-workspace-unmapped' || error.code === 'session-format' || error.code === 'session-revision-conflict' || error.code === 'session-same-instance' ? 409\n : error.code.startsWith('ssh-') ? 502 : 500\n sendJson(res, status, { ok: false, code: error.code, error: error.message })\n return\n }\n sendJson(res, 500, { ok: false, error: 'sync run failed' })\n}\n\nexport function registerSyncPeerRoutes(\n ctx: Context,\n manager: SyncPeerManager,\n transport?: SyncSshTransport,\n coordinator?: SyncCoordinator,\n): void {\n ctx.effect(() =>\n ctx.webServer.register({\n kind: 'prefix',\n path: '/api/dshb/sync/peers',\n handler: async (req, res) => {\n const segments = pathSegments(req)\n const peerId = segments[4]\n const action = segments[5]\n if (segments.length > 6) {\n sendJson(res, 404, { ok: false, error: 'not found' })\n return\n }\n\n if (req.method === 'GET' && peerId === undefined) {\n try {\n sendJson(res, 200, { ok: true, peers: await manager.list() })\n } catch {\n sendJson(res, 500, { ok: false, error: 'sync peer list unavailable' })\n }\n return\n }\n\n if (req.method === 'POST' && peerId === 'probe-remote') {\n // 远端配置探测:① peerId 模式——用已保存对端的存储凭据;② 显式模式——\n // 用表单填写的 SSH 连接信息(新建对端场景)。\n const body = await readBody(req)\n if (!body || (typeof body.peerId !== 'string'\n && (typeof body.host !== 'string' || !body.host.trim()\n || typeof body.username !== 'string' || !body.username.trim()\n || !Number.isInteger(body.port) || (body.port as number) < 1 || (body.port as number) > 65535\n || (body.authKind !== 'password' && body.authKind !== 'key')))) {\n sendJson(res, 400, { ok: false, error: 'either peerId or host/port/username/authKind are required' })\n return\n }\n try {\n const probe = new SyncRemoteProbe()\n let result\n if (typeof body.peerId === 'string' && body.peerId !== 'new') {\n const { peer, secrets } = await manager.connectionData(body.peerId)\n result = await probe.probeRemote(\n { host: peer.host, port: peer.port, username: peer.username, authKind: peer.authKind },\n secrets,\n peer.remoteWebPort,\n )\n } else {\n const secrets = (body.secrets ?? {}) as Record<string, unknown>\n if (body.authKind === 'password' && typeof secrets.password !== 'string') {\n sendJson(res, 400, { ok: false, error: 'SSH password is required for probing' })\n return\n }\n if (body.authKind === 'key' && typeof secrets.privateKey !== 'string') {\n sendJson(res, 400, { ok: false, error: 'SSH private key is required for probing' })\n return\n }\n const authKind = body.authKind === 'key' ? 'key' : 'password'\n result = await probe.probeRemote(\n { host: (body.host as string).trim(), port: body.port as number, username: (body.username as string).trim(), authKind },\n secrets as { password?: string; privateKey?: string; passphrase?: string },\n )\n }\n sendJson(res, 200, { ok: true, probe: result })\n } catch (error) {\n if (error instanceof SyncPeerNotFoundError) {\n sendJson(res, 404, { ok: false, error: '同步节点已不存在' })\n return\n }\n sendProbeFailure(res, error)\n }\n return\n }\n if (req.method === 'POST' && peerId === undefined) {\n const body = await readBody(req)\n if (!body) {\n sendJson(res, 400, { ok: false, error: 'request body must be JSON' })\n return\n }\n const { fields, secrets } = splitBody(body)\n try {\n sendJson(res, 201, { ok: true, peer: await manager.create(fields, secrets) })\n } catch (error) {\n sendFailure(res, error)\n }\n return\n }\n\n if (!peerId) {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n\n if (action === 'catalog' && req.method === 'GET') {\n if (!transport) {\n sendJson(res, 503, { ok: false, error: 'SSH sync transport unavailable' })\n return\n }\n try {\n if (!await manager.get(peerId)) {\n sendJson(res, 404, { ok: false, error: 'sync peer not found' })\n return\n }\n sendJson(res, 200, { ok: true, catalog: await transport.fetchCatalog(peerId) })\n } catch (error) {\n sendProbeFailure(res, error)\n }\n return\n }\n\n if (action !== undefined) {\n if (segments.length !== 6 || req.method !== 'POST') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n if (!transport) {\n sendJson(res, 503, { ok: false, error: 'SSH sync transport unavailable' })\n return\n }\n if (action === 'probe') {\n try {\n const handshake = await transport.probe(peerId)\n sendJson(res, 200, { ok: true, handshake })\n } catch (error) {\n sendProbeFailure(res, error)\n }\n return\n }\n if (action === 'trust-host-key') {\n try {\n await transport.trustObservedHostKey(peerId)\n const peer = await manager.get(peerId)\n sendJson(res, 200, { ok: true, peer })\n } catch (error) {\n sendProbeFailure(res, error)\n }\n return\n }\n if (action === 'run') {\n if (!coordinator) {\n sendJson(res, 503, { ok: false, error: 'sync coordinator unavailable' })\n return\n }\n try {\n const peer = await manager.get(peerId)\n if (!peer) {\n sendJson(res, 404, { ok: false, error: 'sync peer not found' })\n return\n }\n if (!peer.enabled) {\n sendJson(res, 409, { ok: false, code: 'peer-disabled', error: '此同步节点已停用' })\n return\n }\n void coordinator.run(peerId).catch(() => undefined)\n sendJson(res, 202, { ok: true, accepted: true })\n } catch (error) {\n sendRunFailure(res, error)\n }\n return\n }\n if (action === 'stop') {\n // 停止运行中的同步:在最近的安全边界中止,丢弃未完成批次,水位不变。\n if (!coordinator) {\n sendJson(res, 503, { ok: false, error: 'sync coordinator unavailable' })\n return\n }\n try {\n await manager.get(peerId)\n sendJson(res, 200, { ok: true, stopped: coordinator.stop(peerId) })\n } catch (error) {\n sendRunFailure(res, error)\n }\n return\n }\n sendJson(res, 404, { ok: false, error: 'not found' })\n return\n }\n\n if (req.method === 'GET') {\n try {\n const peer = await manager.get(peerId)\n if (!peer) {\n sendJson(res, 404, { ok: false, error: 'sync peer not found' })\n return\n }\n sendJson(res, 200, { ok: true, peer })\n } catch {\n sendJson(res, 500, { ok: false, error: 'sync peer lookup failed' })\n }\n return\n }\n\n if (req.method === 'PATCH') {\n const body = await readBody(req)\n if (!body) {\n sendJson(res, 400, { ok: false, error: 'request body must be JSON' })\n return\n }\n const { fields, secrets } = splitBody(body)\n try {\n sendJson(res, 200, { ok: true, peer: await manager.update(peerId, fields, secrets) })\n } catch (error) {\n sendFailure(res, error)\n }\n return\n }\n\n if (req.method === 'DELETE') {\n try {\n if (!(await manager.remove(peerId))) {\n sendJson(res, 404, { ok: false, error: 'sync peer not found' })\n return\n }\n sendJson(res, 200, { ok: true })\n } catch {\n sendJson(res, 500, { ok: false, error: 'sync peer removal failed' })\n }\n return\n }\n\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n },\n }),\n )\n}\n"],"mappings":";;;;;AAQA,MAAM,iBAAiB;AAEvB,SAAS,SAAS,KAAqB,QAAgB,MAAqB;CAC1E,IAAI,UAAU,QAAQ,EAAE,gBAAgB,mBAAmB,CAAC;CAC5D,IAAI,IAAI,KAAK,UAAU,IAAI,CAAC;AAC9B;AAEA,SAAS,SAAS,KAA+D;CAC/E,OAAO,IAAI,SAAS,YAAY;EAE9B,IADoB,IAAI,QAAQ,eAAe,EAAE,MAAM,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC,YAAY,MAClE,oBAAoB;GACtC,QAAQ,IAAI;GACZ;EACF;EAEA,MAAM,SAAmB,CAAC;EAC1B,IAAI,OAAO;EACX,IAAI,UAAU;EACd,MAAM,aAAmB;GACvB,IAAI,SAAS;GACb,UAAU;GACV,QAAQ,IAAI;EACd;EACA,IAAI,GAAG,SAAS,UAAkB;GAChC,IAAI,SAAS;GACb,QAAQ,MAAM;GACd,IAAI,OAAO,gBAAgB;IACzB,KAAK;IACL,IAAI,QAAQ;IACZ;GACF;GACA,OAAO,KAAK,KAAK;EACnB,CAAC;EACD,IAAI,GAAG,aAAa;GAClB,IAAI,SAAS;GACb,IAAI;IACF,MAAM,QAAiB,KAAK,MAAM,OAAO,OAAO,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC;IACxE,IAAI,UAAU,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IAAO,OAAO;GAAqB,CAAC;EAC/D;CACF,CAAC,CACH;AACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as SyncSessionJournalStore } from "../../session-journal-
|
|
1
|
+
import { t as SyncSessionJournalStore } from "../../session-journal-ftjZuIxo.js";
|
|
2
2
|
export { SyncSessionJournalStore };
|
|
@@ -89,6 +89,16 @@ var SyncSessionJournalStore = class {
|
|
|
89
89
|
pendingPeerIds() {
|
|
90
90
|
return [...new Set(Object.values(this.load().batches).map((batch) => batch.peerId))];
|
|
91
91
|
}
|
|
92
|
+
/** 返回包含该同步记录键的最近一次导入批次;用于把本地会话映射回来源 peer。 */
|
|
93
|
+
peerIdForRecordKey(recordKey) {
|
|
94
|
+
if (typeof recordKey !== "string" || recordKey.length === 0 || recordKey.length > 8192) return void 0;
|
|
95
|
+
let hit;
|
|
96
|
+
for (const batch of Object.values(this.load().batches)) {
|
|
97
|
+
if (!batch.recordKeys.includes(recordKey)) continue;
|
|
98
|
+
if (!hit || batch.startedAt > hit.startedAt) hit = batch;
|
|
99
|
+
}
|
|
100
|
+
return hit?.peerId;
|
|
101
|
+
}
|
|
92
102
|
pendingBatches() {
|
|
93
103
|
return Object.entries(this.load().batches).map(([batchId, batch]) => ({
|
|
94
104
|
batchId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-journal.js","names":[],"sources":["../../../src/core/sync/session-journal.ts"],"sourcesContent":["import { createHash, randomBytes } from 'node:crypto'\nimport { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { Dirent } from 'node:fs'\nimport type { SyncImportMethod } from './model.js'\n\ninterface JournalBatch {\n peerId: string\n sourceName: string\n bundleDigest: string\n startedAt: string\n recordKeys: string[]\n importedVia?: SyncImportMethod\n allowSameInstance?: boolean\n}\n\ninterface JournalData {\n version: 1\n batches: Record<string, JournalBatch>\n}\n\nfunction sessionHome(home?: string): string {\n return home ?? process.env.DSH_HOME ?? join(homedir(), '.dsh')\n}\n\nfunction validBatch(value: unknown): value is JournalBatch {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return false\n const batch = value as Record<string, unknown>\n return typeof batch.peerId === 'string' && /^p-[a-f0-9]{24}$/.test(batch.peerId) &&\n typeof batch.sourceName === 'string' && batch.sourceName.length <= 128 && !/[\\u0000-\\u001f\\u007f]/.test(batch.sourceName) &&\n typeof batch.bundleDigest === 'string' && /^sha256:[a-f0-9]{64}$/.test(batch.bundleDigest) &&\n typeof batch.startedAt === 'string' && batch.startedAt.length <= 64 &&\n Array.isArray(batch.recordKeys) && batch.recordKeys.every((key) => typeof key === 'string' && key.length <= 8192) &&\n (batch.importedVia === undefined || batch.importedVia === 'peer' || batch.importedVia === 'offline') &&\n (batch.allowSameInstance === undefined || typeof batch.allowSameInstance === 'boolean')\n}\n\nfunction validateJournal(value: unknown): JournalData {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid sync session journal')\n const journal = value as Record<string, unknown>\n if (journal.version !== 1 || journal.batches === null || typeof journal.batches !== 'object' || Array.isArray(journal.batches)) {\n throw new Error('Invalid sync session journal')\n }\n const batches = Object.create(null) as Record<string, JournalBatch>\n for (const [id, batch] of Object.entries(journal.batches)) {\n if (!/^b-[a-f0-9]{32}$/.test(id) || !validBatch(batch)) throw new Error('Invalid sync session journal batch')\n batches[id] = {\n ...batch,\n importedVia: batch.importedVia ?? 'peer',\n allowSameInstance: batch.allowSameInstance ?? false,\n recordKeys: [...batch.recordKeys],\n }\n }\n return { version: 1, batches }\n}\n\nfunction atomicWrite(path: string, value: unknown): void {\n mkdirSync(join(path, '..'), { recursive: true, mode: 0o700 })\n const temporary = `${path}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`\n let descriptor: number | undefined\n try {\n descriptor = openSync(temporary, 'wx', 0o600)\n writeFileSync(descriptor, `${JSON.stringify(value, null, 2)}\\n`, 'utf8')\n fsyncSync(descriptor)\n closeSync(descriptor)\n descriptor = undefined\n renameSync(temporary, path)\n chmodSync(path, 0o600)\n } catch (error) {\n if (descriptor !== undefined) closeSync(descriptor)\n try {\n unlinkSync(temporary)\n } catch (cleanupError) {\n if (!(cleanupError instanceof Error) || !('code' in cleanupError) || cleanupError.code !== 'ENOENT') {\n throw new AggregateError([error, cleanupError], 'session journal write and cleanup failed')\n }\n }\n throw error\n }\n}\n\nexport class SyncSessionJournalStore {\n private readonly home: string\n private readonly filePath: string\n private data: JournalData | undefined\n\n constructor(home?: string) {\n this.home = sessionHome(home)\n this.filePath = join(this.home, 'dshb', 'sync-session-journal.json')\n }\n\n begin(\n peerId: string,\n sourceName: string,\n bundleDigest: string,\n recordKeys: readonly string[],\n startedAt = new Date().toISOString(),\n importedVia: SyncImportMethod = 'peer',\n allowSameInstance = false,\n ): string {\n const batchId = `b-${createHash('sha256').update(JSON.stringify([peerId, bundleDigest])).digest('hex').slice(0, 32)}`\n const data = this.load()\n const existing = data.batches[batchId]\n const batch: JournalBatch = {\n peerId,\n sourceName,\n bundleDigest,\n startedAt: existing?.startedAt ?? startedAt,\n recordKeys: [...new Set([...(existing?.recordKeys ?? []), ...recordKeys])],\n importedVia,\n allowSameInstance,\n }\n data.batches[batchId] = batch\n this.save()\n return batchId\n }\n\n beginWithBundle(\n peerId: string,\n sourceName: string,\n bundleDigest: string,\n recordKeys: readonly string[],\n bundle: unknown,\n startedAt = new Date().toISOString(),\n importedVia: SyncImportMethod = 'peer',\n allowSameInstance = false,\n ): string {\n const batchId = `b-${createHash('sha256').update(JSON.stringify([peerId, bundleDigest])).digest('hex').slice(0, 32)}`\n this.writeBundle(batchId, bundle)\n const registered = this.begin(\n peerId,\n sourceName,\n bundleDigest,\n recordKeys,\n startedAt,\n importedVia,\n allowSameInstance,\n )\n if (registered !== batchId) throw new Error('Session journal batch identity changed')\n return batchId\n }\n\n pendingPeerIds(): string[] {\n return [...new Set(Object.values(this.load().batches).map((batch) => batch.peerId))]\n }\n\n pendingBatches(): Array<{ batchId: string; peerId: string; sourceName: string; bundleDigest: string; importedVia: SyncImportMethod; allowSameInstance: boolean }> {\n return Object.entries(this.load().batches).map(([batchId, batch]) => ({\n batchId,\n peerId: batch.peerId,\n sourceName: batch.sourceName,\n bundleDigest: batch.bundleDigest,\n importedVia: batch.importedVia ?? 'peer',\n allowSameInstance: batch.allowSameInstance ?? false,\n }))\n }\n\n findBatch(peerId: string, bundleDigest: string): {\n batchId: string\n peerId: string\n sourceName: string\n bundleDigest: string\n importedVia: SyncImportMethod\n allowSameInstance: boolean\n } | undefined {\n const match = Object.entries(this.load().batches).find(([, batch]) =>\n batch.peerId === peerId && batch.bundleDigest === bundleDigest,\n )\n if (!match) return undefined\n const [batchId, batch] = match\n return {\n batchId,\n peerId: batch.peerId,\n sourceName: batch.sourceName,\n bundleDigest: batch.bundleDigest,\n importedVia: batch.importedVia ?? 'peer',\n allowSameInstance: batch.allowSameInstance ?? false,\n }\n }\n\n writeBundle(batchId: string, value: unknown): void {\n if (!/^b-[a-f0-9]{32}$/.test(batchId)) throw new Error('Invalid sync session batch ID')\n atomicWrite(this.bundlePath(batchId), value)\n }\n\n readBundle(batchId: string): unknown | undefined {\n try {\n return JSON.parse(readFileSync(this.bundlePath(batchId), 'utf8')) as unknown\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined\n throw error\n }\n }\n\n writePrepared(batchId: string, recordKey: string, value: unknown): void {\n if (!/^b-[a-f0-9]{32}$/.test(batchId)) throw new Error('Invalid sync session batch ID')\n const file = this.preparedPath(batchId, recordKey)\n atomicWrite(file, value)\n }\n\n readPrepared(batchId: string, recordKey: string): unknown | undefined {\n const file = this.preparedPath(batchId, recordKey)\n try {\n return JSON.parse(readFileSync(file, 'utf8')) as unknown\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined\n throw error\n }\n }\n\n complete(batchId: string): void {\n const data = this.load()\n delete data.batches[batchId]\n this.save()\n rmSync(join(this.home, 'dshb', 'sync-session-staging', batchId), { recursive: true, force: true })\n }\n\n /**\n * 丢弃一个未完成批次:删除批次记录与暂存目录。用于手动停止同步——\n * 该批未应用的条目不再落地,重启后也不会被 recoverPending 回放。\n * 已应用完成的条目不受影响(它们是完整会话,不是半文件)。\n */\n discard(batchId: string): void {\n if (!/^b-[a-f0-9]{32}$/.test(batchId)) throw new Error('Invalid sync session batch ID')\n const data = this.load()\n if (data.batches[batchId] === undefined) return\n delete data.batches[batchId]\n this.save()\n rmSync(join(this.home, 'dshb', 'sync-session-staging', batchId), { recursive: true, force: true })\n }\n\n cleanupOrphanedStaging(): void {\n const root = join(this.home, 'dshb', 'sync-session-staging')\n let entries: Dirent[]\n try {\n entries = readdirSync(root, { withFileTypes: true })\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return\n throw error\n }\n const activeBatches = new Set(Object.keys(this.load().batches))\n for (const entry of entries) {\n if (entry.isDirectory() && /^b-[a-f0-9]{32}$/.test(entry.name) && !activeBatches.has(entry.name)) {\n rmSync(join(root, entry.name), { recursive: true, force: true })\n }\n }\n }\n\n private preparedPath(batchId: string, recordKey: string): string {\n const digest = createHash('sha256').update(recordKey).digest('hex')\n return join(this.home, 'dshb', 'sync-session-staging', batchId, `${digest}.json`)\n }\n\n private bundlePath(batchId: string): string {\n return join(this.home, 'dshb', 'sync-session-staging', batchId, 'bundle.json')\n }\n\n private load(): JournalData {\n if (this.data) return this.data\n try {\n this.data = validateJournal(JSON.parse(readFileSync(this.filePath, 'utf8')) as unknown)\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {\n this.data = { version: 1, batches: {} }\n } else {\n throw error\n }\n }\n return this.data\n }\n\n private save(): void {\n atomicWrite(this.filePath, this.load())\n }\n}\n"],"mappings":";;;;;AAsBA,SAAS,YAAY,MAAuB;CAC1C,OAAO,QAAQ,QAAQ,IAAI,YAAY,KAAK,QAAQ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;EACnB,YAAY,KAAK,UAAU,KAAK,KAAK,CAAC;CACxC;AACF"}
|
|
1
|
+
{"version":3,"file":"session-journal.js","names":[],"sources":["../../../src/core/sync/session-journal.ts"],"sourcesContent":["import { createHash, randomBytes } from 'node:crypto'\nimport { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { Dirent } from 'node:fs'\nimport type { SyncImportMethod } from './model.js'\n\ninterface JournalBatch {\n peerId: string\n sourceName: string\n bundleDigest: string\n startedAt: string\n recordKeys: string[]\n importedVia?: SyncImportMethod\n allowSameInstance?: boolean\n}\n\ninterface JournalData {\n version: 1\n batches: Record<string, JournalBatch>\n}\n\nfunction sessionHome(home?: string): string {\n return home ?? process.env.DSH_HOME ?? join(homedir(), '.dsh')\n}\n\nfunction validBatch(value: unknown): value is JournalBatch {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return false\n const batch = value as Record<string, unknown>\n return typeof batch.peerId === 'string' && /^p-[a-f0-9]{24}$/.test(batch.peerId) &&\n typeof batch.sourceName === 'string' && batch.sourceName.length <= 128 && !/[\\u0000-\\u001f\\u007f]/.test(batch.sourceName) &&\n typeof batch.bundleDigest === 'string' && /^sha256:[a-f0-9]{64}$/.test(batch.bundleDigest) &&\n typeof batch.startedAt === 'string' && batch.startedAt.length <= 64 &&\n Array.isArray(batch.recordKeys) && batch.recordKeys.every((key) => typeof key === 'string' && key.length <= 8192) &&\n (batch.importedVia === undefined || batch.importedVia === 'peer' || batch.importedVia === 'offline') &&\n (batch.allowSameInstance === undefined || typeof batch.allowSameInstance === 'boolean')\n}\n\nfunction validateJournal(value: unknown): JournalData {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid sync session journal')\n const journal = value as Record<string, unknown>\n if (journal.version !== 1 || journal.batches === null || typeof journal.batches !== 'object' || Array.isArray(journal.batches)) {\n throw new Error('Invalid sync session journal')\n }\n const batches = Object.create(null) as Record<string, JournalBatch>\n for (const [id, batch] of Object.entries(journal.batches)) {\n if (!/^b-[a-f0-9]{32}$/.test(id) || !validBatch(batch)) throw new Error('Invalid sync session journal batch')\n batches[id] = {\n ...batch,\n importedVia: batch.importedVia ?? 'peer',\n allowSameInstance: batch.allowSameInstance ?? false,\n recordKeys: [...batch.recordKeys],\n }\n }\n return { version: 1, batches }\n}\n\nfunction atomicWrite(path: string, value: unknown): void {\n mkdirSync(join(path, '..'), { recursive: true, mode: 0o700 })\n const temporary = `${path}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`\n let descriptor: number | undefined\n try {\n descriptor = openSync(temporary, 'wx', 0o600)\n writeFileSync(descriptor, `${JSON.stringify(value, null, 2)}\\n`, 'utf8')\n fsyncSync(descriptor)\n closeSync(descriptor)\n descriptor = undefined\n renameSync(temporary, path)\n chmodSync(path, 0o600)\n } catch (error) {\n if (descriptor !== undefined) closeSync(descriptor)\n try {\n unlinkSync(temporary)\n } catch (cleanupError) {\n if (!(cleanupError instanceof Error) || !('code' in cleanupError) || cleanupError.code !== 'ENOENT') {\n throw new AggregateError([error, cleanupError], 'session journal write and cleanup failed')\n }\n }\n throw error\n }\n}\n\nexport class SyncSessionJournalStore {\n private readonly home: string\n private readonly filePath: string\n private data: JournalData | undefined\n\n constructor(home?: string) {\n this.home = sessionHome(home)\n this.filePath = join(this.home, 'dshb', 'sync-session-journal.json')\n }\n\n begin(\n peerId: string,\n sourceName: string,\n bundleDigest: string,\n recordKeys: readonly string[],\n startedAt = new Date().toISOString(),\n importedVia: SyncImportMethod = 'peer',\n allowSameInstance = false,\n ): string {\n const batchId = `b-${createHash('sha256').update(JSON.stringify([peerId, bundleDigest])).digest('hex').slice(0, 32)}`\n const data = this.load()\n const existing = data.batches[batchId]\n const batch: JournalBatch = {\n peerId,\n sourceName,\n bundleDigest,\n startedAt: existing?.startedAt ?? startedAt,\n recordKeys: [...new Set([...(existing?.recordKeys ?? []), ...recordKeys])],\n importedVia,\n allowSameInstance,\n }\n data.batches[batchId] = batch\n this.save()\n return batchId\n }\n\n beginWithBundle(\n peerId: string,\n sourceName: string,\n bundleDigest: string,\n recordKeys: readonly string[],\n bundle: unknown,\n startedAt = new Date().toISOString(),\n importedVia: SyncImportMethod = 'peer',\n allowSameInstance = false,\n ): string {\n const batchId = `b-${createHash('sha256').update(JSON.stringify([peerId, bundleDigest])).digest('hex').slice(0, 32)}`\n this.writeBundle(batchId, bundle)\n const registered = this.begin(\n peerId,\n sourceName,\n bundleDigest,\n recordKeys,\n startedAt,\n importedVia,\n allowSameInstance,\n )\n if (registered !== batchId) throw new Error('Session journal batch identity changed')\n return batchId\n }\n\n pendingPeerIds(): string[] {\n return [...new Set(Object.values(this.load().batches).map((batch) => batch.peerId))]\n }\n\n /** 返回包含该同步记录键的最近一次导入批次;用于把本地会话映射回来源 peer。 */\n peerIdForRecordKey(recordKey: string): string | undefined {\n if (typeof recordKey !== 'string' || recordKey.length === 0 || recordKey.length > 8192) return undefined\n let hit: JournalBatch | undefined\n for (const batch of Object.values(this.load().batches)) {\n if (!batch.recordKeys.includes(recordKey)) continue\n if (!hit || batch.startedAt > hit.startedAt) hit = batch\n }\n return hit?.peerId\n }\n\n pendingBatches(): Array<{ batchId: string; peerId: string; sourceName: string; bundleDigest: string; importedVia: SyncImportMethod; allowSameInstance: boolean }> {\n return Object.entries(this.load().batches).map(([batchId, batch]) => ({\n batchId,\n peerId: batch.peerId,\n sourceName: batch.sourceName,\n bundleDigest: batch.bundleDigest,\n importedVia: batch.importedVia ?? 'peer',\n allowSameInstance: batch.allowSameInstance ?? false,\n }))\n }\n\n findBatch(peerId: string, bundleDigest: string): {\n batchId: string\n peerId: string\n sourceName: string\n bundleDigest: string\n importedVia: SyncImportMethod\n allowSameInstance: boolean\n } | undefined {\n const match = Object.entries(this.load().batches).find(([, batch]) =>\n batch.peerId === peerId && batch.bundleDigest === bundleDigest,\n )\n if (!match) return undefined\n const [batchId, batch] = match\n return {\n batchId,\n peerId: batch.peerId,\n sourceName: batch.sourceName,\n bundleDigest: batch.bundleDigest,\n importedVia: batch.importedVia ?? 'peer',\n allowSameInstance: batch.allowSameInstance ?? false,\n }\n }\n\n writeBundle(batchId: string, value: unknown): void {\n if (!/^b-[a-f0-9]{32}$/.test(batchId)) throw new Error('Invalid sync session batch ID')\n atomicWrite(this.bundlePath(batchId), value)\n }\n\n readBundle(batchId: string): unknown | undefined {\n try {\n return JSON.parse(readFileSync(this.bundlePath(batchId), 'utf8')) as unknown\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined\n throw error\n }\n }\n\n writePrepared(batchId: string, recordKey: string, value: unknown): void {\n if (!/^b-[a-f0-9]{32}$/.test(batchId)) throw new Error('Invalid sync session batch ID')\n const file = this.preparedPath(batchId, recordKey)\n atomicWrite(file, value)\n }\n\n readPrepared(batchId: string, recordKey: string): unknown | undefined {\n const file = this.preparedPath(batchId, recordKey)\n try {\n return JSON.parse(readFileSync(file, 'utf8')) as unknown\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined\n throw error\n }\n }\n\n complete(batchId: string): void {\n const data = this.load()\n delete data.batches[batchId]\n this.save()\n rmSync(join(this.home, 'dshb', 'sync-session-staging', batchId), { recursive: true, force: true })\n }\n\n /**\n * 丢弃一个未完成批次:删除批次记录与暂存目录。用于手动停止同步——\n * 该批未应用的条目不再落地,重启后也不会被 recoverPending 回放。\n * 已应用完成的条目不受影响(它们是完整会话,不是半文件)。\n */\n discard(batchId: string): void {\n if (!/^b-[a-f0-9]{32}$/.test(batchId)) throw new Error('Invalid sync session batch ID')\n const data = this.load()\n if (data.batches[batchId] === undefined) return\n delete data.batches[batchId]\n this.save()\n rmSync(join(this.home, 'dshb', 'sync-session-staging', batchId), { recursive: true, force: true })\n }\n\n cleanupOrphanedStaging(): void {\n const root = join(this.home, 'dshb', 'sync-session-staging')\n let entries: Dirent[]\n try {\n entries = readdirSync(root, { withFileTypes: true })\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return\n throw error\n }\n const activeBatches = new Set(Object.keys(this.load().batches))\n for (const entry of entries) {\n if (entry.isDirectory() && /^b-[a-f0-9]{32}$/.test(entry.name) && !activeBatches.has(entry.name)) {\n rmSync(join(root, entry.name), { recursive: true, force: true })\n }\n }\n }\n\n private preparedPath(batchId: string, recordKey: string): string {\n const digest = createHash('sha256').update(recordKey).digest('hex')\n return join(this.home, 'dshb', 'sync-session-staging', batchId, `${digest}.json`)\n }\n\n private bundlePath(batchId: string): string {\n return join(this.home, 'dshb', 'sync-session-staging', batchId, 'bundle.json')\n }\n\n private load(): JournalData {\n if (this.data) return this.data\n try {\n this.data = validateJournal(JSON.parse(readFileSync(this.filePath, 'utf8')) as unknown)\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {\n this.data = { version: 1, batches: {} }\n } else {\n throw error\n }\n }\n return this.data\n }\n\n private save(): void {\n atomicWrite(this.filePath, this.load())\n }\n}\n"],"mappings":";;;;;AAsBA,SAAS,YAAY,MAAuB;CAC1C,OAAO,QAAQ,QAAQ,IAAI,YAAY,KAAK,QAAQ,GAAG,MAAM;AAC/D;AAEA,SAAS,WAAW,OAAuC;CACzD,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG,OAAO;CAChF,MAAM,QAAQ;CACd,OAAO,OAAO,MAAM,WAAW,YAAY,mBAAmB,KAAK,MAAM,MAAM,KAC7E,OAAO,MAAM,eAAe,YAAY,MAAM,WAAW,UAAU,OAAO,CAAC,wBAAwB,KAAK,MAAM,UAAU,KACxH,OAAO,MAAM,iBAAiB,YAAY,wBAAwB,KAAK,MAAM,YAAY,KACzF,OAAO,MAAM,cAAc,YAAY,MAAM,UAAU,UAAU,MACjE,MAAM,QAAQ,MAAM,UAAU,KAAK,MAAM,WAAW,OAAO,QAAQ,OAAO,QAAQ,YAAY,IAAI,UAAU,IA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|
2
2
|
import { Context } from "@deepseek-ai/cordis";
|
|
3
3
|
//#region src/core/sync/session-routes.d.ts
|
|
4
4
|
declare function registerSyncSessionRoutes(ctx: Context, sessions: SyncSessionService): void;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as SyncSessionError } from "../../session-sync-
|
|
1
|
+
import { n as SyncSessionError } from "../../session-sync-BV1CSYic.js";
|
|
2
2
|
//#region src/core/sync/session-routes.ts
|
|
3
3
|
function sendJson(res, status, body) {
|
|
4
4
|
res.writeHead(status, {
|
|
@@ -60,30 +60,6 @@ function registerSyncSessionRoutes(ctx, sessions) {
|
|
|
60
60
|
});
|
|
61
61
|
}
|
|
62
62
|
}));
|
|
63
|
-
ctx.effect(() => ctx.webServer.register({
|
|
64
|
-
kind: "exact",
|
|
65
|
-
path: "/api/dshb/sync/session-sizes",
|
|
66
|
-
handler: async (req, res) => {
|
|
67
|
-
if (req.method !== "GET") {
|
|
68
|
-
sendJson(res, 405, {
|
|
69
|
-
ok: false,
|
|
70
|
-
error: "method not allowed"
|
|
71
|
-
});
|
|
72
|
-
return;
|
|
73
|
-
}
|
|
74
|
-
try {
|
|
75
|
-
sendJson(res, 200, {
|
|
76
|
-
ok: true,
|
|
77
|
-
sessions: await sessions.listSessionSizes()
|
|
78
|
-
});
|
|
79
|
-
} catch {
|
|
80
|
-
sendJson(res, 500, {
|
|
81
|
-
ok: false,
|
|
82
|
-
error: "session size list unavailable"
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
}));
|
|
87
63
|
}
|
|
88
64
|
//#endregion
|
|
89
65
|
export { registerSyncSessionRoutes };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-routes.js","names":[],"sources":["../../../src/core/sync/session-routes.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-host-webserver'\nimport { SyncSessionError, SyncSessionService } from './session-sync.js'\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' })\n res.end(JSON.stringify(body))\n}\n\nfunction pathSegments(req: IncomingMessage): string[] {\n return new URL(req.url ?? '/', 'http://x').pathname.split('/').filter(Boolean)\n}\n\nexport function registerSyncSessionRoutes(ctx: Context, sessions: SyncSessionService): void {\n ctx.effect(() =>\n ctx.webServer.register({\n kind: 'prefix',\n path: '/api/dshb/sync/archives',\n handler: async (req, res) => {\n const segments = pathSegments(req)\n if (req.method === 'GET' && segments.length === 4) {\n try {\n sendJson(res, 200, { ok: true, archives: sessions.listArchives() })\n } catch {\n sendJson(res, 500, { ok: false, error: 'session archive list unavailable' })\n }\n return\n }\n if (req.method === 'POST' && segments.length === 6 && segments[5] === 'restore') {\n const branchId = segments[4]\n if (!/^b-[a-f0-9]{32}$/.test(branchId)) {\n sendJson(res, 400, { ok: false, error: 'invalid session branch ID' })\n return\n }\n try {\n const sessionId = await sessions.restoreArchive(branchId)\n sendJson(res, 200, { ok: true, sessionId })\n } catch (error) {\n const code = error instanceof SyncSessionError ? error.code : 'session-restore-failed'\n sendJson(res, code === 'archive-not-found' ? 404 : 409, {\n ok: false,\n code,\n error: error instanceof SyncSessionError ? error.message : 'session archive restore failed',\n })\n }\n return\n }\n sendJson(res, 404, { ok: false, error: 'not found' })\n },\n }),\n )\n\n
|
|
1
|
+
{"version":3,"file":"session-routes.js","names":[],"sources":["../../../src/core/sync/session-routes.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-host-webserver'\nimport { SyncSessionError, SyncSessionService } from './session-sync.js'\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' })\n res.end(JSON.stringify(body))\n}\n\nfunction pathSegments(req: IncomingMessage): string[] {\n return new URL(req.url ?? '/', 'http://x').pathname.split('/').filter(Boolean)\n}\n\nexport function registerSyncSessionRoutes(ctx: Context, sessions: SyncSessionService): void {\n ctx.effect(() =>\n ctx.webServer.register({\n kind: 'prefix',\n path: '/api/dshb/sync/archives',\n handler: async (req, res) => {\n const segments = pathSegments(req)\n if (req.method === 'GET' && segments.length === 4) {\n try {\n sendJson(res, 200, { ok: true, archives: sessions.listArchives() })\n } catch {\n sendJson(res, 500, { ok: false, error: 'session archive list unavailable' })\n }\n return\n }\n if (req.method === 'POST' && segments.length === 6 && segments[5] === 'restore') {\n const branchId = segments[4]\n if (!/^b-[a-f0-9]{32}$/.test(branchId)) {\n sendJson(res, 400, { ok: false, error: 'invalid session branch ID' })\n return\n }\n try {\n const sessionId = await sessions.restoreArchive(branchId)\n sendJson(res, 200, { ok: true, sessionId })\n } catch (error) {\n const code = error instanceof SyncSessionError ? error.code : 'session-restore-failed'\n sendJson(res, code === 'archive-not-found' ? 404 : 409, {\n ok: false,\n code,\n error: error instanceof SyncSessionError ? error.message : 'session archive restore failed',\n })\n }\n return\n }\n sendJson(res, 404, { ok: false, error: 'not found' })\n },\n }),\n )\n\n}\n"],"mappings":";;AAKA,SAAS,SAAS,KAAqB,QAAgB,MAAqB;CAC1E,IAAI,UAAU,QAAQ;EAAE,gBAAgB;EAAoB,iBAAiB;CAAW,CAAC;CACzF,IAAI,IAAI,KAAK,UAAU,IAAI,CAAC;AAC9B;AAEA,SAAS,aAAa,KAAgC;CACpD,OAAO,IAAI,IAAI,IAAI,OAAO,KAAK,UAAU,CAAC,CAAC,SAAS,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO;AAC/E;AAEA,SAAgB,0BAA0B,KAAc,UAAoC;CAC1F,IAAI,aACF,IAAI,UAAU,SAAS;EACrB,MAAM;EACN,MAAM;EACN,SAAS,OAAO,KAAK,QAAQ;GAC3B,MAAM,WAAW,aAAa,GAAG;GACjC,IAAI,IAAI,WAAW,SAAS,SAAS,WAAW,GAAG;IACjD,IAAI;KACF,SAAS,KAAK,KAAK;MAAE,IAAI;MAAM,UAAU,SAAS,aAAa;KAAE,CAAC;IACpE,QAAQ;KACN,SAAS,KAAK,KAAK;MAAE,IAAI;MAAO,OAAO;KAAmC,CAAC;IAC7E;IACA;GACF;GACA,IAAI,IAAI,WAAW,UAAU,SAAS,WAAW,KAAK,SAAS,OAAO,WAAW;IAC/E,MAAM,WAAW,SAAS;IAC1B,IAAI,CAAC,mBAAmB,KAAK,QAAQ,GAAG;KACtC,SAAS,KAAK,KAAK;MAAE,IAAI;MAAO,OAAO;KAA4B,CAAC;KACpE;IACF;IACA,IAAI;KAEF,SAAS,KAAK,KAAK;MAAE,IAAI;MAAM,WAAA,MADP,SAAS,eAAe,QAAQ;KACf,CAAC;IAC5C,SAAS,OAAO;KACd,MAAM,OAAO,iBAAiB,mBAAmB,MAAM,OAAO;KAC9D,SAAS,KAAK,SAAS,sBAAsB,MAAM,KAAK;MACtD,IAAI;MACJ;MACA,OAAO,iBAAiB,mBAAmB,MAAM,UAAU;KAC7D,CAAC;IACH;IACA;GACF;GACA,SAAS,KAAK,KAAK;IAAE,IAAI;IAAO,OAAO;GAAY,CAAC;EACtD;CACF,CAAC,CACH;AAEF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as sessionEventListDigest, D as validateSyncSessionManifest, E as validateSyncSessionBundle, S as planSessionTransfers, T as validateObjectPayload, _ as SyncSessionWorkspace, a as SyncSessionBundle, b as makeSyncSessionBundle, c as SyncSessionEventDelta, d as SyncSessionManifest, f as SyncSessionManifestEntry, g as SyncSessionTransferPlan, h as SyncSessionService, i as SyncSessionApplyResult, l as SyncSessionEventPrefix, m as SyncSessionObjectInbox, n as SyncObjectInboxWriter, o as SyncSessionEntry, p as SyncSessionObject, r as SyncSessionApplyOptions, s as SyncSessionError, t as ExportObjectCache, u as SyncSessionInstructionSnapshot, v as WorkspaceRegistryLike, w as syncSessionEntryKey, x as makeSyncSessionManifest, y as estimateJsonBytes } from "../../session-sync-
|
|
1
|
+
import { C as sessionEventListDigest, D as validateSyncSessionManifest, E as validateSyncSessionBundle, S as planSessionTransfers, T as validateObjectPayload, _ as SyncSessionWorkspace, a as SyncSessionBundle, b as makeSyncSessionBundle, c as SyncSessionEventDelta, d as SyncSessionManifest, f as SyncSessionManifestEntry, g as SyncSessionTransferPlan, h as SyncSessionService, i as SyncSessionApplyResult, l as SyncSessionEventPrefix, m as SyncSessionObjectInbox, n as SyncObjectInboxWriter, o as SyncSessionEntry, p as SyncSessionObject, r as SyncSessionApplyOptions, s as SyncSessionError, t as ExportObjectCache, u as SyncSessionInstructionSnapshot, v as WorkspaceRegistryLike, w as syncSessionEntryKey, x as makeSyncSessionManifest, y as estimateJsonBytes } from "../../session-sync-AlV-M72t.js";
|
|
2
2
|
export { ExportObjectCache, SyncObjectInboxWriter, SyncSessionApplyOptions, SyncSessionApplyResult, SyncSessionBundle, SyncSessionEntry, SyncSessionError, SyncSessionEventDelta, SyncSessionEventPrefix, SyncSessionInstructionSnapshot, SyncSessionManifest, SyncSessionManifestEntry, SyncSessionObject, SyncSessionObjectInbox, SyncSessionService, SyncSessionTransferPlan, SyncSessionWorkspace, WorkspaceRegistryLike, estimateJsonBytes, makeSyncSessionBundle, makeSyncSessionManifest, planSessionTransfers, sessionEventListDigest, syncSessionEntryKey, validateObjectPayload, validateSyncSessionBundle, validateSyncSessionManifest };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as estimateJsonBytes, c as planSessionTransfers, d as validateObjectPayload, f as validateSyncSessionBundle, i as SyncSessionService, l as sessionEventListDigest, n as SyncSessionError, o as makeSyncSessionBundle, p as validateSyncSessionManifest, r as SyncSessionObjectInbox, s as makeSyncSessionManifest, t as ExportObjectCache, u as syncSessionEntryKey } from "../../session-sync-
|
|
1
|
+
import { a as estimateJsonBytes, c as planSessionTransfers, d as validateObjectPayload, f as validateSyncSessionBundle, i as SyncSessionService, l as sessionEventListDigest, n as SyncSessionError, o as makeSyncSessionBundle, p as validateSyncSessionManifest, r as SyncSessionObjectInbox, s as makeSyncSessionManifest, t as ExportObjectCache, u as syncSessionEntryKey } from "../../session-sync-BV1CSYic.js";
|
|
2
2
|
export { ExportObjectCache, SyncSessionError, SyncSessionObjectInbox, SyncSessionService, estimateJsonBytes, makeSyncSessionBundle, makeSyncSessionManifest, planSessionTransfers, sessionEventListDigest, syncSessionEntryKey, validateObjectPayload, validateSyncSessionBundle, validateSyncSessionManifest };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { _ as parseRemoteProbeOutput, a as SyncRemoteProbe, c as SyncRemoteProbeProfile, d as SyncSshErrorCategory, f as SyncSshProbeError, g as buildSyncSshConnectConfig, h as buildRemoteProbeScript, i as SyncRemoteNodeManifest, l as SyncRemoteProbeResult, m as SyncSshTransport, n as REMOTE_PROBE_END_MARKER, o as SyncRemoteProbeDraft, p as SyncSshSession, r as SyncRemoteHandshake, s as SyncRemoteProbeHandshake, t as REMOTE_PROBE_BEGIN_MARKER, u as SyncSessionDeltaPrefixError } from "../../ssh-transport-
|
|
1
|
+
import { _ as parseRemoteProbeOutput, a as SyncRemoteProbe, c as SyncRemoteProbeProfile, d as SyncSshErrorCategory, f as SyncSshProbeError, g as buildSyncSshConnectConfig, h as buildRemoteProbeScript, i as SyncRemoteNodeManifest, l as SyncRemoteProbeResult, m as SyncSshTransport, n as REMOTE_PROBE_END_MARKER, o as SyncRemoteProbeDraft, p as SyncSshSession, r as SyncRemoteHandshake, s as SyncRemoteProbeHandshake, t as REMOTE_PROBE_BEGIN_MARKER, u as SyncSessionDeltaPrefixError } from "../../ssh-transport-a3qXoscG.js";
|
|
2
2
|
export { REMOTE_PROBE_BEGIN_MARKER, REMOTE_PROBE_END_MARKER, SyncRemoteHandshake, SyncRemoteNodeManifest, SyncRemoteProbe, SyncRemoteProbeDraft, SyncRemoteProbeHandshake, SyncRemoteProbeProfile, SyncRemoteProbeResult, SyncSessionDeltaPrefixError, SyncSshErrorCategory, SyncSshProbeError, SyncSshSession, SyncSshTransport, buildRemoteProbeScript, buildSyncSshConnectConfig, parseRemoteProbeOutput };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { isRecord } from "./model.js";
|
|
2
2
|
import { SyncPeerNotFoundError } from "./peer-manager.js";
|
|
3
3
|
import { MAX_SYNC_DATA_CHUNK_BYTES, SyncFrameDecoder, SyncProtocolError, encodeSyncControlFrame, encodeSyncDataFrame } from "./protocol.js";
|
|
4
|
-
import { n as validateSyncCatalog } from "../../catalog-
|
|
4
|
+
import { n as validateSyncCatalog } from "../../catalog-BPkswHoz.js";
|
|
5
5
|
import { SyncHostKeyChallengeError, SyncHostKeyChallenges, inspectSyncHostKey } from "./host-key.js";
|
|
6
6
|
import { classifySshError } from "../../exec-ssh/connection.js";
|
|
7
7
|
import { REMOTE_SYNC_HELPER_COMMAND } from "./remote-helper.js";
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { t as HlcSnapshot } from "../../revision-C9sOlDZ6.js";
|
|
2
|
-
import { n as SyncStateStore, r as getOrCreateSyncInstanceId, t as SyncPeerStore } from "../../stores-
|
|
2
|
+
import { n as SyncStateStore, r as getOrCreateSyncInstanceId, t as SyncPeerStore } from "../../stores-BwQLabuJ.js";
|
|
3
3
|
export { type HlcSnapshot, SyncPeerStore, SyncStateStore, getOrCreateSyncInstanceId };
|
package/lib/core/sync/stores.js
CHANGED
|
@@ -289,18 +289,13 @@ function requiredString(value, label, maxLength) {
|
|
|
289
289
|
if (typeof value !== "string" || !value.trim() || value.length > maxLength || /[\u0000-\u001f\u007f]/.test(value)) throw new Error(`Invalid ${label}`);
|
|
290
290
|
return value;
|
|
291
291
|
}
|
|
292
|
-
function validateCatalog(value) {
|
|
293
|
-
if (!isRecord(value) || value.protocolVersion !== 1 || typeof value.instanceId !== "string" || !/^i-[a-f0-9]{32}$/.test(value.instanceId) || !Array.isArray(value.nodes) || !Array.isArray(value.workspaces) || !Array.isArray(value.sessions)) throw new Error("Invalid sync catalog payload");
|
|
294
|
-
return value;
|
|
295
|
-
}
|
|
296
292
|
function validateSyncState(value) {
|
|
297
293
|
if (!isRecord(value) || value.version !== 1) throw new Error("Unsupported sync state version");
|
|
298
294
|
if (!isRecord(value.clock) || !isNonNegativeSafeInteger(value.clock.physicalTimeMs) || !isNonNegativeSafeInteger(value.clock.logicalCounter)) throw new Error("Invalid sync clock state");
|
|
299
295
|
if (!isRecord(value.peers) || !isRecord(value.records)) throw new Error("Invalid sync state maps");
|
|
300
296
|
const workspaceValues = value.workspaces === void 0 ? {} : value.workspaces;
|
|
301
297
|
const archiveValues = value.archives === void 0 ? {} : value.archives;
|
|
302
|
-
|
|
303
|
-
if (!isRecord(workspaceValues) || !isRecord(archiveValues) || !isRecord(catalogValues)) throw new Error("Invalid sync session state maps");
|
|
298
|
+
if (!isRecord(workspaceValues) || !isRecord(archiveValues)) throw new Error("Invalid sync session state maps");
|
|
304
299
|
const peers = Object.create(null);
|
|
305
300
|
for (const [id, progress] of Object.entries(value.peers)) {
|
|
306
301
|
if (!/^p-[a-f0-9]{24}$/.test(id)) throw new Error("Invalid sync peer ID in state");
|
|
@@ -320,15 +315,6 @@ function validateSyncState(value) {
|
|
|
320
315
|
}
|
|
321
316
|
const archives = Object.create(null);
|
|
322
317
|
for (const [branchId, archive] of Object.entries(archiveValues)) archives[branchId] = validateArchive(archive, branchId);
|
|
323
|
-
const catalogs = Object.create(null);
|
|
324
|
-
for (const [peerId, entryValue] of Object.entries(catalogValues)) {
|
|
325
|
-
if (!/^p-[a-f0-9]{24}$/.test(peerId)) throw new Error("Invalid sync peer ID in catalog state");
|
|
326
|
-
if (!isRecord(entryValue) || typeof entryValue.fetchedAt !== "string") throw new Error("Invalid sync catalog entry");
|
|
327
|
-
catalogs[peerId] = {
|
|
328
|
-
fetchedAt: entryValue.fetchedAt,
|
|
329
|
-
catalog: validateCatalog(entryValue.catalog)
|
|
330
|
-
};
|
|
331
|
-
}
|
|
332
318
|
return {
|
|
333
319
|
version: 1,
|
|
334
320
|
clock: {
|
|
@@ -338,8 +324,7 @@ function validateSyncState(value) {
|
|
|
338
324
|
peers,
|
|
339
325
|
records,
|
|
340
326
|
workspaces,
|
|
341
|
-
archives
|
|
342
|
-
catalogs
|
|
327
|
+
archives
|
|
343
328
|
};
|
|
344
329
|
}
|
|
345
330
|
function emptySyncState() {
|
|
@@ -352,8 +337,7 @@ function emptySyncState() {
|
|
|
352
337
|
peers: {},
|
|
353
338
|
records: {},
|
|
354
339
|
workspaces: {},
|
|
355
|
-
archives: {}
|
|
356
|
-
catalogs: {}
|
|
340
|
+
archives: {}
|
|
357
341
|
};
|
|
358
342
|
}
|
|
359
343
|
var SyncStateStore = class {
|