webAuthService.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import { ZAI_PROVIDER_ID, type UserInfo } from "@zcode/shared";
  2. import {
  3. BrowserOAuthCredentialRepo,
  4. type WebOAuthProviderId,
  5. } from "./browserOAuthCredentialRepo.js";
  6. import {
  7. buildOAuthState,
  8. buildReturnToCallbackUrl,
  9. buildWebRemoteOAuthRedirectUri,
  10. isTrustedDevReturnTo,
  11. parseOAuthState,
  12. parseOptionalUrl,
  13. resolveSafeAppReturnTo,
  14. } from "./oauthStateCodec.js";
  15. import { WEB_ZAI_OAUTH_CONFIG, type WebZaiOAuthConfig } from "./webZaiOAuthConfig.js";
  16. import { ZaiWebOAuthProvider } from "./zaiWebOAuthProvider.js";
  17. interface WebAuthServiceRuntime {
  18. assign(url: string): void;
  19. createNonce(): string;
  20. getCurrentHref(): string;
  21. getCurrentOrigin(): string;
  22. replace(url: string): void;
  23. }
  24. interface WebAuthServiceDependencies {
  25. config?: WebZaiOAuthConfig;
  26. provider?: ZaiWebOAuthProvider;
  27. repo?: BrowserOAuthCredentialRepo;
  28. runtime?: WebAuthServiceRuntime;
  29. }
  30. interface WebAuthLoginOptions {
  31. devReturnTo?: string;
  32. appReturnTo?: string;
  33. redirectUri?: string;
  34. /** 缺省 zai,保持 /remote 等既有入口行为不变。 */
  35. provider?: WebOAuthProviderId;
  36. }
  37. export interface WebAuthCallbackResult {
  38. userInfo: UserInfo;
  39. appReturnTo: string | null;
  40. }
  41. function createBrowserNonce(): string {
  42. if (globalThis.crypto?.randomUUID) {
  43. return globalThis.crypto.randomUUID();
  44. }
  45. if (!globalThis.crypto?.getRandomValues) {
  46. throw new Error("Secure random generator is unavailable");
  47. }
  48. const bytes = new Uint8Array(16);
  49. globalThis.crypto.getRandomValues(bytes);
  50. return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
  51. }
  52. function createDefaultRuntime(): WebAuthServiceRuntime {
  53. return {
  54. assign: (url) => {
  55. window.location.assign(url);
  56. },
  57. createNonce: createBrowserNonce,
  58. getCurrentHref: () => window.location.href,
  59. getCurrentOrigin: () => window.location.origin,
  60. replace: (url) => {
  61. window.location.replace(url);
  62. },
  63. };
  64. }
  65. export class WebAuthService {
  66. private readonly config: WebZaiOAuthConfig;
  67. private readonly provider: ZaiWebOAuthProvider;
  68. private readonly repo: BrowserOAuthCredentialRepo;
  69. private readonly runtime: WebAuthServiceRuntime;
  70. constructor(dependencies: WebAuthServiceDependencies = {}) {
  71. this.config = dependencies.config ?? WEB_ZAI_OAUTH_CONFIG;
  72. this.provider = dependencies.provider ?? new ZaiWebOAuthProvider(this.config);
  73. this.repo = dependencies.repo ?? new BrowserOAuthCredentialRepo();
  74. this.runtime = dependencies.runtime ?? createDefaultRuntime();
  75. }
  76. startLogin(options: WebAuthLoginOptions = {}): void {
  77. const nonce = this.runtime.createNonce();
  78. const provider = options.provider ?? ZAI_PROVIDER_ID;
  79. const appReturnTo = options.appReturnTo ?? this.runtime.getCurrentHref();
  80. const returnToOptions = { currentOrigin: this.runtime.getCurrentOrigin() };
  81. const redirectUri = buildWebRemoteOAuthRedirectUri(
  82. options.redirectUri ?? this.config.redirectUri,
  83. appReturnTo,
  84. returnToOptions,
  85. );
  86. this.repo.savePendingLogin({ nonce, provider, redirectUri });
  87. const state = buildOAuthState({
  88. nonce,
  89. app_return_to: appReturnTo,
  90. ...(options.devReturnTo
  91. ? {
  92. return_to: buildWebRemoteOAuthRedirectUri(
  93. options.devReturnTo,
  94. appReturnTo,
  95. returnToOptions,
  96. ),
  97. }
  98. : {}),
  99. });
  100. this.runtime.assign(
  101. this.provider.buildAuthorizeUrl({
  102. state,
  103. provider,
  104. redirectUri,
  105. }),
  106. );
  107. }
  108. async handleCallback(url: string): Promise<WebAuthCallbackResult | null> {
  109. const callback = this.provider.parseCallbackParams(url);
  110. const statePayload = parseOAuthState(callback.state);
  111. if (!statePayload) {
  112. throw new Error("OAuth state is invalid");
  113. }
  114. const returnToUrl = parseOptionalUrl(statePayload.return_to);
  115. if (returnToUrl && returnToUrl.origin !== this.runtime.getCurrentOrigin()) {
  116. if (this.config.allowDevReturnToRedirect && isTrustedDevReturnTo(returnToUrl)) {
  117. const redirectUrl = buildReturnToCallbackUrl(returnToUrl.toString(), {
  118. ...(callback.code ? { code: callback.code } : {}),
  119. ...(callback.error ? { error: callback.error } : {}),
  120. state: callback.state,
  121. });
  122. if (redirectUrl) {
  123. this.runtime.replace(redirectUrl);
  124. return null;
  125. }
  126. }
  127. }
  128. if (callback.error) {
  129. throw new Error(`OAuth login failed: ${callback.error}`);
  130. }
  131. if (!callback.code) {
  132. throw new Error("OAuth callback missing code");
  133. }
  134. // provider 与回调地址必须取跳转前记下的那条:authorize 参数名和 token 响应里 access_token
  135. // 的位置都是 provider 特定的,token 请求也要用授权时的完整回调地址。
  136. const pendingLogin = this.repo.takePendingLogin(statePayload.nonce);
  137. if (!pendingLogin) {
  138. throw new Error("OAuth CSRF 检测失败");
  139. }
  140. const { provider, redirectUri } = pendingLogin;
  141. const exchange = await this.provider.exchangeToken({
  142. code: callback.code,
  143. state: callback.state,
  144. provider,
  145. redirectUri,
  146. });
  147. this.repo.saveTokenSet(exchange.tokenSet, provider);
  148. this.repo.saveUserInfo(exchange.rawUserInfo, provider);
  149. this.repo.setActiveProvider(provider);
  150. return {
  151. userInfo: exchange.userInfo,
  152. appReturnTo: resolveSafeAppReturnTo(statePayload.app_return_to, {
  153. currentOrigin: this.runtime.getCurrentOrigin(),
  154. }),
  155. };
  156. }
  157. async restoreCachedSession(): Promise<UserInfo | null> {
  158. return this.repo.loadCachedSession();
  159. }
  160. restoreCachedSessionState() {
  161. return this.repo.loadCachedSessionState();
  162. }
  163. getZCodeJwtToken(): string | null {
  164. return this.repo.loadZCodeJwtToken();
  165. }
  166. /** 设备页账号行的展示资料;只读,不参与登录判断。 */
  167. getActiveAccount(): {
  168. displayName: string;
  169. avatarUrl?: string;
  170. provider: WebOAuthProviderId;
  171. } | null {
  172. const account = this.repo.loadActiveAccount();
  173. if (!account) return null;
  174. const { userInfo, provider } = account;
  175. return {
  176. displayName: userInfo.displayName.trim() || userInfo.username,
  177. ...(userInfo.avatarUrl ? { avatarUrl: userInfo.avatarUrl } : {}),
  178. provider,
  179. };
  180. }
  181. async logout(): Promise<void> {
  182. this.repo.clearAll();
  183. }
  184. }
  185. export function createWebAuthService(): WebAuthService {
  186. return new WebAuthService();
  187. }