oauth-provisioning.test.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
  2. import { mkdtemp, rm } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join, resolve } from "node:path";
  5. import { createRequire } from "node:module";
  6. import { createInterface } from "node:readline";
  7. import { z } from "zod";
  8. import { providerProvisioningEnvelopeSchema } from "@zcode/shared";
  9. const KEYS = [
  10. "oauth:active_provider",
  11. "oauth:session_revision",
  12. "oauth:zai:access_token",
  13. "oauth:zai:refresh_token",
  14. "oauth:zai:user_info",
  15. "oauth:zai_cn:access_token",
  16. "oauth:zai_cn:refresh_token",
  17. "oauth:zai_cn:user_info",
  18. "oauth:bigmodel:access_token",
  19. "oauth:bigmodel:refresh_token",
  20. "oauth:bigmodel:user_info",
  21. "oauth:linked_bigmodel",
  22. "zcodejwttoken",
  23. ];
  24. const empty = Object.fromEntries(KEYS.map((key) => [key, null]));
  25. const primary = {
  26. ...empty,
  27. "oauth:active_provider": "zai_cn",
  28. "oauth:session_revision": "e2e-source-revision",
  29. "oauth:zai_cn:access_token": "e2e-cn-oauth",
  30. "oauth:zai_cn:user_info": JSON.stringify({ user_id: "e2e-primary-user", name: "CN" }),
  31. "oauth:linked_bigmodel": JSON.stringify({
  32. userId: "e2e-primary-user",
  33. customerId: "e2e-linked-customer",
  34. accessToken: "e2e-linked-business",
  35. }),
  36. zcodejwttoken: "e2e-primary-jwt",
  37. };
  38. class Runtime {
  39. child: ChildProcessWithoutNullStreams;
  40. pending = new Map<number, { resolve: (value: any) => void; reject: (error: Error) => void }>();
  41. sequence = 0;
  42. constructor(home: string) {
  43. const require = createRequire(import.meta.url);
  44. this.child = spawn(
  45. process.execPath,
  46. [require.resolve("tsx/cli"), resolve("test/e2e/fixtures/oauth-provisioning/runtime.ts")],
  47. {
  48. env: { ...process.env, HOME: home, ZCODE_DATA_BASE_DIR: home, ZCODE_ENV: "test" },
  49. stdio: ["pipe", "pipe", "pipe"],
  50. },
  51. );
  52. createInterface({ input: this.child.stdout }).on("line", (line) => {
  53. if (!line.startsWith("E2E_PROVISIONING ")) return;
  54. const message = JSON.parse(line.slice("E2E_PROVISIONING ".length));
  55. const pending = this.pending.get(message.id);
  56. if (!pending) return;
  57. this.pending.delete(message.id);
  58. if (message.error) pending.reject(new Error(message.error));
  59. else pending.resolve(message.value);
  60. });
  61. this.child.stderr.on("data", () => {});
  62. this.child.on("exit", (code) => {
  63. for (const pending of this.pending.values())
  64. pending.reject(new Error(`fixture exited: ${code}`));
  65. this.pending.clear();
  66. });
  67. }
  68. call(command: string, payload: Record<string, unknown> = {}): Promise<any> {
  69. const id = ++this.sequence;
  70. return new Promise((resolve, reject) => {
  71. this.pending.set(id, { resolve, reject });
  72. this.child.stdin.write(`${JSON.stringify({ id, command, ...payload })}\n`);
  73. });
  74. }
  75. async close() {
  76. if (this.child.exitCode === null) await this.call("close");
  77. }
  78. }
  79. describe("OAuth provisioning runtime", () => {
  80. let root: string;
  81. let source: Runtime;
  82. let target: Runtime;
  83. before(async function () {
  84. this.timeout(90_000);
  85. root = await mkdtemp(join(tmpdir(), "oauth-provisioning-e2e-"));
  86. source = new Runtime(join(root, "source"));
  87. target = new Runtime(join(root, "target"));
  88. await source.call("seed", { values: primary });
  89. await target.call("seed", { values: { ...empty, "manual:e2e:key": "e2e-manual" } });
  90. });
  91. after(async function () {
  92. this.timeout(30_000);
  93. await Promise.all([source?.close(), target?.close()]);
  94. if (root) await rm(root, { recursive: true, force: true });
  95. });
  96. it("v3 整组同步国内主会话与关联,旧 schema 写入前拒绝", async function () {
  97. this.timeout(90_000);
  98. const envelope = await source.call("source", { syncId: "e2e-v3" });
  99. expect(envelope.schemaVersion).toBe(3);
  100. const oldSchema = z.object({ schemaVersion: z.union([z.literal(1), z.literal(2)]) });
  101. expect(oldSchema.safeParse(envelope).success).toBe(false);
  102. expect(providerProvisioningEnvelopeSchema.safeParse(envelope).success).toBe(true);
  103. const applied = await target.call("apply", { envelope });
  104. expect(applied.status).toBe("applied");
  105. expect(applied.mutations).toHaveLength(1);
  106. expect(applied.mutations[0].operation).toBe("batch");
  107. expect(applied.mutations[0].keys.sort()).toEqual([...KEYS].sort());
  108. const first = await target.call("read", { keys: KEYS });
  109. expect({ ...first, "oauth:session_revision": null }).toEqual({
  110. ...primary,
  111. "oauth:session_revision": null,
  112. });
  113. expect(first["oauth:session_revision"]).not.toBe(primary["oauth:session_revision"]);
  114. const repeated = await target.call("apply", { envelope });
  115. expect(repeated.status).toBe("already-applied");
  116. expect(repeated.mutations).toHaveLength(0);
  117. expect(await target.call("read", { keys: KEYS })).toEqual(first);
  118. await target.call("apply", { envelope: { ...envelope, syncId: "e2e-v3-new-delivery" } });
  119. expect((await target.call("read", { keys: KEYS }))["oauth:session_revision"]).not.toBe(
  120. first["oauth:session_revision"],
  121. );
  122. const availability = await target.call("availability");
  123. expect(availability.loginProvider).toBe("zai_cn");
  124. expect(availability.families).toContain("bigmodel");
  125. });
  126. it("写入后失败整组回滚,并保留并发新登录", async function () {
  127. this.timeout(90_000);
  128. await target.call("seed", {
  129. values: {
  130. ...primary,
  131. "oauth:session_revision": "e2e-before",
  132. zcodejwttoken: "e2e-before-primary",
  133. },
  134. });
  135. const before = await target.call("read", { keys: KEYS });
  136. const envelope = await source.call("source", { syncId: "e2e-rollback" });
  137. await target.call("hold-profile");
  138. await target.call("fault", { mode: "after-write" });
  139. expect((await target.call("apply", { envelope })).status).toBe("failed");
  140. const restored = await target.call("read", { keys: KEYS });
  141. expect({ ...restored, "oauth:session_revision": null }).toEqual({
  142. ...before,
  143. "oauth:session_revision": null,
  144. });
  145. expect(await target.call("finish-profile")).toBe(false);
  146. expect(restored["oauth:session_revision"]).not.toBe(before["oauth:session_revision"]);
  147. await target.call("fault", { mode: "concurrent-login" });
  148. const conflict = await target.call("apply", {
  149. envelope: { ...envelope, syncId: "e2e-conflict" },
  150. });
  151. expect(conflict.status).toBe("rollback_failed");
  152. expect(await target.call("read", { keys: KEYS })).toEqual({
  153. ...primary,
  154. "oauth:session_revision": "e2e-concurrent-revision",
  155. zcodejwttoken: "e2e-concurrent-primary",
  156. });
  157. });
  158. it("旧 v2 不继承目标关联和 revision,手工 Key 保留", async function () {
  159. this.timeout(90_000);
  160. const sourceEnvelope = await source.call("source", { syncId: "e2e-legacy" });
  161. const credentials = [
  162. { scope: "oauth-session", key: "oauth:active_provider", value: "bigmodel" },
  163. { scope: "oauth-session", key: "oauth:bigmodel:access_token", value: "e2e-legacy-business" },
  164. {
  165. scope: "oauth-session",
  166. key: "oauth:bigmodel:user_info",
  167. value: JSON.stringify({ id: "e2e-legacy", username: "legacy" }),
  168. },
  169. { scope: "oauth-session", key: "zcodejwttoken", value: "e2e-legacy-primary" },
  170. ];
  171. const result = await target.call("apply", {
  172. envelope: { ...sourceEnvelope, schemaVersion: 2, credentials },
  173. });
  174. expect(result.status).toBe("applied");
  175. const saved = await target.call("read", { keys: [...KEYS, "manual:e2e:key"] });
  176. expect(saved["oauth:linked_bigmodel"]).toBeNull();
  177. expect(saved["oauth:zai_cn:access_token"]).toBeNull();
  178. expect(saved["oauth:session_revision"]).toBeTruthy();
  179. expect(saved["oauth:session_revision"]).not.toBe("e2e-concurrent-revision");
  180. expect(saved["manual:e2e:key"]).toBe("e2e-manual");
  181. });
  182. it("拒绝旧版本夹带新字段和重复字段,保持目标零写入", async function () {
  183. this.timeout(90_000);
  184. const envelope = await source.call("source", { syncId: "e2e-invalid" });
  185. const before = await target.call("read", { keys: KEYS });
  186. await expect(
  187. target.call("apply", { envelope: { ...envelope, schemaVersion: 2 } }),
  188. ).rejects.toThrow("不允许同步");
  189. await expect(
  190. target.call("apply", {
  191. envelope: {
  192. ...envelope,
  193. syncId: "e2e-duplicate",
  194. credentials: [...envelope.credentials, envelope.credentials[0]],
  195. },
  196. }),
  197. ).rejects.toThrow("重复");
  198. expect(await target.call("read", { keys: KEYS })).toEqual(before);
  199. });
  200. it("退出同步清除整组账号材料,保留手工 Key", async function () {
  201. this.timeout(90_000);
  202. await source.call("seed", { values: empty });
  203. const envelope = await source.call("source", { syncId: "e2e-logout" });
  204. expect((await target.call("apply", { envelope })).status).toBe("applied");
  205. const saved = await target.call("read", { keys: KEYS });
  206. expect({ ...saved, "oauth:session_revision": null }).toEqual(empty);
  207. expect(saved["oauth:session_revision"]).toBeTruthy();
  208. expect(await target.call("availability")).toMatchObject({
  209. loginProvider: null,
  210. userId: null,
  211. families: [],
  212. });
  213. expect(await target.call("read", { keys: ["manual:e2e:key"] })).toEqual({
  214. "manual:e2e:key": "e2e-manual",
  215. });
  216. });
  217. });