webAuthService.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import { BrowserOAuthCredentialRepo } from "../src/auth/browserOAuthCredentialRepo.js";
  3. import { buildOAuthState, parseOAuthState } from "../src/auth/oauthStateCodec.js";
  4. import { createWebZaiOAuthConfig } from "../src/auth/webZaiOAuthConfig.js";
  5. import { WebAuthService } from "../src/auth/webAuthService.js";
  6. import { ZaiWebOAuthProvider } from "../src/auth/zaiWebOAuthProvider.js";
  7. class MemoryStorage implements Storage {
  8. private readonly values = new Map<string, string>();
  9. get length(): number {
  10. return this.values.size;
  11. }
  12. clear(): void {
  13. this.values.clear();
  14. }
  15. getItem(key: string): string | null {
  16. return this.values.get(key) ?? null;
  17. }
  18. key(index: number): string | null {
  19. return [...this.values.keys()][index] ?? null;
  20. }
  21. removeItem(key: string): void {
  22. this.values.delete(key);
  23. }
  24. setItem(key: string, value: string): void {
  25. this.values.set(key, value);
  26. }
  27. }
  28. function createProductionWebZaiOAuthConfig() {
  29. return createWebZaiOAuthConfig({
  30. VITE_ZCODE_BASE_URL: "https://zcode.z.ai",
  31. VITE_ZAI_OAUTH_CLIENT_ID: "client_P8X5CMWmlaRO9gyO-KSqtg",
  32. VITE_ZAI_OAUTH_ORIGIN: "https://chat.z.ai",
  33. });
  34. }
  35. function createService(options?: {
  36. currentHref?: string;
  37. currentOrigin?: string;
  38. allowDevReturnToRedirect?: boolean;
  39. }) {
  40. const localStorage = new MemoryStorage();
  41. const sessionStorage = new MemoryStorage();
  42. const assigned: string[] = [];
  43. const replaced: string[] = [];
  44. const config = {
  45. ...createProductionWebZaiOAuthConfig(),
  46. allowDevReturnToRedirect: options?.allowDevReturnToRedirect ?? false,
  47. };
  48. const service = new WebAuthService({
  49. config,
  50. provider: new ZaiWebOAuthProvider(config, () => 1_000),
  51. repo: new BrowserOAuthCredentialRepo({ localStorage, sessionStorage }),
  52. runtime: {
  53. assign: (url) => assigned.push(url),
  54. createNonce: () => "nonce-1",
  55. getCurrentHref: () =>
  56. options?.currentHref ??
  57. "http://192.168.1.8:5173/web-remote?remoteControlToken=token&relayOrigin=https%3A%2F%2Frelay.example",
  58. getCurrentOrigin: () => options?.currentOrigin ?? "http://192.168.1.8:5173",
  59. replace: (url) => replaced.push(url),
  60. },
  61. });
  62. return { assigned, localStorage, replaced, service, sessionStorage };
  63. }
  64. describe("WebAuthService", () => {
  65. afterEach(() => {
  66. vi.unstubAllEnvs();
  67. vi.unstubAllGlobals();
  68. });
  69. it("uses VITE_ZAI_OAUTH_ORIGIN and VITE_ZAI_OAUTH_CLIENT_ID to build test environment authorize URL", async () => {
  70. const testConfig = createWebZaiOAuthConfig({
  71. VITE_ZCODE_BASE_URL: "https://zcode.z.ai",
  72. VITE_ZAI_OAUTH_CLIENT_ID: "client_P8X5CMWmlaRO9gyO-KSqtg",
  73. VITE_ZAI_OAUTH_ORIGIN: "https://chat.z.ai/",
  74. });
  75. const localStorage = new MemoryStorage();
  76. const sessionStorage = new MemoryStorage();
  77. const assigned: string[] = [];
  78. const service = new WebAuthService({
  79. config: testConfig,
  80. provider: new ZaiWebOAuthProvider(testConfig, () => 1_000),
  81. repo: new BrowserOAuthCredentialRepo({ localStorage, sessionStorage }),
  82. runtime: {
  83. assign: (url) => assigned.push(url),
  84. createNonce: () => "nonce-1",
  85. getCurrentHref: () => "https://zcode.z.ai/web-remote",
  86. getCurrentOrigin: () => "https://zcode.z.ai",
  87. replace: () => undefined,
  88. },
  89. });
  90. service.startLogin();
  91. const authorizeUrl = new URL(assigned[0]!);
  92. expect(authorizeUrl.origin + authorizeUrl.pathname).toBe(
  93. "https://chat.z.ai/api/oauth/authorize",
  94. );
  95. expect(authorizeUrl.searchParams.get("redirect_uri")).toBe(
  96. "https://zcode.z.ai/web-remote/callback",
  97. );
  98. expect(authorizeUrl.searchParams.get("client_id")).toBe("client_P8X5CMWmlaRO9gyO-KSqtg");
  99. });
  100. it("starts ZAI login with nonce, dev return_to, and original app_return_to", () => {
  101. const { assigned, service, sessionStorage } = createService();
  102. service.startLogin({
  103. devReturnTo: "http://192.168.1.8:5173/web-remote/callback",
  104. });
  105. const authorizeUrl = new URL(assigned[0]!);
  106. const state = parseOAuthState(authorizeUrl.searchParams.get("state")!);
  107. expect(sessionStorage.getItem("oauth_pending_nonce")).toBe("nonce-1");
  108. expect(authorizeUrl.origin + authorizeUrl.pathname).toBe(
  109. "https://chat.z.ai/api/oauth/authorize",
  110. );
  111. expect(authorizeUrl.searchParams.get("redirect_uri")).toBe(
  112. "https://zcode.z.ai/web-remote/callback",
  113. );
  114. expect(state).toEqual({
  115. nonce: "nonce-1",
  116. return_to: "http://192.168.1.8:5173/web-remote/callback",
  117. app_return_to:
  118. "http://192.168.1.8:5173/web-remote?remoteControlToken=token&relayOrigin=https%3A%2F%2Frelay.example",
  119. });
  120. });
  121. it("uses the independent share callback when starting share login", () => {
  122. const { assigned, service } = createService({
  123. currentHref: "https://zcode.z.ai/cn/share/share-1",
  124. });
  125. service.startLogin({
  126. appReturnTo: "https://zcode.z.ai/cn/share/share-1",
  127. redirectUri: "https://zcode.z.ai/cn/share/callback",
  128. });
  129. expect(new URL(assigned[0]!).searchParams.get("redirect_uri")).toBe(
  130. "https://zcode.z.ai/cn/share/callback",
  131. );
  132. });
  133. it("preserves the canonical share page as the whole-Web OAuth return target", () => {
  134. const { assigned, service } = createService({
  135. currentHref: "https://zcode.z.ai/cn/share/share-1",
  136. });
  137. service.startLogin({ appReturnTo: "https://zcode.z.ai/cn/share/share-1" });
  138. const authorizeUrl = new URL(assigned[0]!);
  139. expect(parseOAuthState(authorizeUrl.searchParams.get("state")!)).toMatchObject({
  140. app_return_to: "https://zcode.z.ai/cn/share/share-1",
  141. });
  142. });
  143. it("forwards trusted cross-origin dev callbacks before nonce validation or token exchange", async () => {
  144. const { replaced, service } = createService({
  145. allowDevReturnToRedirect: true,
  146. currentOrigin: "https://zcode.z.ai",
  147. currentHref: "https://zcode.z.ai/web-remote/callback",
  148. });
  149. const state = buildOAuthState({
  150. nonce: "nonce-1",
  151. return_to: "http://192.168.1.8:5173/web-remote/callback",
  152. app_return_to: "http://192.168.1.8:5173/web-remote?remoteControlToken=token",
  153. });
  154. const fetchMock = vi.fn();
  155. vi.stubGlobal("fetch", fetchMock);
  156. const result = await service.handleCallback(
  157. `https://zcode.z.ai/web-remote/callback?code=code-1&state=${state}`,
  158. );
  159. expect(result).toBeNull();
  160. expect(fetchMock).not.toHaveBeenCalled();
  161. const redirectUrl = new URL(replaced[0]!);
  162. expect(redirectUrl.origin + redirectUrl.pathname).toBe(
  163. "http://192.168.1.8:5173/web-remote/callback",
  164. );
  165. expect(redirectUrl.searchParams.get("code")).toBe("code-1");
  166. expect(redirectUrl.searchParams.get("state")).toBe(state);
  167. });
  168. it("exchanges token, persists complete session, and returns sanitized app_return_to", async () => {
  169. const { localStorage, service, sessionStorage } = createService();
  170. sessionStorage.setItem("oauth_pending_nonce", "nonce-1");
  171. const state = buildOAuthState({
  172. nonce: "nonce-1",
  173. app_return_to: "http://192.168.1.8:5173/web-remote?remoteControlToken=token&ignored=1",
  174. });
  175. vi.stubGlobal(
  176. "fetch",
  177. vi.fn(async () => ({
  178. ok: true,
  179. json: async () => ({
  180. code: 0,
  181. data: {
  182. token: "jwt-token",
  183. zai: { access_token: "zai-token" },
  184. expires_in: 60,
  185. user: { user_id: "u_1", name: "Ada" },
  186. },
  187. }),
  188. })),
  189. );
  190. const result = await service.handleCallback(
  191. `http://192.168.1.8:5173/web-remote/callback?code=code-1&state=${state}`,
  192. );
  193. expect(result).toEqual({
  194. appReturnTo: "/web-remote?remoteControlToken=token",
  195. userInfo: {
  196. id: "u_1",
  197. username: "Ada",
  198. displayName: "Ada",
  199. },
  200. });
  201. expect(localStorage.getItem("zcodejwttoken")).toBe("jwt-token");
  202. expect(localStorage.getItem("oauth:zai:access_token")).toBe("zai-token");
  203. expect(localStorage.getItem("oauth:active_provider")).toBe("zai");
  204. expect(sessionStorage.getItem("oauth_pending_nonce")).toBeNull();
  205. });
  206. it("does not persist a half-login state when token response is incomplete", async () => {
  207. const { localStorage, service, sessionStorage } = createService();
  208. sessionStorage.setItem("oauth_pending_nonce", "nonce-1");
  209. const state = buildOAuthState({ nonce: "nonce-1" });
  210. vi.stubGlobal(
  211. "fetch",
  212. vi.fn(async () => ({
  213. ok: true,
  214. json: async () => ({
  215. code: 0,
  216. data: {
  217. token: "jwt-token",
  218. zai: {},
  219. user: { user_id: "u_1", name: "Ada" },
  220. },
  221. }),
  222. })),
  223. );
  224. await expect(
  225. service.handleCallback(
  226. `http://192.168.1.8:5173/web-remote/callback?code=code-1&state=${state}`,
  227. ),
  228. ).rejects.toThrow(/access_token/);
  229. expect(localStorage.getItem("zcodejwttoken")).toBeNull();
  230. expect(localStorage.getItem("oauth:zai:access_token")).toBeNull();
  231. expect(localStorage.getItem("oauth:active_provider")).toBeNull();
  232. });
  233. });
  234. /**
  235. * BigModel 登录。
  236. *
  237. * 起因:private 分享的 owner 判定用的是 provider 自己的 user id(BigModel 是
  238. * CustomerNumber 数字串,Z.ai 是 sub UUID),所以桌面端用 BigModel 发布的私享分享,
  239. * 在只能 z.ai 登录的分享页上永远匹配不到 owner,服务端按存在性隐匿返回 404/3211。
  240. */
  241. describe("WebAuthService BigModel provider", () => {
  242. afterEach(() => {
  243. vi.unstubAllGlobals();
  244. });
  245. it("授权 URL 用 BigModel 的参数名(redirect/appId),不是 ZAI 的那套", () => {
  246. const { assigned, service, sessionStorage } = createService();
  247. service.startLogin({
  248. provider: "bigmodel",
  249. redirectUri: "https://zcode.z.ai/cn/share/callback",
  250. });
  251. const url = new URL(assigned[0]!);
  252. expect(url.pathname).toBe("/login");
  253. expect(url.searchParams.get("redirect")).toBe("https://zcode.z.ai/cn/share/callback");
  254. expect(url.searchParams.get("appId")).toBe("zcode");
  255. // ZAI 专用参数不能出现,否则 BigModel 侧会忽略 redirect 直接回默认地址
  256. expect(url.searchParams.get("redirect_uri")).toBeNull();
  257. expect(url.searchParams.get("client_id")).toBeNull();
  258. expect(url.searchParams.get("response_type")).toBeNull();
  259. // 回调页要靠它知道用哪个 provider 换 token
  260. expect(sessionStorage.getItem("oauth_pending_provider")).toBe("bigmodel");
  261. });
  262. it("换 token 时带 provider,并从 data.bigmodel.access_token 取值", async () => {
  263. const { localStorage, service, sessionStorage } = createService();
  264. sessionStorage.setItem("oauth_pending_nonce", "nonce-1");
  265. sessionStorage.setItem("oauth_pending_provider", "bigmodel");
  266. const state = buildOAuthState({ nonce: "nonce-1" });
  267. const fetchMock = vi.fn(async () => ({
  268. ok: true,
  269. json: async () => ({
  270. code: 0,
  271. data: {
  272. token: "jwt-token",
  273. bigmodel: { access_token: "bigmodel-token" },
  274. user: { user_id: "53291785835589288", name: "Ada" },
  275. },
  276. }),
  277. }));
  278. vi.stubGlobal("fetch", fetchMock);
  279. const result = await service.handleCallback(
  280. `https://zcode.z.ai/cn/share/callback?code=code-1&state=${state}`,
  281. );
  282. expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)).provider).toBe("bigmodel");
  283. expect(result?.userInfo.id).toBe("53291785835589288");
  284. expect(localStorage.getItem("oauth:active_provider")).toBe("bigmodel");
  285. expect(localStorage.getItem("oauth:bigmodel:access_token")).toBe("bigmodel-token");
  286. expect(localStorage.getItem("zcodejwttoken")).toBe("jwt-token");
  287. // pending provider 用完即清,避免污染下一次登录
  288. expect(sessionStorage.getItem("oauth_pending_provider")).toBeNull();
  289. });
  290. it("缺少 pending provider 时按 zai 兜底,保持旧回调链接可用", async () => {
  291. const { localStorage, service, sessionStorage } = createService();
  292. sessionStorage.setItem("oauth_pending_nonce", "nonce-1");
  293. const state = buildOAuthState({ nonce: "nonce-1" });
  294. const fetchMock = vi.fn(async () => ({
  295. ok: true,
  296. json: async () => ({
  297. code: 0,
  298. data: {
  299. token: "jwt-token",
  300. zai: { access_token: "zai-token" },
  301. user: { user_id: "u_1", name: "Ada" },
  302. },
  303. }),
  304. }));
  305. vi.stubGlobal("fetch", fetchMock);
  306. await service.handleCallback(`https://zcode.z.ai/cn/share/callback?code=code-1&state=${state}`);
  307. expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)).provider).toBe("zai");
  308. expect(localStorage.getItem("oauth:active_provider")).toBe("zai");
  309. });
  310. it("BigModel 响应缺 access_token 时不落半个登录态", async () => {
  311. const { localStorage, service, sessionStorage } = createService();
  312. sessionStorage.setItem("oauth_pending_nonce", "nonce-1");
  313. sessionStorage.setItem("oauth_pending_provider", "bigmodel");
  314. const state = buildOAuthState({ nonce: "nonce-1" });
  315. vi.stubGlobal(
  316. "fetch",
  317. vi.fn(async () => ({
  318. ok: true,
  319. json: async () => ({
  320. code: 0,
  321. data: { token: "jwt-token", bigmodel: {}, user: { user_id: "5329", name: "Ada" } },
  322. }),
  323. })),
  324. );
  325. await expect(
  326. service.handleCallback(`https://zcode.z.ai/cn/share/callback?code=code-1&state=${state}`),
  327. ).rejects.toThrow(/data\.bigmodel\.access_token/);
  328. expect(localStorage.getItem("zcodejwttoken")).toBeNull();
  329. expect(localStorage.getItem("oauth:active_provider")).toBeNull();
  330. });
  331. });