source-server-update-disconnect.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. import { BufferReader, BufferWriter, deserialize, serialize, VSBuffer } from "@zcode/rpc";
  2. import { ISourceServerManagementService, type UpdateConnectionProfileInput } from "@zcode/services";
  3. const DISCONNECT_REQUEST = -8301;
  4. const UPDATE_REQUEST = -8302;
  5. const SAVE_PROFILE_REQUEST = -8303;
  6. interface UpdateDisconnectProbe {
  7. sent: boolean;
  8. requests: number[][];
  9. responses: number[][];
  10. restore(): void;
  11. }
  12. declare global {
  13. interface Window {
  14. __updateDisconnectProbe?: UpdateDisconnectProbe;
  15. }
  16. }
  17. /** 更新 UI 会禁用同卡按钮;在真实 updating 事件到达时提交并发 RPC,覆盖 Host 必须兑现的断开终态。 */
  18. export async function disconnectDuringNextSourceUpdate(sourceServerId: string): Promise<void> {
  19. await observeUpdateCancellation(sourceServerId, "disconnectSource", sourceServerId);
  20. }
  21. /** 两条真实 SSH 线路已建立;经同一 Host RPC 更新 B,并在 A 的物理连接失效时删除 B。 */
  22. export async function updateAndRemoveNonCurrentProfile(
  23. sourceServerId: string,
  24. ownerProfileId: string,
  25. profile: UpdateConnectionProfileInput,
  26. ): Promise<void> {
  27. await observeUpdateCancellation(sourceServerId, "removeProfile", profile.profileId, ownerProfileId, profile);
  28. }
  29. async function observeUpdateCancellation(
  30. sourceServerId: string,
  31. command: "disconnectSource" | "removeProfile",
  32. removedId: string,
  33. ownerProfileId?: string,
  34. profile?: UpdateConnectionProfileInput,
  35. ): Promise<void> {
  36. const writer = new BufferWriter();
  37. serialize(writer, [
  38. 100,
  39. DISCONNECT_REQUEST,
  40. ISourceServerManagementService.channelName,
  41. command,
  42. ]);
  43. serialize(writer, [removedId]);
  44. const updateWriter = new BufferWriter();
  45. serialize(updateWriter, [100, UPDATE_REQUEST, ISourceServerManagementService.channelName, "updateSource"]);
  46. serialize(updateWriter, [{ profileId: removedId }]);
  47. // 复用已在线 Source 的线路可能没有独立保存密码;经正式设置命令准备可静默更新的 B 线路。
  48. const profileWriter = new BufferWriter();
  49. serialize(profileWriter, [100, SAVE_PROFILE_REQUEST, ISourceServerManagementService.channelName, "updateProfile"]);
  50. serialize(profileWriter, [profile]);
  51. const savedHeader = new BufferWriter();
  52. serialize(savedHeader, [201, SAVE_PROFILE_REQUEST]);
  53. await browser.execute(
  54. (channel, sourceId, disconnectRequest, ownerId, updateRequest, saveProfileRequest, savedPrefix) => {
  55. const original = MessagePort.prototype.postMessage;
  56. let removeListener: (() => void) | undefined;
  57. const probe: UpdateDisconnectProbe = {
  58. sent: false,
  59. requests: [],
  60. responses: [],
  61. restore() {
  62. MessagePort.prototype.postMessage = original;
  63. removeListener?.();
  64. delete window.__updateDisconnectProbe;
  65. },
  66. };
  67. function receive(this: MessagePort, event: MessageEvent) {
  68. if (!(event.data instanceof Uint8Array)) return;
  69. probe.responses.push(Array.from(event.data));
  70. if (saveProfileRequest.length && savedPrefix.every((byte, index) => event.data[index] === byte))
  71. original.call(this, Uint8Array.from(updateRequest));
  72. const text = new TextDecoder().decode(event.data);
  73. if (
  74. !probe.sent && text.includes('"state":"updating"') && text.includes(sourceId) &&
  75. (!ownerId || (text.includes('"state":{') && text.includes(`"profileId":"${ownerId}"`)))
  76. ) {
  77. probe.sent = true;
  78. original.call(this, Uint8Array.from(disconnectRequest));
  79. }
  80. }
  81. MessagePort.prototype.postMessage = function (message: unknown, options?: unknown) {
  82. let startUpdate = false;
  83. if (message instanceof Uint8Array) {
  84. const text = new TextDecoder().decode(message);
  85. if (!ownerId && removeListener && text.includes(channel) && text.includes("updateSource"))
  86. throw new Error("Unexpected second update request");
  87. if (text.includes(channel) && text.includes(ownerId ? "getSnapshot" : "updateSource") && !removeListener) {
  88. removeListener = () => this.removeEventListener("message", receive);
  89. probe.requests.push(ownerId ? updateRequest : Array.from(message));
  90. this.addEventListener("message", receive);
  91. startUpdate = Boolean(ownerId);
  92. }
  93. }
  94. Reflect.apply(original, this, options === undefined ? [message] : [message, options]);
  95. if (startUpdate) original.call(this, Uint8Array.from(saveProfileRequest.length ? saveProfileRequest : updateRequest));
  96. };
  97. window.__updateDisconnectProbe = probe;
  98. },
  99. ISourceServerManagementService.channelName,
  100. sourceServerId,
  101. Array.from(writer.buffer.buffer),
  102. ownerProfileId,
  103. Array.from(updateWriter.buffer.buffer),
  104. profile ? Array.from(profileWriter.buffer.buffer) : [],
  105. Array.from(savedHeader.buffer.buffer),
  106. );
  107. }
  108. export async function readUpdateDisconnectEvidence() {
  109. const probe = await browser.execute(() => {
  110. const probe = window.__updateDisconnectProbe;
  111. return probe
  112. ? { sent: probe.sent, requests: probe.requests, responses: probe.responses }
  113. : null;
  114. });
  115. if (!probe) throw new Error("Missing update disconnect probe");
  116. const decode = (bytes: number[]) => {
  117. const reader = new BufferReader(VSBuffer.wrap(Uint8Array.from(bytes)));
  118. return { header: deserialize(reader) as [number, number], body: deserialize(reader) };
  119. };
  120. const updateId = probe.requests[0] ? decode(probe.requests[0]).header[1] : undefined;
  121. const frames = probe.responses.map(decode);
  122. return {
  123. sent: probe.sent,
  124. savedProfile: frames.find((frame) => frame.header[1] === SAVE_PROFILE_REQUEST),
  125. update: frames.find(
  126. (frame) => frame.header[1] === updateId && [201, 202, 203].includes(frame.header[0]),
  127. ),
  128. cancellation: frames.find((frame) => frame.header[1] === DISCONNECT_REQUEST),
  129. states: frames
  130. .filter((frame) => frame.header[0] === 204 && frame.body?.state)
  131. .map((frame) => frame.body.state),
  132. };
  133. }
  134. export async function restoreUpdateDisconnectProbe(): Promise<void> {
  135. await browser.execute(() => window.__updateDisconnectProbe?.restore());
  136. }