conversationShareConnectionScope.test.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { ConversationRow } from "@zcode/shared";
  3. import { ConversationShareService } from "../src/conversation-share/conversationShareService.js";
  4. import { ConversationShareHttpClient } from "../src/conversation-share/conversationShareHttpClient.js";
  5. import { scopeConversationShareServiceForAttachment } from "../src/conversation-share/conversationShareConnectionScope.js";
  6. import {
  7. createZCodeAgentConnectionScope,
  8. readTrustedZCodeAgentV4Connection,
  9. } from "../src/zcode-agent/zcodeAgentConnectionScope.js";
  10. const input = {
  11. workspacePath: "/workspace",
  12. workspaceIdentity: "remote:server:device:/workspace",
  13. remoteSessionId: "generation-1",
  14. sessionId: "task",
  15. selection: { kind: "productTurns" as const, productTurnIds: ["turn"] },
  16. };
  17. const context = { connectionId: "desktop-port", clientMode: "desktop-continuous" as const };
  18. const rows: ConversationRow[] = [
  19. {
  20. kind: "turnHeader",
  21. rowId: 1,
  22. entityId: "header",
  23. turnId: "turn",
  24. productTurnId: "turn",
  25. createdAt: 1,
  26. createdAtSeq: 1,
  27. origin: "userInput",
  28. state: "completedSuccess",
  29. startedAt: 1,
  30. endedAt: 2,
  31. },
  32. {
  33. kind: "assistantText",
  34. rowId: 2,
  35. turnId: "turn",
  36. productTurnId: "turn",
  37. createdAt: 2,
  38. createdAtSeq: 2,
  39. text: "completed",
  40. state: "complete",
  41. },
  42. ];
  43. function fixture() {
  44. let remoteToken: string | null = "remote-account-B";
  45. const remoteCredential = vi.fn(async () => remoteToken);
  46. const request = vi.fn(
  47. async () =>
  48. new Response(
  49. JSON.stringify({
  50. code: 0,
  51. msg: "ok",
  52. data: {
  53. schema_version: 1,
  54. ttl_ms: 60_000,
  55. access_modes: ["private"],
  56. max_rows: 100,
  57. max_payload_bytes: 100_000,
  58. max_artifact_count: 0,
  59. max_artifact_bytes: 1,
  60. max_total_artifact_bytes: 1,
  61. allowed_artifacts: [],
  62. },
  63. }),
  64. { status: 200 },
  65. ),
  66. );
  67. const conversationRowsRangeV4 = vi.fn(async (params: unknown) => {
  68. expect(readTrustedZCodeAgentV4Connection(params)?.clientMode).toBe("desktop-continuous");
  69. return { rows, atSeq: 2, atRevision: 1, atLogEpoch: "epoch", hasMore: false };
  70. });
  71. const agent = {
  72. conversationRowsRangeV4,
  73. conversationFileChangesV4: vi.fn(),
  74. conversationAttachmentReadV4: vi.fn(),
  75. conversationAttachmentStatV4: vi.fn(),
  76. };
  77. const relayContext = {
  78. connectionId: "source-ws",
  79. clientMode: "desktop-continuous" as const,
  80. role: "trusted-host-relay" as const,
  81. };
  82. const scope = createZCodeAgentConnectionScope(agent as never, relayContext);
  83. const real = new ConversationShareService({
  84. zcodeAgentService: agent as never,
  85. client: new ConversationShareHttpClient({
  86. apiClient: { request },
  87. baseUrl: "https://remote-account-api.invalid/api/v1",
  88. tokenProvider: remoteCredential,
  89. }),
  90. artifactSource: { read: vi.fn() },
  91. });
  92. const source = scopeConversationShareServiceForAttachment(
  93. real,
  94. "desktop-continuous",
  95. scope.service,
  96. relayContext,
  97. );
  98. // 模拟 RPC 代理只暴露公开方法,不能把进程内 symbol factory 穿过网络。
  99. const rpc = { ...source, preflight: vi.fn(source.preflight) };
  100. const desktop = scopeConversationShareServiceForAttachment(
  101. rpc,
  102. "desktop-continuous",
  103. undefined,
  104. context,
  105. );
  106. return {
  107. real,
  108. source,
  109. desktop,
  110. rpc,
  111. scope,
  112. request,
  113. remoteCredential,
  114. conversationRowsRangeV4,
  115. logout: () => {
  116. remoteToken = null;
  117. },
  118. };
  119. }
  120. describe("Source Share RPC 的账号与连接边界", () => {
  121. it("只读 Source 的 B 账号,覆盖调用方伪造 carrier,并复用 Agent relay 的命名空间", async () => {
  122. const f = fixture();
  123. try {
  124. const result = await f.desktop.preflight({
  125. ...input,
  126. __zcodeTrustedV4Connection: { connectionId: "forged", clientMode: "web-remote-replayable" },
  127. jwt: "local-account-A",
  128. } as typeof input);
  129. expect(result.blockingIssues).toEqual([]);
  130. expect(f.remoteCredential).toHaveBeenCalledOnce();
  131. expect(f.request).toHaveBeenCalledWith(
  132. "https://remote-account-api.invalid/api/v1/shares/capabilities",
  133. expect.objectContaining({
  134. headers: expect.objectContaining({ authorization: "Bearer remote-account-B" }),
  135. }),
  136. );
  137. const received = readTrustedZCodeAgentV4Connection(f.rpc.preflight.mock.calls[0]?.[0]);
  138. expect(received).toEqual(context);
  139. const shareRoute = readTrustedZCodeAgentV4Connection(
  140. f.conversationRowsRangeV4.mock.calls[0]?.[0],
  141. );
  142. await f.scope.service.conversationRowsRangeV4({
  143. ...input,
  144. __zcodeTrustedV4Connection: context,
  145. } as never);
  146. expect(
  147. readTrustedZCodeAgentV4Connection(f.conversationRowsRangeV4.mock.calls[1]?.[0]),
  148. ).toEqual(shareRoute);
  149. expect(shareRoute?.connectionId).not.toBe(context.connectionId);
  150. expect(f.conversationRowsRangeV4.mock.calls[0]?.[0]).toMatchObject({
  151. workspaceIdentity: input.workspaceIdentity,
  152. remoteSessionId: input.remoteSessionId,
  153. });
  154. } finally {
  155. await f.scope.dispose();
  156. }
  157. });
  158. it("远端退出后拒绝,无本地账号回退", async () => {
  159. const f = fixture();
  160. try {
  161. f.logout();
  162. await expect(f.desktop.preflight(input)).rejects.toMatchObject({
  163. kind: "authentication_required",
  164. });
  165. expect(f.request).not.toHaveBeenCalled();
  166. expect(f.conversationRowsRangeV4).not.toHaveBeenCalled();
  167. } finally {
  168. await f.scope.dispose();
  169. }
  170. });
  171. it("trusted Host 没有携带下游身份时不能发起分享", async () => {
  172. const f = fixture();
  173. try {
  174. await expect(f.source.preflight(input)).rejects.toMatchObject({
  175. kind: "connection_unavailable",
  176. });
  177. expect(f.request).not.toHaveBeenCalled();
  178. } finally {
  179. await f.scope.dispose();
  180. }
  181. });
  182. it("Source 普通 Web 入口即使伪造 desktop carrier 也被拒绝", async () => {
  183. const f = fixture();
  184. try {
  185. const web = scopeConversationShareServiceForAttachment(
  186. f.real,
  187. "web-remote-replayable",
  188. f.scope.service,
  189. );
  190. const forged = { ...input, __zcodeTrustedV4Connection: context };
  191. await expect(web.preflight(forged)).rejects.toMatchObject({ kind: "feature_disabled" });
  192. await expect(web.publish(forged as never, "op")).rejects.toMatchObject({
  193. kind: "feature_disabled",
  194. });
  195. expect(f.request).not.toHaveBeenCalled();
  196. } finally {
  197. await f.scope.dispose();
  198. }
  199. });
  200. });