codingPlanEmbeddedWebview.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import {
  2. BIGMODEL_PROVIDER_ID,
  3. BUILTIN_MODEL_PROVIDER_IDS,
  4. DEFAULT_ZCODE_ENDPOINT_ORIGIN,
  5. isTrustedCodingPlanWebviewOrigin,
  6. isZaiCodingPlanProviderId,
  7. normalizeZCodeEndpointOrigin,
  8. type ZCodeEnv,
  9. ZCODE_ENV,
  10. ZAI_PROVIDER_ID,
  11. } from "@zcode/shared";
  12. import type { CodingPlanWebviewLocale } from "@zcode/shared";
  13. import type { CodingPlanFunnelContext } from "@/lib/codingPlanFunnelTelemetry.js";
  14. import type { CodingPlanProviderId } from "@/settings/model-provider-section/constants.js";
  15. export type CodingPlanWebsiteProvider = "zai" | "bigmodel";
  16. export type CodingPlanPurchaseAudience = "personal" | "team";
  17. export interface CodingPlanEmbeddedCredentials {
  18. zaiAccessToken?: string | null;
  19. zcodeJwtToken?: string | null;
  20. bigmodelAccessToken?: string | null;
  21. }
  22. export interface CodingPlanEmbeddedReportContext {
  23. purchase_funnel_id?: string;
  24. purchase_entry_reporter?: "app";
  25. upgrade_source?: string;
  26. event_region?: string;
  27. event_text?: string;
  28. entry_plan_status?: string;
  29. entry_plan_level?: string;
  30. entry_plan_list?: string;
  31. purchase_audience?: string;
  32. provider_family?: string;
  33. channel?: string;
  34. device_mid?: string;
  35. user_id?: string;
  36. app_version?: string;
  37. }
  38. export type CodingPlanEmbeddedTheme = "zai-light" | "zai-dark";
  39. /**
  40. * App locale(zh-CN / en-US)→ 官网 URL lang 段(cn / en)。
  41. * 用于 webview URL 的 ?lang= hint,让官网首屏就有正确语言,避免注入前的英文闪烁。
  42. */
  43. export function codingPlanLocaleToWebsiteLang(
  44. locale: CodingPlanWebviewLocale | null | undefined,
  45. ): "cn" | "en" {
  46. return locale === "zh-CN" ? "cn" : "en";
  47. }
  48. export interface ResolveCodingPlanEmbeddedOriginOptions {
  49. dev: boolean;
  50. endpointOrigin: string;
  51. e2eStoreBridgeEnabled?: boolean;
  52. overrideOrigin?: string | null;
  53. zcodeEnv?: ZCodeEnv;
  54. }
  55. export const CODING_PLAN_WEBVIEW_OVERRIDE_ENV_KEY = "VITE_CODING_PLAN_WEBVIEW_ORIGIN";
  56. const CODING_PLAN_WEBVIEW_CREDENTIAL_LOCAL_STORAGE_KEYS = [
  57. "oauth:zai:access_token",
  58. "zcodejwttoken",
  59. "oauth:bigmodel:access_token",
  60. ] as const;
  61. const CODING_PLAN_REPORT_CONTEXT_STORAGE_KEY = "zcode:coding-plan:report-context";
  62. export function resolveCodingPlanWebsiteProvider(
  63. providerId: CodingPlanProviderId,
  64. ): CodingPlanWebsiteProvider {
  65. return isZaiCodingPlanProviderId(providerId) ||
  66. providerId === BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan
  67. ? "zai"
  68. : "bigmodel";
  69. }
  70. export function resolveCodingPlanEmbeddedOrigin({
  71. dev,
  72. endpointOrigin,
  73. e2eStoreBridgeEnabled,
  74. overrideOrigin,
  75. zcodeEnv = ZCODE_ENV,
  76. }: ResolveCodingPlanEmbeddedOriginOptions): string {
  77. const normalizedOverride = overrideOrigin?.trim();
  78. if (
  79. normalizedOverride &&
  80. isTrustedCodingPlanWebviewOrigin(normalizedOverride, { e2eStoreBridgeEnabled })
  81. ) {
  82. return normalizeZCodeEndpointOrigin(normalizedOverride);
  83. }
  84. // Bug 原因:本地开发默认注入 ZCODE_ENV=production,不能仅凭 Vite DEV 就打开未启动的官网本地页。
  85. if (dev && zcodeEnv === "test") {
  86. return "http://localhost:3000";
  87. }
  88. const normalizedEndpointOrigin = normalizeZCodeEndpointOrigin(endpointOrigin);
  89. return isTrustedCodingPlanWebviewOrigin(normalizedEndpointOrigin, { e2eStoreBridgeEnabled })
  90. ? normalizedEndpointOrigin
  91. : DEFAULT_ZCODE_ENDPOINT_ORIGIN;
  92. }
  93. export function buildCodingPlanEmbeddedWebviewUrl({
  94. origin,
  95. provider,
  96. locale,
  97. theme,
  98. audience,
  99. teamPlanKey,
  100. }: {
  101. origin: string;
  102. provider: CodingPlanWebsiteProvider;
  103. // 传入 App 当前 locale,作为官网首屏语言 hint(?lang=cn|en),避免注入前的英文闪烁。
  104. locale?: CodingPlanWebviewLocale | null;
  105. // 官网 SSR 默认 dark;首次打开 WebView 时 localStorage 还没有主题,
  106. // 必须把 App 当前主题同步放进 URL,让官网 head 脚本在首帧 paint 前读到。
  107. theme?: CodingPlanEmbeddedTheme | null;
  108. audience?: CodingPlanPurchaseAudience;
  109. teamPlanKey?: string | null;
  110. }): string {
  111. const url = new URL("/coding-plan", normalizeZCodeEndpointOrigin(origin));
  112. url.searchParams.set("provider", provider);
  113. url.searchParams.set("embedded", "app");
  114. url.searchParams.set("lang", codingPlanLocaleToWebsiteLang(locale));
  115. if (audience) {
  116. url.searchParams.set("audience", audience);
  117. }
  118. if (teamPlanKey?.trim()) {
  119. url.searchParams.set("teamPlanKey", teamPlanKey.trim());
  120. }
  121. if (theme) {
  122. url.searchParams.set("theme", theme);
  123. }
  124. return url.toString();
  125. }
  126. export function isTrustedCodingPlanEmbeddedWebviewUrl(
  127. value: string | null | undefined,
  128. options?: {
  129. e2eStoreBridgeEnabled?: boolean;
  130. },
  131. ): boolean {
  132. if (!value) return false;
  133. try {
  134. const url = new URL(value);
  135. if (url.protocol !== "http:" && url.protocol !== "https:") return false;
  136. if (
  137. !isTrustedCodingPlanWebviewOrigin(url.origin, {
  138. e2eStoreBridgeEnabled: options?.e2eStoreBridgeEnabled,
  139. })
  140. ) {
  141. return false;
  142. }
  143. if (!url.pathname.includes("coding-plan")) return false;
  144. if (url.searchParams.get("embedded") === "app") return true;
  145. // PayPal 成功后先回到 /coding-plan/payment/callback,embedded=app
  146. // 在 returnTo 里。该页仍需要 App 注入 OAuth token 完成 subscribe,不能被当作外站清理凭据。
  147. if (!url.pathname.endsWith("/coding-plan/payment/callback")) return false;
  148. const returnTo = url.searchParams.get("returnTo");
  149. if (!returnTo) return false;
  150. const target = new URL(returnTo, url.origin);
  151. return (
  152. target.origin === url.origin &&
  153. target.pathname.includes("coding-plan") &&
  154. target.searchParams.get("embedded") === "app" &&
  155. !target.pathname.endsWith("/coding-plan/payment/callback")
  156. );
  157. } catch {
  158. return false;
  159. }
  160. }
  161. export function createCodingPlanAuthInjectionScript({
  162. provider,
  163. credentials,
  164. theme,
  165. locale,
  166. reportContext,
  167. }: {
  168. provider: CodingPlanWebsiteProvider;
  169. credentials: CodingPlanEmbeddedCredentials;
  170. theme: CodingPlanEmbeddedTheme;
  171. // App 当前 locale,写入 window.__zcodeLang__ 供 zcodeBridge.getLang() 读取,
  172. // 并附带在 auth-ready 事件 detail 里让官网一次性同步初始语言。
  173. locale: CodingPlanWebviewLocale | null;
  174. reportContext?: CodingPlanEmbeddedReportContext | null;
  175. }): string {
  176. const values: Record<string, string | null> =
  177. provider === "zai"
  178. ? {
  179. "oauth:zai:access_token": credentials.zaiAccessToken?.trim() || null,
  180. zcodejwttoken: credentials.zcodeJwtToken?.trim() || null,
  181. "oauth:bigmodel:access_token": null,
  182. }
  183. : {
  184. "oauth:zai:access_token": null,
  185. // zcodejwttoken 是 zcode-plan 域通用凭证(BigModel OAuth callback 同样落盘),
  186. // 官网用它查 billing/balance 判定 Start Plan 是否使用中;BigModel 分支缺失注入
  187. // 会导致官网 Start Plan 卡因查不到权益而误显示「已过期」。业务接口仍走
  188. // oauth:bigmodel:access_token,互不污染。
  189. zcodejwttoken: credentials.zcodeJwtToken?.trim() || null,
  190. "oauth:bigmodel:access_token": credentials.bigmodelAccessToken?.trim() || null,
  191. };
  192. const storageUpdates = Object.entries(values)
  193. .map(([key, value]) =>
  194. value
  195. ? `localStorage.setItem(${JSON.stringify(key)}, ${JSON.stringify(value)});`
  196. : `localStorage.removeItem(${JSON.stringify(key)});`,
  197. )
  198. .join("\n ");
  199. const resolvedLocale: CodingPlanWebviewLocale = locale === "zh-CN" ? "zh-CN" : "en-US";
  200. const normalizedReportContext = normalizeCodingPlanEmbeddedReportContext(reportContext);
  201. return `(() => {
  202. ${storageUpdates}
  203. const zcodeTheme = ${JSON.stringify(theme)};
  204. document.documentElement.classList.toggle("dark", zcodeTheme === "zai-dark");
  205. document.documentElement.classList.toggle("theme-zai-light", zcodeTheme === "zai-light");
  206. document.documentElement.classList.toggle("theme-zai-dark", zcodeTheme === "zai-dark");
  207. localStorage.setItem("zcode-theme", zcodeTheme);
  208. localStorage.setItem("zcode:coding-plan:embedded", "app");
  209. // 写入当前 App locale,供官网 zcodeBridge.getLang() 读取。
  210. // 注意:这是注入 webview 执行的原始 JS,不能用 TS 语法(如 as any)。
  211. window.__zcodeLang__ = ${JSON.stringify(resolvedLocale)};
  212. const zcodeReportContext = ${JSON.stringify(normalizedReportContext)};
  213. window.__zcodeReportContext__ = zcodeReportContext;
  214. localStorage.setItem(${JSON.stringify(CODING_PLAN_REPORT_CONTEXT_STORAGE_KEY)}, JSON.stringify(zcodeReportContext));
  215. window.dispatchEvent(new CustomEvent("zcode-coding-plan-auth-ready", {
  216. detail: { ...${JSON.stringify({ provider, locale: resolvedLocale })}, reportContext: zcodeReportContext },
  217. }));
  218. })()`;
  219. }
  220. export function buildCodingPlanEmbeddedReportContext({
  221. funnelContext,
  222. deviceMid,
  223. userId,
  224. appVersion,
  225. }: {
  226. funnelContext?: CodingPlanFunnelContext | null;
  227. deviceMid?: string | null;
  228. userId?: string | null;
  229. appVersion?: string | null;
  230. }): CodingPlanEmbeddedReportContext {
  231. return normalizeCodingPlanEmbeddedReportContext({
  232. purchase_funnel_id: funnelContext?.purchaseFunnelId,
  233. // 缺少归属标记会让兼容官网重复上报入口;无漏斗时不能声明 App 已接管。
  234. purchase_entry_reporter: funnelContext ? "app" : undefined,
  235. upgrade_source: funnelContext?.upgradeSource,
  236. event_region: funnelContext?.eventRegion,
  237. event_text: funnelContext?.eventText,
  238. entry_plan_status: funnelContext?.entryPlanStatus,
  239. entry_plan_level: funnelContext?.entryPlanLevel,
  240. entry_plan_list: funnelContext?.entryPlanList,
  241. purchase_audience: funnelContext?.purchaseAudience,
  242. provider_family: funnelContext?.providerFamily,
  243. channel: funnelContext?.channel,
  244. device_mid: deviceMid ?? undefined,
  245. user_id: userId ?? undefined,
  246. app_version: appVersion ?? undefined,
  247. });
  248. }
  249. function normalizeCodingPlanEmbeddedReportContext(
  250. context: CodingPlanEmbeddedReportContext | null | undefined,
  251. ): CodingPlanEmbeddedReportContext {
  252. if (!context) return {};
  253. return Object.fromEntries(
  254. Object.entries(context).flatMap(([key, value]) => {
  255. if (typeof value !== "string") return [];
  256. const normalized = value.trim();
  257. return normalized ? [[key, normalized]] : [];
  258. }),
  259. ) as CodingPlanEmbeddedReportContext;
  260. }
  261. export function createCodingPlanCredentialClearScript(): string {
  262. const keys = [...CODING_PLAN_WEBVIEW_CREDENTIAL_LOCAL_STORAGE_KEYS];
  263. return `(() => {
  264. for (const key of ${JSON.stringify(keys)}) {
  265. localStorage.removeItem(key);
  266. }
  267. localStorage.removeItem(${JSON.stringify(CODING_PLAN_REPORT_CONTEXT_STORAGE_KEY)});
  268. delete window.__zcodeReportContext__;
  269. })()`;
  270. }
  271. export function createCodingPlanScrollbarHideScript(): string {
  272. return `(() => {
  273. const styleId = "zcode-coding-plan-hide-scrollbar";
  274. if (document.getElementById(styleId)) return;
  275. const style = document.createElement("style");
  276. style.id = styleId;
  277. style.textContent = \`
  278. html,
  279. body,
  280. * {
  281. scrollbar-width: none !important;
  282. }
  283. html::-webkit-scrollbar,
  284. body::-webkit-scrollbar,
  285. *::-webkit-scrollbar {
  286. display: none !important;
  287. width: 0 !important;
  288. height: 0 !important;
  289. }
  290. \`;
  291. document.head.appendChild(style);
  292. })()`;
  293. }
  294. /**
  295. * 生成「更新 webview 当前 locale」的注入脚本。
  296. * App locale 运行时变化时对 webview executeJavaScript 此脚本:
  297. * 重写 window.__zcodeLang__ 并派发 zcode-coding-plan-lang-change 事件,
  298. * 官网侧(zcodeBridge.onLangChange 或 window 监听)据此无感切换语言。
  299. */
  300. export function createCodingPlanLangInjectionScript(locale: CodingPlanWebviewLocale): string {
  301. const resolvedLocale: CodingPlanWebviewLocale = locale === "zh-CN" ? "zh-CN" : "en-US";
  302. return `(() => {
  303. // 注意:注入 webview 执行的原始 JS,不能用 TS 语法(如 as any)。
  304. window.__zcodeLang__ = ${JSON.stringify(resolvedLocale)};
  305. window.dispatchEvent(new CustomEvent("zcode-coding-plan-lang-change", {
  306. detail: ${JSON.stringify({ locale: resolvedLocale })},
  307. }));
  308. })()`;
  309. }
  310. export function getCodingPlanCredentialKeys(provider: CodingPlanWebsiteProvider): string[] {
  311. // zcodejwttoken 对两个 provider 都加载:它是 zcode-plan 域通用凭证,
  312. // BigModel OAuth callback 同样落盘(见 resolveBigModelStartPlanZcodeJwt)。
  313. return provider === "zai"
  314. ? [`oauth:${ZAI_PROVIDER_ID}:access_token`, "zcodejwttoken"]
  315. : [`oauth:${BIGMODEL_PROVIDER_ID}:access_token`, "zcodejwttoken"];
  316. }