conversationShareMockApiClient.ts 26 KB

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