conversationShareMockApiClient.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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 =
  28. | "capabilities"
  29. | "preparation"
  30. | "upload"
  31. | "confirm"
  32. | "preview"
  33. | "continuation"
  34. | "manage";
  35. export interface ConversationShareMockRouteError {
  36. status: number;
  37. code?: ConversationShareApiErrorCode;
  38. msg?: string;
  39. /** 服务端拒绝明细(rule / artifact_id / actual / limit 等)。 */
  40. data?: Record<string, unknown>;
  41. }
  42. export interface ConversationShareMockApiClientOptions {
  43. contentBlockVersions?: Record<string, number>;
  44. now?: () => number;
  45. ttlMs?: number;
  46. /** 创建者可选的有效期范围;null 模拟未声明范围的旧服务端。默认 1 小时至 30 天。 */
  47. ttlRange?: { minMs: number; maxMs: number } | null;
  48. authenticatedToken?: string;
  49. shareBaseUrl?: string;
  50. scenario?: Partial<Record<MockRoute, ConversationShareMockRouteError>>;
  51. confirmSafetyCheckPendingAttempts?: number;
  52. }
  53. interface StoredPreparation {
  54. preparationId: string;
  55. ownerToken: string;
  56. request: ConversationSharePreparationRequest;
  57. expiresAt: number;
  58. uploads: Map<string, ConversationShareArtifactDescriptor>;
  59. safetyCheckPendingResponses: number;
  60. share?: ConversationShareRecord;
  61. }
  62. /** E2E 预置分享的 owner:匹配任意已登录 token,测试进程不需要知道桌面端 JWT。 */
  63. const ANY_OWNER_TOKEN = "*";
  64. const MANAGE_DEFAULT_LIMIT = 20;
  65. interface StoredShare {
  66. shareId: string;
  67. shareCode: string;
  68. ownerToken: string;
  69. status: "active" | "revoked";
  70. sourceSessionId?: string;
  71. createdAt: number;
  72. expiresAt: number;
  73. title: string;
  74. accessMode: ConversationShareAccessMode;
  75. artifacts: ConversationShareArtifactDescriptor[];
  76. request: ConversationShareConfirmRequest;
  77. }
  78. const JSON_HEADERS = { "Content-Type": "application/json" };
  79. function success(data: unknown, headers?: ResponseInit["headers"]): Response {
  80. return new Response(JSON.stringify({ code: 0, msg: "", data }), {
  81. status: 200,
  82. headers: {
  83. ...JSON_HEADERS,
  84. ...Object.fromEntries(new Headers(headers).entries()),
  85. },
  86. });
  87. }
  88. function failure(error: ConversationShareMockRouteError): Response {
  89. if (error.status === 401 && error.code === undefined) {
  90. return new Response(null, { status: 401 });
  91. }
  92. return new Response(
  93. JSON.stringify({
  94. code: error.code ?? 3001,
  95. msg: error.msg ?? "mock request failed",
  96. ...(error.data === undefined ? {} : { data: error.data }),
  97. }),
  98. { status: error.status, headers: JSON_HEADERS },
  99. );
  100. }
  101. function parseBearer(init?: ApiRequestInit): string | null {
  102. const authorization = new Headers(init?.headers).get("Authorization");
  103. const match = /^Bearer\s+(.+)$/iu.exec(authorization ?? "");
  104. return match?.[1]?.trim() || null;
  105. }
  106. function parseJsonBody(init?: ApiRequestInit): unknown {
  107. if (typeof init?.body !== "string") throw new TypeError("Expected a JSON body");
  108. return JSON.parse(init.body) as unknown;
  109. }
  110. /**
  111. * 与 revision 23 HTTP 契约一致的有状态内存 Mock。
  112. *
  113. * Mock 放在 ApiClient 边界,使上层始终运行真实 HTTP 客户端的鉴权、严格 schema
  114. * 和错误映射逻辑;切换到后端环境时只需要替换 ApiClient,不需要修改业务流程。
  115. */
  116. export class ConversationShareMockApiClient implements ApiClient {
  117. private readonly now: () => number;
  118. private readonly ttlMs: number;
  119. private readonly ttlRange: { minMs: number; maxMs: number } | null;
  120. private readonly shareBaseUrl: string;
  121. private readonly scenario: Partial<Record<MockRoute, ConversationShareMockRouteError>>;
  122. private readonly confirmSafetyCheckPendingAttempts: number;
  123. /** 仅 E2E:下一次管理路由请求返回的一次性失败,消费后清空。 */
  124. private nextManageFailure: ConversationShareMockRouteError | undefined;
  125. /** 仅 E2E:下一次产物上传返回的一次性拒绝;data 未带 artifact_id 时补成本次上传的产物。 */
  126. private nextUploadFailure: ConversationShareMockRouteError | undefined;
  127. /** 仅 E2E:覆盖 capabilities 的数值上限;POST 空对象即恢复默认。 */
  128. private capabilityOverrides: Partial<
  129. Record<
  130. "max_rows" | "max_artifact_count" | "max_artifact_bytes" | "max_total_artifact_bytes",
  131. number
  132. >
  133. > = {};
  134. private readonly preparations = new Map<string, StoredPreparation>();
  135. private readonly preparationByRequest = new Map<string, StoredPreparation>();
  136. private readonly shares = new Map<string, StoredShare>();
  137. private readonly grants = new Map<string, string>();
  138. private sequence = 0;
  139. private readonly contentBlockVersions: Record<string, number>;
  140. constructor(options: ConversationShareMockApiClientOptions = {}) {
  141. this.contentBlockVersions = options.contentBlockVersions ?? { workflow: 1 };
  142. const pendingAttempts = options.confirmSafetyCheckPendingAttempts ?? 0;
  143. if (!Number.isSafeInteger(pendingAttempts) || pendingAttempts < 0) {
  144. throw new TypeError("confirmSafetyCheckPendingAttempts must be a non-negative integer");
  145. }
  146. this.confirmSafetyCheckPendingAttempts = pendingAttempts;
  147. this.now = options.now ?? Date.now;
  148. this.ttlMs = options.ttlMs ?? 24 * 60 * 60 * 1_000;
  149. this.ttlRange =
  150. options.ttlRange === undefined
  151. ? { minMs: 60 * 60 * 1_000, maxMs: 30 * 24 * 60 * 60 * 1_000 }
  152. : options.ttlRange;
  153. // Mock 生成的链接必须指向当前可运行的 share 页面;示例域名会让本地发布结果变成不可访问的假链接。
  154. this.shareBaseUrl = (
  155. options.shareBaseUrl ??
  156. process.env.ZCODE_CONVERSATION_SHARE_WEB_URL ??
  157. "http://127.0.0.1:5173/cn/share"
  158. ).replace(/\/+$/u, "");
  159. this.scenario = options.scenario ?? {};
  160. }
  161. async request(input: string | URL, init?: ApiRequestInit): Promise<Response> {
  162. const url = new URL(input);
  163. const path = url.pathname.replace(/^\/api\/v1/u, "");
  164. if (path === "/shares/capabilities" && (init?.method ?? "GET") === "GET") {
  165. return this.route("capabilities", () => this.getCapabilities(init));
  166. }
  167. if (path === "/shares/preparations" && init?.method === "POST") {
  168. return this.route("preparation", () => this.createPreparation(init));
  169. }
  170. const upload = /^\/shares\/preparations\/([^/]+)\/artifacts$/u.exec(path);
  171. if (upload && init?.method === "POST") {
  172. return this.route("upload", () => this.uploadArtifact(decodeURIComponent(upload[1]!), init));
  173. }
  174. const confirm = /^\/shares\/preparations\/([^/]+)\/confirm$/u.exec(path);
  175. if (confirm && init?.method === "POST") {
  176. return this.route("confirm", () => this.confirm(decodeURIComponent(confirm[1]!), init));
  177. }
  178. const preview = /^\/shares\/([^/]+)\/preview$/u.exec(path);
  179. if (preview && (init?.method ?? "GET") === "GET") {
  180. return this.route("preview", () => this.getPreview(decodeURIComponent(preview[1]!), init));
  181. }
  182. // 仅 E2E 诊断:列出全部已存储分享的来源会话,便于定位「没有显示跳转」。
  183. if (path === "/shares/__e2e/managed" && (init?.method ?? "GET") === "GET") {
  184. return success([...this.shares.values()].map((share) => this.managedItem(share)));
  185. }
  186. if (path === "/shares/__e2e/seed-managed" && init?.method === "POST") {
  187. return this.seedManagedShares(init);
  188. }
  189. if (path === "/shares/__e2e/fail-next-manage" && init?.method === "POST") {
  190. this.nextManageFailure = parseJsonBody(init) as ConversationShareMockRouteError;
  191. return success(null);
  192. }
  193. if (path === "/shares/__e2e/fail-next-upload" && init?.method === "POST") {
  194. this.nextUploadFailure = parseJsonBody(init) as ConversationShareMockRouteError;
  195. return success(null);
  196. }
  197. if (path === "/shares/__e2e/capabilities" && init?.method === "POST") {
  198. this.capabilityOverrides = parseJsonBody(init) as typeof this.capabilityOverrides;
  199. return success(null);
  200. }
  201. if (path === "/shares/mine" && (init?.method ?? "GET") === "GET") {
  202. return this.route("manage", () => this.listManagedShares(url, init));
  203. }
  204. const managed = /^\/shares\/mine\/([^/]+?)(?:\/(revoke|restore))?$/u.exec(path);
  205. if (managed) {
  206. const shareId = decodeURIComponent(managed[1]!);
  207. const action = managed[2];
  208. if (action && init?.method === "POST") {
  209. return this.route("manage", () =>
  210. this.setManagedShareStatus(shareId, action === "revoke" ? "revoked" : "active", init),
  211. );
  212. }
  213. if (!action && init?.method === "DELETE") {
  214. return this.route("manage", () => this.deleteManagedShare(shareId, init));
  215. }
  216. }
  217. const continuation = /^\/shares\/([^/]+)\/continuation$/u.exec(path);
  218. if (continuation && init?.method === "POST") {
  219. return this.route("continuation", () =>
  220. this.getContinuation(decodeURIComponent(continuation[1]!), init),
  221. );
  222. }
  223. return failure({ status: 404, code: 3211, msg: "route not found" });
  224. }
  225. private async route(route: MockRoute, handler: () => Promise<Response>): Promise<Response> {
  226. if (route === "manage" && this.nextManageFailure) {
  227. const once = this.nextManageFailure;
  228. this.nextManageFailure = undefined;
  229. return failure(once);
  230. }
  231. const injected = this.scenario[route];
  232. return injected ? failure(injected) : handler();
  233. }
  234. private requireToken(init?: ApiRequestInit): string | Response {
  235. const token = parseBearer(init);
  236. return token ?? new Response(null, { status: 401 });
  237. }
  238. private async getCapabilities(init?: ApiRequestInit): Promise<Response> {
  239. const token = this.requireToken(init);
  240. if (token instanceof Response) return token;
  241. return success({
  242. schema_version: 1,
  243. content_block_versions: this.contentBlockVersions,
  244. ttl_ms: this.ttlMs,
  245. ...(this.ttlRange
  246. ? { min_ttl_ms: this.ttlRange.minMs, max_ttl_ms: this.ttlRange.maxMs }
  247. : {}),
  248. access_modes: ["private", "public_readonly", "public_importable"],
  249. max_rows: 10_000,
  250. max_payload_bytes: 10 * 1024 * 1024,
  251. max_artifact_count: 20,
  252. max_artifact_bytes: 50 * 1024 * 1024,
  253. max_total_artifact_bytes: 200 * 1024 * 1024,
  254. allowed_artifacts: [
  255. { type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] },
  256. { type: "html", extensions: ["html"], mime_types: ["text/html"] },
  257. {
  258. type: "image",
  259. extensions: ["png", "jpg"],
  260. mime_types: ["image/png", "image/jpeg"],
  261. },
  262. {
  263. type: "pptx",
  264. extensions: ["pptx"],
  265. mime_types: ["application/vnd.openxmlformats-officedocument.presentationml.presentation"],
  266. },
  267. {
  268. type: "docx",
  269. extensions: ["docx"],
  270. mime_types: ["application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
  271. },
  272. {
  273. type: "xlsx",
  274. extensions: ["xlsx"],
  275. mime_types: ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
  276. },
  277. { type: "md", extensions: ["md"], mime_types: ["text/markdown"] },
  278. ],
  279. ...this.capabilityOverrides,
  280. });
  281. }
  282. private async createPreparation(init?: ApiRequestInit): Promise<Response> {
  283. const token = this.requireToken(init);
  284. if (token instanceof Response) return token;
  285. const parsed = conversationSharePreparationRequestSchema.safeParse(parseJsonBody(init));
  286. if (!parsed.success) return failure({ status: 400, code: 3001, msg: "invalid request" });
  287. // 与服务端一致:超出范围或未声明范围时拒绝,不静默截断。
  288. const ttl = parsed.data.ttl_ms;
  289. if (
  290. ttl !== undefined &&
  291. (!this.ttlRange || ttl < this.ttlRange.minMs || ttl > this.ttlRange.maxMs)
  292. ) {
  293. return failure({ status: 400, code: 3001, msg: "share ttl out of range" });
  294. }
  295. const requestKey = `${token}:${parsed.data.client_request_id}`;
  296. const existing = this.preparationByRequest.get(requestKey);
  297. if (existing) {
  298. if (JSON.stringify(existing.request) !== JSON.stringify(parsed.data)) {
  299. return failure({
  300. status: 409,
  301. code: 3001,
  302. msg: "idempotency key conflict",
  303. });
  304. }
  305. return success(this.preparationData(existing));
  306. }
  307. const preparation: StoredPreparation = {
  308. preparationId: `mock-preparation-${++this.sequence}`,
  309. ownerToken: token,
  310. request: parsed.data,
  311. expiresAt: this.now() + this.ttlMs,
  312. uploads: new Map(),
  313. safetyCheckPendingResponses: 0,
  314. };
  315. this.preparations.set(preparation.preparationId, preparation);
  316. this.preparationByRequest.set(requestKey, preparation);
  317. return success(this.preparationData(preparation));
  318. }
  319. private preparationData(preparation: StoredPreparation): Record<string, unknown> {
  320. return {
  321. preparation_id: preparation.preparationId,
  322. status: preparation.share ? "confirmed" : "preparing",
  323. access_mode: preparation.request.access_mode,
  324. expires_at: preparation.expiresAt,
  325. ...(preparation.share ? { share: preparation.share } : {}),
  326. };
  327. }
  328. private async uploadArtifact(preparationId: string, init?: ApiRequestInit): Promise<Response> {
  329. const token = this.requireToken(init);
  330. if (token instanceof Response) return token;
  331. const preparation = this.ownedPreparation(preparationId, token);
  332. if (preparation instanceof Response) return preparation;
  333. if (!(init?.body instanceof FormData)) {
  334. return failure({
  335. status: 400,
  336. code: 3001,
  337. msg: "multipart body required",
  338. });
  339. }
  340. const descriptorValue = init.body.get("descriptor");
  341. const file = init.body.get("file");
  342. if (typeof descriptorValue !== "string" || !(file instanceof Blob)) {
  343. return failure({
  344. status: 400,
  345. code: 3001,
  346. msg: "descriptor and file required",
  347. });
  348. }
  349. let descriptorJson: unknown;
  350. try {
  351. descriptorJson = JSON.parse(descriptorValue) as unknown;
  352. } catch {
  353. return failure({ status: 400, code: 3001, msg: "invalid descriptor" });
  354. }
  355. const parsed = conversationShareArtifactDescriptorSchema.safeParse(descriptorJson);
  356. if (!parsed.success) return failure({ status: 422, code: 3205, msg: "invalid artifact" });
  357. if (this.nextUploadFailure) {
  358. const injected = this.nextUploadFailure;
  359. this.nextUploadFailure = undefined;
  360. return failure({
  361. ...injected,
  362. ...(injected.data
  363. ? { data: { artifact_id: parsed.data.artifact_id, ...injected.data } }
  364. : {}),
  365. });
  366. }
  367. // 同一 preparation 内的公开 artifact ID 必须唯一,禁止 Map#set 静默覆盖首次上传。
  368. if (preparation.uploads.has(parsed.data.artifact_id)) {
  369. return failure({ status: 409, code: 3210, msg: "share upload incomplete" });
  370. }
  371. const sha256 = createHash("sha256")
  372. .update(Buffer.from(await file.arrayBuffer()))
  373. .digest("hex");
  374. if (file.size !== parsed.data.size_bytes || sha256 !== parsed.data.sha256) {
  375. return failure({
  376. status: 422,
  377. code: 3205,
  378. msg: "artifact digest mismatch",
  379. });
  380. }
  381. preparation.uploads.set(parsed.data.artifact_id, parsed.data);
  382. return success({
  383. artifact_id: parsed.data.artifact_id,
  384. size_bytes: parsed.data.size_bytes,
  385. sha256,
  386. status: "uploaded",
  387. safety_status: "pending",
  388. });
  389. }
  390. private async confirm(preparationId: string, init?: ApiRequestInit): Promise<Response> {
  391. const token = this.requireToken(init);
  392. if (token instanceof Response) return token;
  393. const preparation = this.ownedPreparation(preparationId, token);
  394. if (preparation instanceof Response) return preparation;
  395. const parsed = conversationShareConfirmRequestSchema.safeParse(parseJsonBody(init));
  396. if (!parsed.success) return failure({ status: 400, code: 3001, msg: "invalid request" });
  397. // Bugfix:只校验 schema/hash 会让 Mock 接受后端必定以 3205 拒绝的本地运行 Row;
  398. // confirm 必须同时执行公开投影约束,保证联调前能复现真实服务端行为。
  399. try {
  400. assertConversationSharePublicProjection({
  401. rows: parsed.data.projection.rows,
  402. selectedProductTurnIds: parsed.data.selected_product_turn_ids,
  403. });
  404. } catch {
  405. return failure({
  406. status: 422,
  407. code: 3205,
  408. msg: "invalid shared conversation",
  409. });
  410. }
  411. if (preparation.share) return success(preparation.share);
  412. const artifacts = [...preparation.uploads.values()].sort((left, right) =>
  413. left.artifact_id.localeCompare(right.artifact_id),
  414. );
  415. if (artifacts.length !== preparation.request.artifact_count) {
  416. return failure({
  417. status: 409,
  418. code: 3210,
  419. msg: "artifact upload incomplete",
  420. });
  421. }
  422. // Bugfix:revision 23 不再在 confirm 重复发送 preparation 元数据和 artifacts;
  423. // Mock 必须像后端一样从 preparation/upload 状态重建后再校验摘要。
  424. const rebuilt = buildConversationShareConfirmRequest({
  425. selected_product_turn_ids: parsed.data.selected_product_turn_ids,
  426. projection: parsed.data.projection,
  427. artifacts,
  428. disclosure_confirmation: parsed.data.disclosure_confirmation,
  429. });
  430. if (
  431. rebuilt.integrity.content_blocks_sha256 !== parsed.data.integrity.content_blocks_sha256 ||
  432. rebuilt.integrity.projection_sha256 !== parsed.data.integrity.projection_sha256 ||
  433. rebuilt.integrity.artifact_set_sha256 !== parsed.data.integrity.artifact_set_sha256
  434. ) {
  435. return failure({
  436. status: 422,
  437. code: 3205,
  438. msg: "payload digest mismatch",
  439. });
  440. }
  441. if (preparation.safetyCheckPendingResponses < this.confirmSafetyCheckPendingAttempts) {
  442. preparation.safetyCheckPendingResponses += 1;
  443. return failure({
  444. status: 409,
  445. code: 3215,
  446. msg: "share safety check pending",
  447. });
  448. }
  449. const shareCode = `mock-share-${++this.sequence}`;
  450. // 分享有效期从 confirm 时起算,取 preparation 记录的 ttl_ms,未指定时用默认值。
  451. const shareExpiresAt = this.now() + (preparation.request.ttl_ms ?? this.ttlMs);
  452. const record: ConversationShareRecord = {
  453. share_code: shareCode,
  454. share_url: `${this.shareBaseUrl}/${encodeURIComponent(shareCode)}`,
  455. access_mode: preparation.request.access_mode,
  456. expires_at: shareExpiresAt,
  457. };
  458. preparation.share = record;
  459. this.shares.set(shareCode, {
  460. shareId: `mock-share-id-${this.sequence}`,
  461. shareCode,
  462. ownerToken: token,
  463. createdAt: this.now(),
  464. expiresAt: shareExpiresAt,
  465. title: preparation.request.title,
  466. accessMode: preparation.request.access_mode,
  467. status: "active",
  468. ...(preparation.request.source_session_id
  469. ? { sourceSessionId: preparation.request.source_session_id }
  470. : {}),
  471. artifacts,
  472. request: parsed.data,
  473. });
  474. return success(record);
  475. }
  476. private async getPreview(shareCode: string, init?: ApiRequestInit): Promise<Response> {
  477. const share = this.availableShare(shareCode);
  478. if (share instanceof Response) return share;
  479. const token = parseBearer(init);
  480. if (share.accessMode === "private" && token !== share.ownerToken) {
  481. return failure({ status: 404, code: 3211, msg: "share not found" });
  482. }
  483. return success(
  484. {
  485. schema_version: 1,
  486. share: this.publicMetadata(share),
  487. rows: share.request.projection.rows,
  488. ...(share.request.projection.content_blocks
  489. ? { content_blocks: share.request.projection.content_blocks }
  490. : {}),
  491. artifacts: share.artifacts.map((artifact) => ({
  492. ...artifact,
  493. url: `${this.shareBaseUrl}/${encodeURIComponent(shareCode)}/artifacts/${encodeURIComponent(artifact.artifact_id)}`,
  494. url_expires_at: share.expiresAt,
  495. })),
  496. integrity: share.request.integrity,
  497. },
  498. { "Cache-Control": "no-store" },
  499. );
  500. }
  501. private async getContinuation(shareCode: string, init?: ApiRequestInit): Promise<Response> {
  502. const token = this.requireToken(init);
  503. if (token instanceof Response) return token;
  504. const share = this.availableShare(shareCode);
  505. if (share instanceof Response) return share;
  506. const parsed = conversationShareContinuationRequestSchema.safeParse(parseJsonBody(init));
  507. if (!parsed.success) return failure({ status: 400, code: 3001, msg: "invalid request" });
  508. if (
  509. share.accessMode === "public_readonly" ||
  510. (share.accessMode === "private" && token !== share.ownerToken)
  511. ) {
  512. return failure({ status: 403, code: 3214, msg: "import not allowed" });
  513. }
  514. const grantKey = `${shareCode}:${token}:${parsed.data.client_request_id}`;
  515. let grantId = this.grants.get(grantKey);
  516. if (!grantId) {
  517. grantId = `mock-import-grant-${++this.sequence}`;
  518. this.grants.set(grantKey, grantId);
  519. }
  520. return success(
  521. {
  522. schema_version: 1,
  523. import_grant_id: grantId,
  524. import_grant_expires_at: share.expiresAt,
  525. share: { ...this.publicMetadata(share), share_id: share.shareId },
  526. rows: share.request.projection.rows,
  527. ...(share.request.projection.content_blocks
  528. ? { content_blocks: share.request.projection.content_blocks }
  529. : {}),
  530. artifacts: share.artifacts.map((artifact) => ({
  531. ...artifact,
  532. download_url: `${this.shareBaseUrl}/${encodeURIComponent(shareCode)}/downloads/${encodeURIComponent(artifact.artifact_id)}`,
  533. download_url_expires_at: share.expiresAt,
  534. })),
  535. integrity: share.request.integrity,
  536. },
  537. { "Cache-Control": "no-store" },
  538. );
  539. }
  540. private ownedPreparation(preparationId: string, token: string): StoredPreparation | Response {
  541. const preparation = this.preparations.get(preparationId);
  542. if (!preparation || preparation.ownerToken !== token) {
  543. return failure({ status: 404, code: 3211, msg: "preparation not found" });
  544. }
  545. if (this.now() > preparation.expiresAt) {
  546. return failure({ status: 410, code: 3212, msg: "preparation expired" });
  547. }
  548. return preparation;
  549. }
  550. private availableShare(shareCode: string): StoredShare | Response {
  551. const share = this.shares.get(shareCode);
  552. if (!share) return failure({ status: 404, code: 3211, msg: "share not found" });
  553. if (this.now() > share.expiresAt) {
  554. return failure({ status: 410, code: 3212, msg: "share expired" });
  555. }
  556. if (share.status === "revoked") {
  557. return failure({ status: 410, code: 3218, msg: "share revoked" });
  558. }
  559. return share;
  560. }
  561. private ownsShare(share: StoredShare, token: string): boolean {
  562. return share.ownerToken === token || share.ownerToken === ANY_OWNER_TOKEN;
  563. }
  564. private managedItem(share: StoredShare): Record<string, unknown> {
  565. return {
  566. share_id: share.shareId,
  567. share_code: share.shareCode,
  568. share_url: `${this.shareBaseUrl}/${encodeURIComponent(share.shareCode)}`,
  569. title: share.title,
  570. access_mode: share.accessMode,
  571. status: share.status,
  572. created_at: share.createdAt,
  573. expires_at: share.expiresAt,
  574. ...(share.sourceSessionId ? { source_session_id: share.sourceSessionId } : {}),
  575. };
  576. }
  577. /** 管理 API:owner 只能看到未过期的 active/revoked 分享,未持有返回 3211。 */
  578. private ownedManagedShare(shareId: string, token: string): StoredShare | Response {
  579. const share = [...this.shares.values()].find((item) => item.shareId === shareId);
  580. if (!share || !this.ownsShare(share, token)) {
  581. return failure({ status: 404, code: 3211, msg: "share not found" });
  582. }
  583. if (this.now() > share.expiresAt) {
  584. return failure({ status: 410, code: 3212, msg: "share expired" });
  585. }
  586. return share;
  587. }
  588. private async listManagedShares(url: URL, init?: ApiRequestInit): Promise<Response> {
  589. const token = this.requireToken(init);
  590. if (token instanceof Response) return token;
  591. const limit = Number(url.searchParams.get("limit") ?? MANAGE_DEFAULT_LIMIT);
  592. const offset = Number(url.searchParams.get("cursor") ?? 0);
  593. const owned = [...this.shares.values()]
  594. .filter((share) => this.ownsShare(share, token) && this.now() <= share.expiresAt)
  595. .sort((left, right) => right.createdAt - left.createdAt);
  596. const page = owned.slice(offset, offset + limit);
  597. const nextOffset = offset + page.length;
  598. return success({
  599. items: page.map((share) => this.managedItem(share)),
  600. ...(nextOffset < owned.length ? { next_cursor: String(nextOffset) } : {}),
  601. });
  602. }
  603. private async setManagedShareStatus(
  604. shareId: string,
  605. status: StoredShare["status"],
  606. init?: ApiRequestInit,
  607. ): Promise<Response> {
  608. const token = this.requireToken(init);
  609. if (token instanceof Response) return token;
  610. const share = this.ownedManagedShare(shareId, token);
  611. if (share instanceof Response) return share;
  612. share.status = status;
  613. return success(this.managedItem(share));
  614. }
  615. private async deleteManagedShare(shareId: string, init?: ApiRequestInit): Promise<Response> {
  616. const token = this.requireToken(init);
  617. if (token instanceof Response) return token;
  618. const share = this.ownedManagedShare(shareId, token);
  619. if (share instanceof Response) return share;
  620. this.shares.delete(share.shareCode);
  621. return success(null);
  622. }
  623. /**
  624. * 仅 E2E:预置不来自本机发布的分享(其他设备的会话、旧版无来源的分享)。
  625. * owner 为任意 token,返回生成的 share_id 供用例断言。
  626. */
  627. private async seedManagedShares(init?: ApiRequestInit): Promise<Response> {
  628. const body = parseJsonBody(init) as {
  629. items: Array<{
  630. title: string;
  631. accessMode?: ConversationShareAccessMode;
  632. sourceSessionId?: string;
  633. }>;
  634. };
  635. const created = body.items.map((item) => {
  636. const shareCode = `mock-share-${++this.sequence}`;
  637. const share: StoredShare = {
  638. shareId: `mock-share-id-${this.sequence}`,
  639. shareCode,
  640. ownerToken: ANY_OWNER_TOKEN,
  641. status: "active",
  642. ...(item.sourceSessionId ? { sourceSessionId: item.sourceSessionId } : {}),
  643. // 比本机发布更早,列表按创建时间倒序时排在后面。
  644. createdAt: this.now() - this.sequence * 60_000,
  645. expiresAt: this.now() + this.ttlMs,
  646. title: item.title,
  647. accessMode: item.accessMode ?? "public_readonly",
  648. artifacts: [],
  649. request: {} as ConversationShareConfirmRequest,
  650. };
  651. this.shares.set(shareCode, share);
  652. return share.shareId;
  653. });
  654. return success({ share_ids: created });
  655. }
  656. private publicMetadata(share: StoredShare): Record<string, unknown> {
  657. return {
  658. title: share.title,
  659. access_mode: share.accessMode,
  660. created_at: share.createdAt,
  661. expires_at: share.expiresAt,
  662. };
  663. }
  664. }