sourceServerContracts.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. ZCODE_COMPATIBILITY_MANIFEST,
  4. sourceServerUpdateTargetSchema,
  5. getSourceServerUpdateTarget,
  6. isSameSourceServerUpdateTarget,
  7. compatibilityManifestSchema,
  8. connectionProfileSchema,
  9. evaluateSourceServerCompatibility,
  10. serverRemoteInfoSchema,
  11. serverRemoteInfoOutputSchema,
  12. serverRemoteAnonymousInfoSchema,
  13. sourceServerRecordSchema,
  14. sourceServerManagementSnapshotSchema,
  15. sourceServerManagementSnapshotRequestSchema,
  16. SOURCE_SERVER_UPDATE_RUNNING_TASKS_ERROR_CODE,
  17. isPublicZCodeErrorCode,
  18. sourceServerConnectionStateSnapshotSchema,
  19. sourceServerOperationLogSchema,
  20. sourceServerInstallProgressSchema,
  21. sourceServerReleaseDescriptorSchema,
  22. } from "../src/index.js";
  23. const profileId = "17ef20b3-622d-4a53-98c1-0cdff29f3e6d";
  24. const sourceServerId = "3cd4f9da-cd79-426c-9d70-75f36e9f6a87";
  25. describe("R3 Source Server contracts", () => {
  26. it("negotiates optional virtualProjects without changing the legacy wire version", () => {
  27. const legacy = {
  28. serverId: sourceServerId,
  29. name: "Server",
  30. version: "3",
  31. protocolVersion: 1,
  32. authRequired: false,
  33. workspaces: [],
  34. capabilities: { desktopContinuous: true, websocketRpc: true },
  35. };
  36. expect(serverRemoteInfoSchema.parse(legacy).capabilities).not.toHaveProperty("virtualProjects");
  37. const modern = { ...legacy, capabilities: { ...legacy.capabilities, virtualProjects: true } };
  38. expect(serverRemoteInfoOutputSchema.parse(modern).capabilities.virtualProjects).toBe(true);
  39. expect(serverRemoteInfoSchema.parse(modern).capabilities.virtualProjects).toBe(true);
  40. });
  41. it("validates read-only install preview and isolated running task projections", () => {
  42. const base = { profileId, state: "needs-install", updatedAt: 1 };
  43. const installPreview = {
  44. version: "3.12.2",
  45. installPath: "/home/dev/.zcode/server",
  46. sizeBytes: 4194304,
  47. };
  48. const runningTasks = [
  49. { sessionId: "task", workspacePath: "/repo", workspaceIdentity: "source:/repo" },
  50. ];
  51. expect(
  52. sourceServerConnectionStateSnapshotSchema.parse({ ...base, installPreview, runningTasks }),
  53. ).toMatchObject({ installPreview, runningTasks });
  54. expect(
  55. sourceServerConnectionStateSnapshotSchema.safeParse({
  56. ...base,
  57. installPreview: { ...installPreview, sizeBytes: -1 },
  58. }).success,
  59. ).toBe(false);
  60. expect(
  61. sourceServerConnectionStateSnapshotSchema.safeParse({
  62. ...base,
  63. runningTasks: [{ sessionId: "task" }],
  64. }).success,
  65. ).toBe(false);
  66. });
  67. it("统计未取得时使用显式状态,不允许附带伪造计数或未知状态", () => {
  68. expect(sourceServerManagementSnapshotRequestSchema.safeParse({}).success).toBe(true);
  69. expect(
  70. sourceServerManagementSnapshotRequestSchema.safeParse({ refreshMigrationCounts: true })
  71. .success,
  72. ).toBe(true);
  73. expect(
  74. sourceServerManagementSnapshotRequestSchema.safeParse({ refreshMigrationCounts: "true" })
  75. .success,
  76. ).toBe(false);
  77. expect(sourceServerManagementSnapshotRequestSchema.safeParse({ extra: true }).success).toBe(
  78. false,
  79. );
  80. const schema = sourceServerManagementSnapshotSchema.shape.migrationCounts.element;
  81. for (const status of ["loading", "unavailable", "requires-connection"]) {
  82. expect(schema.safeParse({ sourceServerId, status }).success).toBe(true);
  83. expect(schema.safeParse({ sourceServerId, status, failedPathCount: 0 }).success).toBe(false);
  84. }
  85. expect(
  86. schema.safeParse({
  87. sourceServerId,
  88. status: "available",
  89. failedPathCount: 0,
  90. abandonedPathCount: 2,
  91. }).success,
  92. ).toBe(true);
  93. expect(schema.safeParse({ sourceServerId, status: "unknown" }).success).toBe(false);
  94. });
  95. it("accepts install progress without allowing readiness or arbitrary payloads", () => {
  96. for (const phase of ["verify-archive", "extract", "verify", "restart"]) {
  97. expect(
  98. sourceServerInstallProgressSchema.safeParse({
  99. type: "source-server-install-progress",
  100. phase,
  101. }).success,
  102. ).toBe(true);
  103. }
  104. for (const value of [
  105. { type: "source-server-install-progress", phase: "ready" },
  106. { type: "source-server-install-progress", phase: "verify", progress: 100 },
  107. { phase: "verify" },
  108. { applied: true },
  109. ])
  110. expect(sourceServerInstallProgressSchema.safeParse(value).success).toBe(false);
  111. });
  112. it("keeps Source update, migration and bind errors in one public registry", () => {
  113. expect(SOURCE_SERVER_UPDATE_RUNNING_TASKS_ERROR_CODE).toBe(
  114. "source-server-update-running-tasks",
  115. );
  116. expect(
  117. [
  118. SOURCE_SERVER_UPDATE_RUNNING_TASKS_ERROR_CODE,
  119. "source-server-upgrade-required",
  120. "workspace-task-identity-conflict",
  121. "workspace-config-file-conflict",
  122. "remote-bind-canceled",
  123. "remote-workspace-bind-session-missing",
  124. "remote-workspace-directory-unavailable",
  125. ].every(isPublicZCodeErrorCode),
  126. ).toBe(true);
  127. expect(isPublicZCodeErrorCode("internal-stack-trace")).toBe(false);
  128. });
  129. it("rejects unregistered error codes in Source management state", () => {
  130. const base = {
  131. profileId,
  132. state: "failed" as const,
  133. updatedAt: 1,
  134. };
  135. expect(
  136. sourceServerConnectionStateSnapshotSchema.safeParse({
  137. ...base,
  138. errorCode: "source-server-private-debug",
  139. }).success,
  140. ).toBe(false);
  141. expect(
  142. sourceServerConnectionStateSnapshotSchema.safeParse({
  143. ...base,
  144. errorCode: "source-server-upgrade-required",
  145. }).success,
  146. ).toBe(true);
  147. });
  148. it("严格校验 Source Server 更新进度日志", () => {
  149. expect(
  150. sourceServerOperationLogSchema.parse({
  151. profileId,
  152. operation: "update",
  153. phase: "upload",
  154. level: "info",
  155. message: "archive",
  156. progress: 0.5,
  157. timestamp: 1,
  158. }),
  159. ).toMatchObject({ phase: "upload", progress: 0.5 });
  160. expect(
  161. sourceServerOperationLogSchema.safeParse({
  162. profileId,
  163. operation: "update",
  164. phase: "upload",
  165. level: "info",
  166. message: "archive",
  167. progress: 1.1,
  168. timestamp: 1,
  169. }).success,
  170. ).toBe(false);
  171. });
  172. it.each([
  173. {
  174. transport: "ssh",
  175. target: {
  176. kind: "ssh",
  177. host: "example.com",
  178. port: 22,
  179. username: "alice",
  180. passwordCredentialKey: `connection-profile:${profileId}:password`,
  181. },
  182. },
  183. {
  184. transport: "wsl",
  185. target: { kind: "wsl", distro: "Ubuntu-24.04", user: "alice" },
  186. },
  187. {
  188. transport: "docker",
  189. target: { kind: "docker", container: "zcode-dev" },
  190. },
  191. ] as const)("accepts a strict $transport Connection Profile", ({ transport, target }) => {
  192. expect(
  193. connectionProfileSchema.parse({
  194. profileId,
  195. transport,
  196. target,
  197. sourceServerId,
  198. createdAt: 1,
  199. }),
  200. ).toMatchObject({ transport, target, lifecycleState: "active" });
  201. });
  202. it("defaults old Source/Profile records to installed and active", () => {
  203. expect(sourceServerRecordSchema.parse({ sourceServerId, displayName: "server" })).toMatchObject(
  204. { installState: "installed", declaredWorkspaces: [] },
  205. );
  206. expect(
  207. connectionProfileSchema.parse({
  208. profileId,
  209. transport: "docker",
  210. target: { kind: "docker", container: "demo" },
  211. createdAt: 1,
  212. }),
  213. ).toMatchObject({ lifecycleState: "active" });
  214. });
  215. it("accepts and strictly validates device-level remote workspace records", () => {
  216. const parsed = sourceServerRecordSchema.parse({
  217. sourceServerId,
  218. displayName: "server",
  219. declaredWorkspaces: [
  220. {
  221. workspacePath: "/srv/project",
  222. workspaceIdentity: `remote:server:${sourceServerId}:/srv/project`,
  223. label: "project",
  224. },
  225. ],
  226. });
  227. expect(parsed.declaredWorkspaces).toEqual([
  228. {
  229. workspacePath: "/srv/project",
  230. workspaceIdentity: `remote:server:${sourceServerId}:/srv/project`,
  231. label: "project",
  232. },
  233. ]);
  234. expect(
  235. sourceServerRecordSchema.safeParse({
  236. sourceServerId,
  237. displayName: "server",
  238. declaredWorkspaces: [{ workspacePath: "/srv/project", unknown: true }],
  239. }).success,
  240. ).toBe(false);
  241. });
  242. it("rejects transport/target mismatches, inline secrets and unknown fields", () => {
  243. expect(
  244. connectionProfileSchema.safeParse({
  245. profileId,
  246. transport: "docker",
  247. target: { kind: "ssh", host: "example.com", username: "alice" },
  248. createdAt: 1,
  249. }).success,
  250. ).toBe(false);
  251. expect(
  252. connectionProfileSchema.safeParse({
  253. profileId,
  254. transport: "ssh",
  255. target: {
  256. kind: "ssh",
  257. host: "example.com",
  258. username: "alice",
  259. password: "secret",
  260. },
  261. createdAt: 1,
  262. }).success,
  263. ).toBe(false);
  264. expect(
  265. connectionProfileSchema.safeParse({
  266. profileId,
  267. transport: "docker",
  268. target: { kind: "docker", container: "zcode-dev" },
  269. createdAt: 1,
  270. unexpected: true,
  271. }).success,
  272. ).toBe(false);
  273. });
  274. it("validates Source Server records strictly", () => {
  275. expect(
  276. sourceServerRecordSchema.parse({
  277. sourceServerId,
  278. displayName: "devbox · alice",
  279. osUser: "alice",
  280. hostname: "devbox",
  281. preferredProfileId: profileId,
  282. }),
  283. ).toMatchObject({ sourceServerId, displayName: "devbox · alice" });
  284. expect(
  285. sourceServerRecordSchema.safeParse({
  286. sourceServerId,
  287. displayName: "devbox · alice",
  288. route: "ssh://example.com",
  289. }).success,
  290. ).toBe(false);
  291. });
  292. it("validates the embedded compatibility manifest", () => {
  293. expect(compatibilityManifestSchema.parse(ZCODE_COMPATIBILITY_MANIFEST)).toEqual(
  294. ZCODE_COMPATIBILITY_MANIFEST,
  295. );
  296. expect(
  297. compatibilityManifestSchema.safeParse({
  298. ...ZCODE_COMPATIBILITY_MANIFEST,
  299. unknown: true,
  300. }).success,
  301. ).toBe(false);
  302. });
  303. it("validates an independent content-addressed Source Server release descriptor", () => {
  304. const descriptor = sourceServerReleaseDescriptorSchema.parse({
  305. schemaVersion: 1,
  306. version: "3.8.1",
  307. archives: [
  308. {
  309. target: "linux-x64",
  310. version: "3.8.1",
  311. fileName: "zcode-server-linux-x64.tar.gz",
  312. sha256: "a".repeat(64),
  313. sizeBytes: 1024,
  314. urls: ["zcode-server-linux-x64.tar.gz"],
  315. },
  316. ],
  317. });
  318. expect(descriptor.archives[0]).toMatchObject({
  319. target: "linux-x64",
  320. sha256: "a".repeat(64),
  321. sizeBytes: 1024,
  322. });
  323. expect(() =>
  324. sourceServerReleaseDescriptorSchema.parse({
  325. ...descriptor,
  326. archives: [descriptor.archives[0], descriptor.archives[0]],
  327. }),
  328. ).toThrow(/duplicate Source Server release target/i);
  329. });
  330. it("keeps client server-info parsing forward compatible while server output stays strict", () => {
  331. const info = {
  332. serverId: sourceServerId,
  333. version: "3.8.0",
  334. protocolVersion: 1,
  335. authRequired: true,
  336. workspaces: [],
  337. compatibility: {
  338. schemaVersion: 1,
  339. productVersion: "3.8.0",
  340. minCompatibleVersion: "3.8.0",
  341. },
  342. migration: { failedPathCount: 2 },
  343. identity: { osUser: "alice", hostname: "devbox" },
  344. capabilities: { desktopContinuous: true, websocketRpc: true },
  345. };
  346. expect(serverRemoteInfoSchema.parse(info)).toEqual(info);
  347. expect(
  348. serverRemoteInfoSchema.parse({
  349. ...info,
  350. futureField: true,
  351. migration: { failedPathCount: 2, futureMigrationField: "ignored" },
  352. }),
  353. ).toEqual(info);
  354. expect(serverRemoteInfoOutputSchema.safeParse({ ...info, futureField: true }).success).toBe(
  355. false,
  356. );
  357. expect(
  358. serverRemoteAnonymousInfoSchema.parse({
  359. version: "3.7.0",
  360. protocolVersion: 1,
  361. authRequired: true,
  362. compatibility: info.compatibility,
  363. futureField: true,
  364. }),
  365. ).toEqual({
  366. version: "3.7.0",
  367. protocolVersion: 1,
  368. authRequired: true,
  369. compatibility: info.compatibility,
  370. });
  371. });
  372. it("lets the newer endpoint manifest decide whether the older endpoint is compatible", () => {
  373. expect(
  374. evaluateSourceServerCompatibility(
  375. {
  376. schemaVersion: 1,
  377. productVersion: "3.9.0",
  378. minCompatibleVersion: "3.8.0",
  379. },
  380. {
  381. schemaVersion: 1,
  382. productVersion: "3.8.2",
  383. minCompatibleVersion: "3.8.0",
  384. },
  385. ),
  386. ).toMatchObject({
  387. compatible: true,
  388. newerEndpoint: "controller",
  389. updateAvailable: true,
  390. });
  391. expect(
  392. evaluateSourceServerCompatibility(
  393. {
  394. schemaVersion: 1,
  395. productVersion: "4.0.0",
  396. minCompatibleVersion: "3.9.0",
  397. },
  398. {
  399. schemaVersion: 1,
  400. productVersion: "3.8.9",
  401. minCompatibleVersion: "3.8.0",
  402. },
  403. ),
  404. ).toMatchObject({ compatible: false, upgradeTarget: "server" });
  405. expect(
  406. evaluateSourceServerCompatibility(
  407. {
  408. schemaVersion: 1,
  409. productVersion: "3.8.0",
  410. minCompatibleVersion: "3.8.0",
  411. },
  412. {
  413. schemaVersion: 1,
  414. productVersion: "4.0.0",
  415. minCompatibleVersion: "3.9.0",
  416. },
  417. ),
  418. ).toMatchObject({ compatible: false, upgradeTarget: "controller" });
  419. });
  420. });
  421. it("升级身份只允许规范化非敏感字段,WSL 必须已解析", () => {
  422. const ssh = {
  423. kind: "ssh",
  424. host: " Example.com ",
  425. username: "dev",
  426. password: "secret",
  427. privateKeyPath: "/tmp/key",
  428. } as const;
  429. expect(getSourceServerUpdateTarget(ssh)).toEqual({
  430. kind: "ssh",
  431. host: "example.com",
  432. port: 22,
  433. username: "dev",
  434. });
  435. expect(
  436. isSameSourceServerUpdateTarget(ssh, {
  437. kind: "ssh",
  438. host: "example.com",
  439. port: 22,
  440. username: "dev",
  441. }),
  442. ).toBe(true);
  443. expect(sourceServerUpdateTargetSchema.safeParse({ kind: "wsl", distro: "Ubuntu" }).success).toBe(
  444. false,
  445. );
  446. expect(
  447. sourceServerUpdateTargetSchema.safeParse({ kind: "wsl", distro: "Ubuntu", user: "" }).success,
  448. ).toBe(false);
  449. expect(
  450. sourceServerUpdateTargetSchema.safeParse({ kind: "docker", container: "a", password: "secret" })
  451. .success,
  452. ).toBe(false);
  453. expect(sourceServerUpdateTargetSchema.safeParse(ssh).success).toBe(false);
  454. });
  455. it("尚未解析的 WSL Profile 不匹配实际升级身份", () => {
  456. expect(
  457. isSameSourceServerUpdateTarget({ kind: "wsl" }, { kind: "wsl", distro: "Ubuntu", user: "dev" }),
  458. ).toBe(false);
  459. });