webAuthService.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. isTrustedDevReturnTo,
  10. parseOAuthState,
  11. parseOptionalUrl,
  12. resolveSafeAppReturnTo,
  13. } from "./oauthStateCodec.js";
  14. import { WEB_ZAI_OAUTH_CONFIG, type WebZaiOAuthConfig } from "./webZaiOAuthConfig.js";
  15. import { ZaiWebOAuthProvider } from "./zaiWebOAuthProvider.js";
  16. interface WebAuthServiceRuntime {
  17. assign(url: string): void;
  18. createNonce(): string;
  19. getCurrentHref(): string;
  20. getCurrentOrigin(): string;
  21. replace(url: string): void;
  22. }
  23. interface WebAuthServiceDependencies {
  24. config?: WebZaiOAuthConfig;
  25. provider?: ZaiWebOAuthProvider;
  26. repo?: BrowserOAuthCredentialRepo;
  27. runtime?: WebAuthServiceRuntime;
  28. }
  29. interface WebAuthLoginOptions {
  30. devReturnTo?: string;
  31. appReturnTo?: string;
  32. redirectUri?: string;
  33. /** 缺省 zai,保持 /remote 等既有入口行为不变。 */
  34. provider?: WebOAuthProviderId;
  35. }
  36. export interface WebAuthCallbackResult {
  37. userInfo: UserInfo;
  38. appReturnTo: string | null;
  39. }
  40. function createBrowserNonce(): string {
  41. if (globalThis.crypto?.randomUUID) {
  42. return globalThis.crypto.randomUUID();
  43. }
  44. if (!globalThis.crypto?.getRandomValues) {
  45. throw new Error("Secure random generator is unavailable");
  46. }
  47. const bytes = new Uint8Array(16);
  48. globalThis.crypto.getRandomValues(bytes);
  49. return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
  50. }
  51. function createDefaultRuntime(): WebAuthServiceRuntime {
  52. return {
  53. assign: (url) => {
  54. window.location.assign(url);
  55. },
  56. createNonce: createBrowserNonce,
  57. getCurrentHref: () => window.location.href,
  58. getCurrentOrigin: () => window.location.origin,
  59. replace: (url) => {
  60. window.location.replace(url);
  61. },
  62. };
  63. }
  64. export class WebAuthService {
  65. private readonly config: WebZaiOAuthConfig;
  66. private readonly provider: ZaiWebOAuthProvider;
  67. private readonly repo: BrowserOAuthCredentialRepo;
  68. private readonly runtime: WebAuthServiceRuntime;
  69. constructor(dependencies: WebAuthServiceDependencies = {}) {
  70. this.config = dependencies.config ?? WEB_ZAI_OAUTH_CONFIG;
  71. this.provider = dependencies.provider ?? new ZaiWebOAuthProvider(this.config);
  72. this.repo = dependencies.repo ?? new BrowserOAuthCredentialRepo();
  73. this.runtime = dependencies.runtime ?? createDefaultRuntime();
  74. }
  75. startLogin(options: WebAuthLoginOptions = {}): void {
  76. const nonce = this.runtime.createNonce();
  77. const provider = options.provider ?? ZAI_PROVIDER_ID;
  78. this.repo.savePendingNonce(nonce);
  79. this.repo.savePendingProvider(provider);
  80. const state = buildOAuthState({
  81. nonce,
  82. app_return_to: options.appReturnTo ?? this.runtime.getCurrentHref(),
  83. ...(options.devReturnTo ? { return_to: options.devReturnTo } : {}),
  84. });
  85. this.runtime.assign(
  86. this.provider.buildAuthorizeUrl({
  87. state,
  88. provider,
  89. redirectUri: options.redirectUri ?? this.config.redirectUri,
  90. }),
  91. );
  92. }
  93. async handleCallback(url: string): Promise<WebAuthCallbackResult | null> {
  94. const callback = this.provider.parseCallbackParams(url);
  95. const statePayload = parseOAuthState(callback.state);
  96. if (!statePayload) {
  97. throw new Error("OAuth state is invalid");
  98. }
  99. const returnToUrl = parseOptionalUrl(statePayload.return_to);
  100. if (returnToUrl && returnToUrl.origin !== this.runtime.getCurrentOrigin()) {
  101. if (this.config.allowDevReturnToRedirect && isTrustedDevReturnTo(returnToUrl)) {
  102. const redirectUrl = buildReturnToCallbackUrl(returnToUrl.toString(), {
  103. ...(callback.code ? { code: callback.code } : {}),
  104. ...(callback.error ? { error: callback.error } : {}),
  105. state: callback.state,
  106. });
  107. if (redirectUrl) {
  108. this.runtime.replace(redirectUrl);
  109. return null;
  110. }
  111. }
  112. }
  113. if (callback.error) {
  114. throw new Error(`OAuth login failed: ${callback.error}`);
  115. }
  116. if (!callback.code) {
  117. throw new Error("OAuth callback missing code");
  118. }
  119. const pendingNonce = this.repo.loadPendingNonce();
  120. if (statePayload.nonce !== pendingNonce) {
  121. throw new Error("OAuth CSRF 检测失败");
  122. }
  123. // provider 必须取跳转前记下的那个:authorize 参数名和 token 响应里 access_token 的位置
  124. // 都是 provider 特定的。缺失时按 zai 兜底,保持旧回调链接可用。
  125. const provider = this.repo.loadPendingProvider() ?? ZAI_PROVIDER_ID;
  126. this.repo.clearPendingNonce();
  127. this.repo.clearPendingProvider();
  128. const callbackRedirectUri = ["/cn/share/callback", "/share/callback"].includes(
  129. new URL(url).pathname,
  130. )
  131. ? this.config.shareRedirectUri
  132. : this.config.redirectUri;
  133. const exchange = await this.provider.exchangeToken({
  134. code: callback.code,
  135. state: callback.state,
  136. provider,
  137. redirectUri: callbackRedirectUri,
  138. });
  139. this.repo.saveTokenSet(exchange.tokenSet, provider);
  140. this.repo.saveUserInfo(exchange.rawUserInfo, provider);
  141. this.repo.setActiveProvider(provider);
  142. return {
  143. userInfo: exchange.userInfo,
  144. appReturnTo: resolveSafeAppReturnTo(statePayload.app_return_to, {
  145. currentOrigin: this.runtime.getCurrentOrigin(),
  146. }),
  147. };
  148. }
  149. async restoreCachedSession(): Promise<UserInfo | null> {
  150. return this.repo.loadCachedSession();
  151. }
  152. restoreCachedSessionState() {
  153. return this.repo.loadCachedSessionState();
  154. }
  155. getZCodeJwtToken(): string | null {
  156. return this.repo.loadZCodeJwtToken();
  157. }
  158. async logout(): Promise<void> {
  159. this.repo.clearAll();
  160. }
  161. }
  162. export function createWebAuthService(): WebAuthService {
  163. return new WebAuthService();
  164. }