codingPlanEmbeddedWebview.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. // @vitest-environment jsdom
  2. import { createElement } from "react";
  3. import { cleanup, render } from "@testing-library/react";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import {
  6. BUILTIN_MODEL_PROVIDER_IDS,
  7. DEFAULT_ZCODE_ENDPOINT_ORIGIN,
  8. isTrustedCodingPlanWebviewOrigin,
  9. } from "@zcode/shared";
  10. import {
  11. buildCodingPlanEmbeddedWebviewUrl,
  12. buildCodingPlanEmbeddedReportContext,
  13. createCodingPlanAuthInjectionScript,
  14. createCodingPlanCredentialClearScript,
  15. getCodingPlanCredentialKeys,
  16. isTrustedCodingPlanEmbeddedWebviewUrl,
  17. resolveCodingPlanEmbeddedOrigin,
  18. resolveCodingPlanWebsiteProvider,
  19. } from "@/settings/model-provider-section/codingPlanEmbeddedWebview.js";
  20. import { CodingPlanEmbeddedWebviewDialog } from "@/settings/CodingPlanEmbeddedWebviewDialog.js";
  21. const h = vi.hoisted(() => ({
  22. theme: "zai-light",
  23. }));
  24. vi.mock("@/hooks/usePlatform.js", () => ({
  25. usePlatform: () => ({
  26. activateOrSetWorkspace: vi.fn(),
  27. connectRemote: vi.fn(),
  28. getDeviceId: vi.fn(() => Promise.resolve("device-mid-test")),
  29. notifyRendererReady: vi.fn(),
  30. onOAuthCallback: vi.fn(),
  31. openExternal: vi.fn(),
  32. registerOAuthState: vi.fn(),
  33. selectDirectory: vi.fn(),
  34. }),
  35. }));
  36. vi.mock("@/i18n/IntlProvider.js", () => ({
  37. useZCodeIntl: () => ({
  38. intl: {
  39. formatMessage: ({ id }: { id: string }) => id,
  40. },
  41. locale: "en-US",
  42. }),
  43. }));
  44. vi.mock("@/store/StoreProvider.js", () => ({
  45. useZCodeStoreWithDefault: (
  46. selector: (state: { theme: string; user: { id: string } | null }) => unknown,
  47. ) =>
  48. selector({
  49. theme: h.theme,
  50. user: { id: "user-test" },
  51. }),
  52. }));
  53. afterEach(() => {
  54. cleanup();
  55. h.theme = "zai-light";
  56. });
  57. describe("coding plan embedded webview bridge", () => {
  58. it("builds the website URL with app embedded marker and no telemetry query", () => {
  59. const url = new URL(
  60. buildCodingPlanEmbeddedWebviewUrl({
  61. origin: "https://zcode.z.ai",
  62. provider: "bigmodel",
  63. audience: "team",
  64. teamPlanKey: "team-plan-a",
  65. theme: "zai-light",
  66. }),
  67. );
  68. expect(url.origin).toBe("https://zcode.z.ai");
  69. expect(url.pathname).toBe("/coding-plan");
  70. expect(Object.fromEntries(url.searchParams)).toMatchObject({
  71. provider: "bigmodel",
  72. embedded: "app",
  73. lang: "en",
  74. theme: "zai-light",
  75. audience: "team",
  76. teamPlanKey: "team-plan-a",
  77. });
  78. expect(url.searchParams.has("purchase_funnel_id")).toBe(false);
  79. expect(url.searchParams.has("device_mid")).toBe(false);
  80. expect(url.searchParams.has("user_id")).toBe(false);
  81. expect(url.searchParams.has("app_version")).toBe(false);
  82. });
  83. it.each([
  84. [BUILTIN_MODEL_PROVIDER_IDS.zaiTeamCodingPlan, "zai"],
  85. [BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan, "bigmodel"],
  86. ] as const)("maps Team Provider %s to website family %s", (providerId, family) => {
  87. expect(resolveCodingPlanWebsiteProvider(providerId)).toBe(family);
  88. });
  89. it("builds the report context that website telemetry reads from the bridge", () => {
  90. expect(
  91. buildCodingPlanEmbeddedReportContext({
  92. deviceMid: "device-mid-test",
  93. userId: "user-1",
  94. appVersion: "9.8.7",
  95. funnelContext: {
  96. purchaseFunnelId: "funnel-app",
  97. upgradeSource: "session_quota_alert",
  98. eventRegion: "app.session",
  99. eventText: "upgrade",
  100. entryPlanStatus: "start_plan",
  101. entryPlanLevel: "start",
  102. entryPlanList: "start_plan__weekend-plan",
  103. purchaseAudience: "team",
  104. providerFamily: "bigmodel",
  105. channel: "MaaS",
  106. },
  107. }),
  108. ).toMatchObject({
  109. purchase_funnel_id: "funnel-app",
  110. purchase_entry_reporter: "app",
  111. upgrade_source: "session_quota_alert",
  112. event_region: "app.session",
  113. event_text: "upgrade",
  114. entry_plan_status: "start_plan",
  115. entry_plan_level: "start",
  116. purchase_audience: "team",
  117. provider_family: "bigmodel",
  118. channel: "MaaS",
  119. device_mid: "device-mid-test",
  120. user_id: "user-1",
  121. app_version: "9.8.7",
  122. });
  123. });
  124. it("does not claim app entry reporting without a funnel", () => {
  125. expect(buildCodingPlanEmbeddedReportContext({})).not.toHaveProperty("purchase_entry_reporter");
  126. });
  127. it("preserves entry ownership in window, storage and ready events on reinjection", () => {
  128. const ready = vi.fn();
  129. window.addEventListener("zcode-coding-plan-auth-ready", ready);
  130. try {
  131. const reportContext = {
  132. purchase_funnel_id: "funnel-app",
  133. purchase_entry_reporter: "app" as const,
  134. };
  135. const script = createCodingPlanAuthInjectionScript({
  136. provider: "bigmodel",
  137. credentials: {},
  138. reportContext,
  139. });
  140. window.eval(script);
  141. window.eval(script);
  142. expect(
  143. (window as unknown as { __zcodeReportContext__: unknown }).__zcodeReportContext__,
  144. ).toEqual(reportContext);
  145. expect(JSON.parse(localStorage.getItem("zcode:coding-plan:report-context") || "{}")).toEqual(
  146. reportContext,
  147. );
  148. expect(ready).toHaveBeenCalledTimes(2);
  149. for (const [event] of ready.mock.calls) {
  150. expect((event as CustomEvent).detail.reportContext).toEqual(reportContext);
  151. }
  152. } finally {
  153. window.removeEventListener("zcode-coding-plan-auth-ready", ready);
  154. window.eval(createCodingPlanCredentialClearScript());
  155. }
  156. });
  157. it("uses localhost in local development and endpoint origin otherwise", () => {
  158. expect(
  159. resolveCodingPlanEmbeddedOrigin({
  160. dev: true,
  161. endpointOrigin: "https://zcode.z.ai",
  162. zcodeEnv: "test",
  163. }),
  164. ).toBe("http://localhost:3000");
  165. expect(
  166. resolveCodingPlanEmbeddedOrigin({
  167. dev: true,
  168. endpointOrigin: "https://zcode.z.ai",
  169. zcodeEnv: "production",
  170. }),
  171. ).toBe("https://zcode.z.ai");
  172. expect(
  173. resolveCodingPlanEmbeddedOrigin({
  174. dev: false,
  175. endpointOrigin: "https://zcode.z.ai",
  176. zcodeEnv: "production",
  177. }),
  178. ).toBe("https://zcode.z.ai");
  179. expect(
  180. resolveCodingPlanEmbeddedOrigin({
  181. dev: true,
  182. endpointOrigin: "https://zcode.z.ai",
  183. zcodeEnv: "test",
  184. overrideOrigin: "https://example.test/path",
  185. }),
  186. ).toBe("http://localhost:3000");
  187. });
  188. it("only trusts official coding plan origins unless the E2E bridge enables loopback mocks", () => {
  189. expect(isTrustedCodingPlanWebviewOrigin("https://zcode.z.ai")).toBe(true);
  190. expect(isTrustedCodingPlanWebviewOrigin("https://zcode.z.ai")).toBe(true);
  191. expect(isTrustedCodingPlanWebviewOrigin("http://localhost:3000")).toBe(true);
  192. expect(isTrustedCodingPlanWebviewOrigin("https://evil.example")).toBe(false);
  193. expect(isTrustedCodingPlanWebviewOrigin("http://127.0.0.1:4555")).toBe(false);
  194. expect(
  195. isTrustedCodingPlanWebviewOrigin("http://127.0.0.1:4555", {
  196. e2eStoreBridgeEnabled: true,
  197. }),
  198. ).toBe(true);
  199. });
  200. it("trusts PayPal callback pages that return to the embedded Coding Plan page", () => {
  201. const returnTo = encodeURIComponent(
  202. "/coding-plan?provider=zai&embedded=app&lang=cn&theme=zai-dark",
  203. );
  204. expect(
  205. isTrustedCodingPlanEmbeddedWebviewUrl(
  206. `http://localhost:3000/coding-plan/payment/callback?channel=paypal&status=return&returnTo=${returnTo}`,
  207. ),
  208. ).toBe(true);
  209. expect(
  210. isTrustedCodingPlanEmbeddedWebviewUrl(
  211. "http://localhost:3000/coding-plan/payment/callback?channel=paypal&status=return",
  212. ),
  213. ).toBe(false);
  214. expect(
  215. isTrustedCodingPlanEmbeddedWebviewUrl(
  216. "http://localhost:3000/coding-plan/payment/callback?returnTo=%2Fcoding-plan%3Fprovider%3Dzai",
  217. ),
  218. ).toBe(false);
  219. });
  220. it("falls back to the official website when a configured webview override is not trusted", () => {
  221. expect(
  222. resolveCodingPlanEmbeddedOrigin({
  223. dev: false,
  224. endpointOrigin: "https://untrusted.example",
  225. overrideOrigin: "https://evil.example/path",
  226. }),
  227. ).toBe(DEFAULT_ZCODE_ENDPOINT_ORIGIN);
  228. expect(
  229. resolveCodingPlanEmbeddedOrigin({
  230. dev: false,
  231. endpointOrigin: "https://untrusted.example",
  232. e2eStoreBridgeEnabled: true,
  233. overrideOrigin: "http://127.0.0.1:4555/path",
  234. }),
  235. ).toBe("http://127.0.0.1:4555");
  236. });
  237. it("maps coding plan provider ids to website provider query values", () => {
  238. expect(
  239. resolveCodingPlanWebsiteProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan),
  240. ).toBe("zai");
  241. expect(resolveCodingPlanWebsiteProvider(BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan)).toBe("zai");
  242. expect(
  243. resolveCodingPlanWebsiteProvider(BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan),
  244. ).toBe("bigmodel");
  245. });
  246. it("injects provider credentials into the webview localStorage and dispatches ready event", () => {
  247. const script = createCodingPlanAuthInjectionScript({
  248. provider: "zai",
  249. theme: "zai-dark",
  250. locale: "en-US",
  251. credentials: {
  252. zaiAccessToken: "zai-business-token",
  253. zcodeJwtToken: "zcode-jwt",
  254. },
  255. reportContext: {
  256. purchase_funnel_id: "funnel-app",
  257. device_mid: "device-mid-test",
  258. user_id: "user-1",
  259. app_version: "9.8.7",
  260. },
  261. });
  262. expect(script).toContain('localStorage.setItem("oauth:zai:access_token"');
  263. expect(script).toContain('localStorage.setItem("zcodejwttoken"');
  264. expect(script).toContain("zcode-coding-plan-auth-ready");
  265. expect(script).toContain('"provider":"zai"');
  266. expect(script).toContain("window.__zcodeReportContext__");
  267. expect(script).toContain("zcode:coding-plan:report-context");
  268. expect(script).toContain('"purchase_funnel_id":"funnel-app"');
  269. expect(script).toContain('"device_mid":"device-mid-test"');
  270. expect(script).toContain('"user_id":"user-1"');
  271. expect(script).toContain('"app_version":"9.8.7"');
  272. expect(script).toContain("reportContext: zcodeReportContext");
  273. expect(script).toContain('document.documentElement.classList.toggle("dark"');
  274. expect(script).toContain('localStorage.setItem("zcode-theme", zcodeTheme)');
  275. expect(script).toContain('localStorage.removeItem("oauth:bigmodel:access_token")');
  276. });
  277. it("injects the zcode JWT for the bigmodel provider so the website can query Start Plan balance", () => {
  278. // 修复原因:BigModel 分支此前显式清空 zcodejwttoken,官网内嵌页查不到
  279. // billing/balance(该接口只认 zcode JWT),Start Plan 卡被误判为「已过期」。
  280. const script = createCodingPlanAuthInjectionScript({
  281. provider: "bigmodel",
  282. theme: "zai-light",
  283. locale: "zh-CN",
  284. credentials: {
  285. bigmodelAccessToken: "bigmodel-business-token",
  286. zcodeJwtToken: "zcode-jwt",
  287. },
  288. });
  289. expect(script).toContain('localStorage.setItem("oauth:bigmodel:access_token"');
  290. expect(script).toContain('localStorage.setItem("zcodejwttoken"');
  291. expect(script).toContain('localStorage.removeItem("oauth:zai:access_token")');
  292. });
  293. it("loads the zcode JWT credential key for both website providers", () => {
  294. expect(getCodingPlanCredentialKeys("zai")).toEqual(["oauth:zai:access_token", "zcodejwttoken"]);
  295. expect(getCodingPlanCredentialKeys("bigmodel")).toEqual([
  296. "oauth:bigmodel:access_token",
  297. "zcodejwttoken",
  298. ]);
  299. });
  300. it("clears all provider credential keys from the persistent webview storage", () => {
  301. const script = createCodingPlanCredentialClearScript();
  302. expect(script).toContain("oauth:zai:access_token");
  303. expect(script).toContain("zcodejwttoken");
  304. expect(script).toContain("oauth:bigmodel:access_token");
  305. expect(script).toContain("localStorage.removeItem(key)");
  306. expect(script).toContain("zcode:coding-plan:report-context");
  307. expect(script).toContain("delete window.__zcodeReportContext__");
  308. });
  309. it("only injects credentials on the current trusted embedded coding plan page", () => {
  310. expect(
  311. isTrustedCodingPlanEmbeddedWebviewUrl(
  312. "https://zcode.z.ai/coding-plan?provider=zai&embedded=app",
  313. ),
  314. ).toBe(true);
  315. expect(
  316. isTrustedCodingPlanEmbeddedWebviewUrl(
  317. "https://zcode.z.ai/cn/coding-plan?provider=zai&embedded=app",
  318. ),
  319. ).toBe(true);
  320. expect(isTrustedCodingPlanEmbeddedWebviewUrl("https://pay.example/checkout?embedded=app")).toBe(
  321. false,
  322. );
  323. expect(
  324. isTrustedCodingPlanEmbeddedWebviewUrl("https://zcode.z.ai/coding-plan?provider=zai"),
  325. ).toBe(false);
  326. });
  327. it("keeps the initial webview src stable when the app theme changes while open", () => {
  328. const props = {
  329. credentialService: { load: vi.fn(() => Promise.resolve(null)) },
  330. onOpenChange: vi.fn(),
  331. open: true,
  332. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  333. };
  334. const view = render(createElement(CodingPlanEmbeddedWebviewDialog, props));
  335. const webview = view.getByTestId("coding-plan-embedded-webview");
  336. const initialSrc = webview.getAttribute("src");
  337. expect(initialSrc).toContain("theme=zai-light");
  338. h.theme = "zai-dark";
  339. view.rerender(createElement(CodingPlanEmbeddedWebviewDialog, props));
  340. // 修复原因:支付授权可能持续数分钟,系统主题自动切换不能让 src 变化并重载 PayPal 流程。
  341. expect(view.getByTestId("coding-plan-embedded-webview").getAttribute("src")).toBe(initialSrc);
  342. });
  343. });