conversationShareMockApiClient.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. /* oxlint-disable eslint(max-lines) -- 有状态 Mock 集中模拟 revision 23 六条路由及其共享幂等状态,拆散会隐藏跨路由状态机。 */
  2. /**
  3. * 分享 API 的有状态测试替身。
  4. *
  5. * 只用于测试:让真实的 ConversationShareHttpClient 跑完整
  6. * preparation → upload → confirm → preview → continuation 时序,并按后端契约
  7. * 返回文档化的 status/code 组合。运行时一律走真实 API,因此它必须留在 test/ 下,
  8. * 不能编进 @zcode/services 的发布产物。
  9. */
  10. import { createHash } from "node:crypto";
  11. import {
  12. conversationShareArtifactDescriptorSchema,
  13. conversationShareConfirmRequestSchema,
  14. conversationShareContinuationRequestSchema,
  15. conversationSharePreparationRequestSchema,
  16. type ApiClient,
  17. type ApiRequestInit,
  18. type ConversationShareAccessMode,
  19. type ConversationShareApiErrorCode,
  20. type ConversationShareArtifactDescriptor,
  21. type ConversationShareConfirmRequest,
  22. type ConversationSharePreparationRequest,
  23. type ConversationShareRecord,
  24. } from "@zcode/shared";
  25. import { buildConversationShareConfirmRequest } from "../../src/conversation-share/conversationShareIntegrity.js";
  26. import { assertConversationSharePublicProjection } from "../../src/conversation-share/conversationSharePublicProjection.js";
  27. type MockRoute = "capabilities" | "preparation" | "upload" | "confirm" | "preview" | "continuation";
  28. export interface ConversationShareMockRouteError {
  29. status: number;
  30. code?: ConversationShareApiErrorCode;
  31. msg?: string;
  32. }
  33. export interface ConversationShareMockApiClientOptions {
  34. now?: () => number;
  35. ttlMs?: number;
  36. authenticatedToken?: string;
  37. shareBaseUrl?: string;
  38. scenario?: Partial<Record<MockRoute, ConversationShareMockRouteError>>;
  39. confirmSafetyCheckPendingAttempts?: number;
  40. }
  41. interface StoredPreparation {
  42. preparationId: string;
  43. ownerToken: string;
  44. request: ConversationSharePreparationRequest;
  45. expiresAt: number;
  46. uploads: Map<string, ConversationShareArtifactDescriptor>;
  47. safetyCheckPendingResponses: number;
  48. share?: ConversationShareRecord;
  49. }
  50. interface StoredShare {
  51. shareId: string;
  52. shareCode: string;
  53. ownerToken: string;
  54. createdAt: number;
  55. expiresAt: number;
  56. title: string;
  57. accessMode: ConversationShareAccessMode;
  58. artifacts: ConversationShareArtifactDescriptor[];
  59. request: ConversationShareConfirmRequest;
  60. }
  61. const JSON_HEADERS = { "Content-Type": "application/json" };
  62. function success(data: unknown, headers?: ResponseInit["headers"]): Response {
  63. return new Response(JSON.stringify({ code: 0, msg: "", data }), {
  64. status: 200,
  65. headers: {
  66. ...JSON_HEADERS,
  67. ...Object.fromEntries(new Headers(headers).entries()),
  68. },
  69. });
  70. }
  71. function failure(error: ConversationShareMockRouteError): Response {
  72. if (error.status === 401 && error.code === undefined) {
  73. return new Response(null, { status: 401 });
  74. }
  75. return new Response(
  76. JSON.stringify({
  77. code: error.code ?? 3001,
  78. msg: error.msg ?? "mock request failed",
  79. }),
  80. { status: error.status, headers: JSON_HEADERS },
  81. );
  82. }
  83. function parseBearer(init?: ApiRequestInit): string | null {
  84. const authorization = new Headers(init?.headers).get("Authorization");
  85. const match = /^Bearer\s+(.+)$/iu.exec(authorization ?? "");
  86. return match?.[1]?.trim() || null;
  87. }
  88. function parseJsonBody(init?: ApiRequestInit): unknown {
  89. if (typeof init?.body !== "string") throw new TypeError("Expected a JSON body");
  90. return JSON.parse(init.body) as unknown;
  91. }
  92. /**
  93. * 与 revision 23 HTTP 契约一致的有状态内存 Mock。
  94. *
  95. * Mock 放在 ApiClient 边界,使上层始终运行真实 HTTP 客户端的鉴权、严格 schema
  96. * 和错误映射逻辑;切换到后端环境时只需要替换 ApiClient,不需要修改业务流程。
  97. */
  98. export class ConversationShareMockApiClient implements ApiClient {
  99. private readonly now: () => number;
  100. private readonly ttlMs: number;
  101. private readonly shareBaseUrl: string;
  102. private readonly scenario: Partial<Record<MockRoute, ConversationShareMockRouteError>>;
  103. private readonly confirmSafetyCheckPendingAttempts: number;
  104. private readonly preparations = new Map<string, StoredPreparation>();
  105. private readonly preparationByRequest = new Map<string, StoredPreparation>();
  106. private readonly shares = new Map<string, StoredShare>();
  107. private readonly grants = new Map<string, string>();
  108. private sequence = 0;
  109. constructor(options: ConversationShareMockApiClientOptions = {}) {
  110. const pendingAttempts = options.confirmSafetyCheckPendingAttempts ?? 0;
  111. if (!Number.isSafeInteger(pendingAttempts) || pendingAttempts < 0) {
  112. throw new TypeError("confirmSafetyCheckPendingAttempts must be a non-negative integer");
  113. }
  114. this.confirmSafetyCheckPendingAttempts = pendingAttempts;
  115. this.now = options.now ?? Date.now;
  116. this.ttlMs = options.ttlMs ?? 24 * 60 * 60 * 1_000;
  117. // Mock 生成的链接必须指向当前可运行的 share 页面;示例域名会让本地发布结果变成不可访问的假链接。
  118. this.shareBaseUrl = (
  119. options.shareBaseUrl ??
  120. process.env.ZCODE_CONVERSATION_SHARE_WEB_URL ??
  121. "http://127.0.0.1:5173/cn/share"
  122. ).replace(/\/+$/u, "");
  123. this.scenario = options.scenario ?? {};
  124. }
  125. async request(input: string | URL, init?: ApiRequestInit): Promise<Response> {
  126. const url = new URL(input);
  127. const path = url.pathname.replace(/^\/api\/v1/u, "");
  128. if (path === "/shares/capabilities" && (init?.method ?? "GET") === "GET") {
  129. return this.route("capabilities", () => this.getCapabilities(init));
  130. }
  131. if (path === "/shares/preparations" && init?.method === "POST") {
  132. return this.route("preparation", () => this.createPreparation(init));
  133. }
  134. const upload = /^\/shares\/preparations\/([^/]+)\/artifacts$/u.exec(path);
  135. if (upload && init?.method === "POST") {
  136. return this.route("upload", () => this.uploadArtifact(decodeURIComponent(upload[1]!), init));
  137. }
  138. const confirm = /^\/shares\/preparations\/([^/]+)\/confirm$/u.exec(path);
  139. if (confirm && init?.method === "POST") {
  140. return this.route("confirm", () => this.confirm(decodeURIComponent(confirm[1]!), init));
  141. }
  142. const preview = /^\/shares\/([^/]+)\/preview$/u.exec(path);
  143. if (preview && (init?.method ?? "GET") === "GET") {
  144. return this.route("preview", () => this.getPreview(decodeURIComponent(preview[1]!), init));
  145. }
  146. const continuation = /^\/shares\/([^/]+)\/continuation$/u.exec(path);
  147. if (continuation && init?.method === "POST") {
  148. return this.route("continuation", () =>
  149. this.getContinuation(decodeURIComponent(continuation[1]!), init),
  150. );
  151. }
  152. return failure({ status: 404, code: 3211, msg: "route not found" });
  153. }
  154. private async route(route: MockRoute, handler: () => Promise<Response>): Promise<Response> {
  155. const injected = this.scenario[route];
  156. return injected ? failure(injected) : handler();
  157. }
  158. private requireToken(init?: ApiRequestInit): string | Response {
  159. const token = parseBearer(init);
  160. return token ?? new Response(null, { status: 401 });
  161. }
  162. private async getCapabilities(init?: ApiRequestInit): Promise<Response> {
  163. const token = this.requireToken(init);
  164. if (token instanceof Response) return token;
  165. return success({
  166. schema_version: 1,
  167. ttl_ms: this.ttlMs,
  168. access_modes: ["private", "public_readonly", "public_importable"],
  169. max_rows: 10_000,
  170. max_payload_bytes: 10 * 1024 * 1024,
  171. max_artifact_count: 20,
  172. max_artifact_bytes: 50 * 1024 * 1024,
  173. max_total_artifact_bytes: 200 * 1024 * 1024,
  174. allowed_artifacts: [
  175. { type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] },
  176. { type: "html", extensions: ["html"], mime_types: ["text/html"] },
  177. {
  178. type: "image",
  179. extensions: ["png", "jpg"],
  180. mime_types: ["image/png", "image/jpeg"],
  181. },
  182. {
  183. type: "pptx",
  184. extensions: ["pptx"],
  185. mime_types: ["application/vnd.openxmlformats-officedocument.presentationml.presentation"],
  186. },
  187. {
  188. type: "docx",
  189. extensions: ["docx"],
  190. mime_types: ["application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
  191. },
  192. {
  193. type: "xlsx",
  194. extensions: ["xlsx"],
  195. mime_types: ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
  196. },
  197. { type: "md", extensions: ["md"], mime_types: ["text/markdown"] },
  198. ],
  199. });
  200. }
  201. private async createPreparation(init?: ApiRequestInit): Promise<Response> {
  202. const token = this.requireToken(init);
  203. if (token instanceof Response) return token;
  204. const parsed = conversationSharePreparationRequestSchema.safeParse(parseJsonBody(init));
  205. if (!parsed.success) return failure({ status: 400, code: 3001, msg: "invalid request" });
  206. const requestKey = `${token}:${parsed.data.client_request_id}`;
  207. const existing = this.preparationByRequest.get(requestKey);
  208. if (existing) {
  209. if (JSON.stringify(existing.request) !== JSON.stringify(parsed.data)) {
  210. return failure({
  211. status: 409,
  212. code: 3001,
  213. msg: "idempotency key conflict",
  214. });
  215. }
  216. return success(this.preparationData(existing));
  217. }
  218. const preparation: StoredPreparation = {
  219. preparationId: `mock-preparation-${++this.sequence}`,
  220. ownerToken: token,
  221. request: parsed.data,
  222. expiresAt: this.now() + this.ttlMs,
  223. uploads: new Map(),
  224. safetyCheckPendingResponses: 0,
  225. };
  226. this.preparations.set(preparation.preparationId, preparation);
  227. this.preparationByRequest.set(requestKey, preparation);
  228. return success(this.preparationData(preparation));
  229. }
  230. private preparationData(preparation: StoredPreparation): Record<string, unknown> {
  231. return {
  232. preparation_id: preparation.preparationId,
  233. status: preparation.share ? "confirmed" : "preparing",
  234. access_mode: preparation.request.access_mode,
  235. expires_at: preparation.expiresAt,
  236. ...(preparation.share ? { share: preparation.share } : {}),
  237. };
  238. }
  239. private async uploadArtifact(preparationId: string, init?: ApiRequestInit): Promise<Response> {
  240. const token = this.requireToken(init);
  241. if (token instanceof Response) return token;
  242. const preparation = this.ownedPreparation(preparationId, token);
  243. if (preparation instanceof Response) return preparation;
  244. if (!(init?.body instanceof FormData)) {
  245. return failure({
  246. status: 400,
  247. code: 3001,
  248. msg: "multipart body required",
  249. });
  250. }
  251. const descriptorValue = init.body.get("descriptor");
  252. const file = init.body.get("file");
  253. if (typeof descriptorValue !== "string" || !(file instanceof Blob)) {
  254. return failure({
  255. status: 400,
  256. code: 3001,
  257. msg: "descriptor and file required",
  258. });
  259. }
  260. let descriptorJson: unknown;
  261. try {
  262. descriptorJson = JSON.parse(descriptorValue) as unknown;
  263. } catch {
  264. return failure({ status: 400, code: 3001, msg: "invalid descriptor" });
  265. }
  266. const parsed = conversationShareArtifactDescriptorSchema.safeParse(descriptorJson);
  267. if (!parsed.success) return failure({ status: 422, code: 3205, msg: "invalid artifact" });
  268. // 同一 preparation 内的公开 artifact ID 必须唯一,禁止 Map#set 静默覆盖首次上传。
  269. if (preparation.uploads.has(parsed.data.artifact_id)) {
  270. return failure({ status: 409, code: 3210, msg: "share upload incomplete" });
  271. }
  272. const sha256 = createHash("sha256")
  273. .update(Buffer.from(await file.arrayBuffer()))
  274. .digest("hex");
  275. if (file.size !== parsed.data.size_bytes || sha256 !== parsed.data.sha256) {
  276. return failure({
  277. status: 422,
  278. code: 3205,
  279. msg: "artifact digest mismatch",
  280. });
  281. }
  282. preparation.uploads.set(parsed.data.artifact_id, parsed.data);
  283. return success({
  284. artifact_id: parsed.data.artifact_id,
  285. size_bytes: parsed.data.size_bytes,
  286. sha256,
  287. status: "uploaded",
  288. safety_status: "pending",
  289. });
  290. }
  291. private async confirm(preparationId: string, init?: ApiRequestInit): Promise<Response> {
  292. const token = this.requireToken(init);
  293. if (token instanceof Response) return token;
  294. const preparation = this.ownedPreparation(preparationId, token);
  295. if (preparation instanceof Response) return preparation;
  296. const parsed = conversationShareConfirmRequestSchema.safeParse(parseJsonBody(init));
  297. if (!parsed.success) return failure({ status: 400, code: 3001, msg: "invalid request" });
  298. // Bugfix:只校验 schema/hash 会让 Mock 接受后端必定以 3205 拒绝的本地运行 Row;
  299. // confirm 必须同时执行公开投影约束,保证联调前能复现真实服务端行为。
  300. try {
  301. assertConversationSharePublicProjection({
  302. rows: parsed.data.projection.rows,
  303. selectedProductTurnIds: parsed.data.selected_product_turn_ids,
  304. });
  305. } catch {
  306. return failure({
  307. status: 422,
  308. code: 3205,
  309. msg: "invalid shared conversation",
  310. });
  311. }
  312. if (preparation.share) return success(preparation.share);
  313. const artifacts = [...preparation.uploads.values()].sort((left, right) =>
  314. left.artifact_id.localeCompare(right.artifact_id),
  315. );
  316. if (artifacts.length !== preparation.request.artifact_count) {
  317. return failure({
  318. status: 409,
  319. code: 3210,
  320. msg: "artifact upload incomplete",
  321. });
  322. }
  323. // Bugfix:revision 23 不再在 confirm 重复发送 preparation 元数据和 artifacts;
  324. // Mock 必须像后端一样从 preparation/upload 状态重建后再校验摘要。
  325. const rebuilt = buildConversationShareConfirmRequest({
  326. selected_product_turn_ids: parsed.data.selected_product_turn_ids,
  327. projection: parsed.data.projection,
  328. artifacts,
  329. disclosure_confirmation: parsed.data.disclosure_confirmation,
  330. });
  331. if (
  332. rebuilt.integrity.projection_sha256 !== parsed.data.integrity.projection_sha256 ||
  333. rebuilt.integrity.artifact_set_sha256 !== parsed.data.integrity.artifact_set_sha256
  334. ) {
  335. return failure({
  336. status: 422,
  337. code: 3205,
  338. msg: "payload digest mismatch",
  339. });
  340. }
  341. if (preparation.safetyCheckPendingResponses < this.confirmSafetyCheckPendingAttempts) {
  342. preparation.safetyCheckPendingResponses += 1;
  343. return failure({
  344. status: 409,
  345. code: 3215,
  346. msg: "share safety check pending",
  347. });
  348. }
  349. const shareCode = `mock-share-${++this.sequence}`;
  350. const record: ConversationShareRecord = {
  351. share_code: shareCode,
  352. share_url: `${this.shareBaseUrl}/${encodeURIComponent(shareCode)}`,
  353. access_mode: preparation.request.access_mode,
  354. expires_at: preparation.expiresAt,
  355. };
  356. preparation.share = record;
  357. this.shares.set(shareCode, {
  358. shareId: `mock-share-id-${this.sequence}`,
  359. shareCode,
  360. ownerToken: token,
  361. createdAt: this.now(),
  362. expiresAt: preparation.expiresAt,
  363. title: preparation.request.title,
  364. accessMode: preparation.request.access_mode,
  365. artifacts,
  366. request: parsed.data,
  367. });
  368. return success(record);
  369. }
  370. private async getPreview(shareCode: string, init?: ApiRequestInit): Promise<Response> {
  371. const share = this.availableShare(shareCode);
  372. if (share instanceof Response) return share;
  373. const token = parseBearer(init);
  374. if (share.accessMode === "private" && token !== share.ownerToken) {
  375. return failure({ status: 404, code: 3211, msg: "share not found" });
  376. }
  377. return success(
  378. {
  379. schema_version: 1,
  380. share: this.publicMetadata(share),
  381. rows: share.request.projection.rows,
  382. artifacts: share.artifacts.map((artifact) => ({
  383. ...artifact,
  384. url: `${this.shareBaseUrl}/${encodeURIComponent(shareCode)}/artifacts/${encodeURIComponent(artifact.artifact_id)}`,
  385. url_expires_at: share.expiresAt,
  386. })),
  387. integrity: share.request.integrity,
  388. },
  389. { "Cache-Control": "no-store" },
  390. );
  391. }
  392. private async getContinuation(shareCode: string, init?: ApiRequestInit): Promise<Response> {
  393. const token = this.requireToken(init);
  394. if (token instanceof Response) return token;
  395. const share = this.availableShare(shareCode);
  396. if (share instanceof Response) return share;
  397. const parsed = conversationShareContinuationRequestSchema.safeParse(parseJsonBody(init));
  398. if (!parsed.success) return failure({ status: 400, code: 3001, msg: "invalid request" });
  399. if (
  400. share.accessMode === "public_readonly" ||
  401. (share.accessMode === "private" && token !== share.ownerToken)
  402. ) {
  403. return failure({ status: 403, code: 3214, msg: "import not allowed" });
  404. }
  405. const grantKey = `${shareCode}:${token}:${parsed.data.client_request_id}`;
  406. let grantId = this.grants.get(grantKey);
  407. if (!grantId) {
  408. grantId = `mock-import-grant-${++this.sequence}`;
  409. this.grants.set(grantKey, grantId);
  410. }
  411. return success(
  412. {
  413. schema_version: 1,
  414. import_grant_id: grantId,
  415. import_grant_expires_at: share.expiresAt,
  416. share: { ...this.publicMetadata(share), share_id: share.shareId },
  417. rows: share.request.projection.rows,
  418. artifacts: share.artifacts.map((artifact) => ({
  419. ...artifact,
  420. download_url: `${this.shareBaseUrl}/${encodeURIComponent(shareCode)}/downloads/${encodeURIComponent(artifact.artifact_id)}`,
  421. download_url_expires_at: share.expiresAt,
  422. })),
  423. integrity: share.request.integrity,
  424. },
  425. { "Cache-Control": "no-store" },
  426. );
  427. }
  428. private ownedPreparation(preparationId: string, token: string): StoredPreparation | Response {
  429. const preparation = this.preparations.get(preparationId);
  430. if (!preparation || preparation.ownerToken !== token) {
  431. return failure({ status: 404, code: 3211, msg: "preparation not found" });
  432. }
  433. if (this.now() > preparation.expiresAt) {
  434. return failure({ status: 410, code: 3212, msg: "preparation expired" });
  435. }
  436. return preparation;
  437. }
  438. private availableShare(shareCode: string): StoredShare | Response {
  439. const share = this.shares.get(shareCode);
  440. if (!share) return failure({ status: 404, code: 3211, msg: "share not found" });
  441. if (this.now() > share.expiresAt) {
  442. return failure({ status: 410, code: 3212, msg: "share expired" });
  443. }
  444. return share;
  445. }
  446. private publicMetadata(share: StoredShare): Record<string, unknown> {
  447. return {
  448. title: share.title,
  449. access_mode: share.accessMode,
  450. created_at: share.createdAt,
  451. expires_at: share.expiresAt,
  452. };
  453. }
  454. }