oauth.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. /**
  2. * OAuth 领域类型定义
  3. *
  4. * 说明:敏感信息(如 appSecret)以及 provider 默认端点配置
  5. * 只允许放在 services 的 provider 模块中,不能放 shared 层。
  6. */
  7. /** 内置 BigModel provider id */
  8. export const BIGMODEL_PROVIDER_ID = "bigmodel" as const;
  9. /** 内置 ZAI provider id */
  10. export const ZAI_PROVIDER_ID = "zai" as const;
  11. /** 凭据解密失败错误前缀 */
  12. export const CREDENTIAL_DECRYPT_ERROR_PREFIX = "凭据解密失败:" as const;
  13. /** 凭据解密失败稳定错误码 */
  14. export const CREDENTIAL_DECRYPT_ERROR_CODE = "ZCODE_CREDENTIAL_DECRYPT_FAILED" as const;
  15. /** 判断错误是否来自本地凭据解密失败 */
  16. export function isCredentialDecryptError(error: unknown): boolean {
  17. const code = readCredentialErrorCode(error);
  18. if (code) {
  19. return code === CREDENTIAL_DECRYPT_ERROR_CODE;
  20. }
  21. // 兼容历史错误和跨边界丢失 code 的旧 payload;新错误应优先携带稳定 code。
  22. if (readCredentialErrorMessage(error).startsWith(CREDENTIAL_DECRYPT_ERROR_PREFIX)) {
  23. return true;
  24. }
  25. return false;
  26. }
  27. function readCredentialErrorCode(error: unknown): string {
  28. if (typeof error === "object" && error !== null && "code" in error) {
  29. return String((error as { code?: unknown }).code ?? "");
  30. }
  31. return "";
  32. }
  33. function readCredentialErrorMessage(error: unknown): string {
  34. if (error instanceof Error) {
  35. return error.message;
  36. }
  37. if (typeof error === "object" && error !== null && "message" in error) {
  38. return String((error as { message?: unknown }).message ?? "");
  39. }
  40. return "";
  41. }
  42. /** OAuth provider 标识 */
  43. export type OAuthProviderId =
  44. | typeof BIGMODEL_PROVIDER_ID
  45. | typeof ZAI_PROVIDER_ID
  46. | (string & { readonly __oauthProviderBrand?: never });
  47. /** Provider 展示元信息 */
  48. export interface OAuthProviderMeta {
  49. id: OAuthProviderId;
  50. displayName: string;
  51. enabled: boolean;
  52. order: number;
  53. }
  54. /** 发起 OAuth 请求 */
  55. export interface OAuthStartRequest {
  56. provider: OAuthProviderId;
  57. }
  58. /** 发起 OAuth 返回 */
  59. export interface OAuthStartResponse {
  60. provider: OAuthProviderId;
  61. authorizeUrl: string;
  62. state: string;
  63. }
  64. /** 应用登录回调结果 */
  65. export interface OAuthSessionCallbackResult {
  66. kind: "session";
  67. provider: OAuthProviderId;
  68. userInfo: {
  69. id: string;
  70. username: string;
  71. displayName: string;
  72. avatarUrl?: string;
  73. };
  74. }
  75. /** 只携带归因参数的 OAuth deep link 回调结果 */
  76. export interface OAuthAttributionCallbackResult {
  77. kind: "attribution";
  78. provider: OAuthProviderId;
  79. attribution: OAuthLoginAttribution;
  80. }
  81. /** 同一登录已由 polling 完成后迟到的 deep link;调用方只需忽略。 */
  82. export interface OAuthDuplicateCallbackResult {
  83. kind: "duplicate";
  84. provider: OAuthProviderId;
  85. }
  86. /** OAuth 回调归一化结果 */
  87. export type OAuthCallbackResult =
  88. | OAuthSessionCallbackResult
  89. | OAuthAttributionCallbackResult
  90. | OAuthDuplicateCallbackResult;
  91. /** Main 进程路由 deep link 时使用的 state 上报结构 */
  92. export interface OAuthStateRegistration {
  93. state: string;
  94. provider?: OAuthProviderId;
  95. }
  96. /** 归一化后的回调参数 */
  97. export interface OAuthCallbackParams {
  98. state: string;
  99. code: string;
  100. attribution?: OAuthLoginAttribution;
  101. }
  102. /** OAuth 登录归因参数:来自官网中转页或投放链接 */
  103. export interface OAuthLoginAttribution {
  104. channel_id?: string;
  105. utm_source?: string;
  106. utm_campaign?: string;
  107. }
  108. /** 归一化 token 结构 */
  109. export interface OAuthTokenSet {
  110. accessToken: string;
  111. refreshToken?: string;
  112. expiresAt?: number;
  113. zcodeJwtToken?: string;
  114. }
  115. export interface UserInfo {
  116. id: string;
  117. username: string;
  118. displayName: string;
  119. avatarUrl?: string;
  120. }
  121. export type OAuthCachedSessionRestoreResult =
  122. | { status: "authenticated"; userInfo: UserInfo }
  123. | { status: "signed-out" }
  124. | { status: "reauthentication-required"; reason: "jwt-expired" };
  125. /** Host 在检测到 ZCode JWT 失效后通知 Renderer 展示确认并重启。 */
  126. export const ZCODE_JWT_INVALID_BROADCAST_CHANNEL = "auth:zcode-jwt-invalid";
  127. export type JwtExpirationResult =
  128. | { kind: "valid"; expiresAt: number }
  129. | { kind: "expired"; expiresAt: number }
  130. | { kind: "unknown" };
  131. /**
  132. * 只解析 JWT 的 exp 来判断本地生命周期,不承担签名校验。
  133. * 无法证明已过期的历史或非标准 token 保持兼容,最终有效性仍由服务端决定。
  134. */
  135. export function resolveJwtExpiration(
  136. token: string,
  137. now = Date.now(),
  138. clockSkewMs = 30_000,
  139. ): JwtExpirationResult {
  140. try {
  141. const payloadSegment = token.split(".")[1];
  142. if (!payloadSegment) {
  143. return { kind: "unknown" };
  144. }
  145. const normalized = payloadSegment.replace(/-/g, "+").replace(/_/g, "/");
  146. const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=");
  147. const decoded = globalThis.atob(padded);
  148. const bytes = Uint8Array.from(decoded, (character) => character.charCodeAt(0));
  149. const payload = JSON.parse(new TextDecoder().decode(bytes)) as { exp?: unknown };
  150. if (typeof payload.exp !== "number" || !Number.isFinite(payload.exp) || payload.exp <= 0) {
  151. return { kind: "unknown" };
  152. }
  153. const expiresAt = payload.exp * 1_000;
  154. return now + Math.max(0, clockSkewMs) >= expiresAt
  155. ? { kind: "expired", expiresAt }
  156. : { kind: "valid", expiresAt };
  157. } catch {
  158. return { kind: "unknown" };
  159. }
  160. }
  161. /** 归一化用户信息 */
  162. export interface OAuthUserProfile {
  163. id: string;
  164. username: string;
  165. displayName: string;
  166. avatarUrl?: string;
  167. rawProfile?: unknown;
  168. }
  169. /** 登出范围 */
  170. export type OAuthLogoutScope = "active" | "all";