zaiBusinessTokenResolver.ts 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import type { ApiClient } from "@zcode/shared";
  2. import { readApiJson } from "./api/apiJson.js";
  3. const ZAI_BUSINESS_TOKEN_REFRESH_SKEW_MS = 5 * 60 * 1000;
  4. interface ZaiBusinessLoginEnvelope {
  5. code?: number;
  6. msg?: string;
  7. success?: boolean;
  8. data?: {
  9. access_token?: string;
  10. accessToken?: string;
  11. expires_in?: number;
  12. } | null;
  13. }
  14. interface CachedZaiBusinessToken {
  15. oauthAccessToken: string;
  16. accessToken: string;
  17. expiresAt: number;
  18. }
  19. interface ZaiBusinessTokenResolverOptions {
  20. apiClient: ApiClient;
  21. loginUrl: string;
  22. timeoutMs: number;
  23. now?: () => number;
  24. }
  25. export class ZaiBusinessTokenResolver {
  26. private readonly apiClient: ApiClient;
  27. private readonly loginUrl: string;
  28. private readonly timeoutMs: number;
  29. private readonly now: () => number;
  30. private cachedToken: CachedZaiBusinessToken | null = null;
  31. constructor(options: ZaiBusinessTokenResolverOptions) {
  32. this.apiClient = options.apiClient;
  33. this.loginUrl = options.loginUrl;
  34. this.timeoutMs = options.timeoutMs;
  35. this.now = options.now ?? Date.now;
  36. }
  37. async resolve(oauthAccessToken: string): Promise<string> {
  38. const normalizedToken = oauthAccessToken.trim();
  39. if (!normalizedToken) {
  40. throw new Error("zai_oauth_required");
  41. }
  42. const cachedToken = this.cachedToken;
  43. if (this.isCachedTokenValid(cachedToken, normalizedToken)) {
  44. return cachedToken.accessToken;
  45. }
  46. this.cachedToken = null;
  47. return this.exchangeBusinessToken(normalizedToken);
  48. }
  49. private isCachedTokenValid(
  50. cachedToken: CachedZaiBusinessToken | null,
  51. oauthAccessToken: string,
  52. ): cachedToken is CachedZaiBusinessToken {
  53. return Boolean(
  54. cachedToken &&
  55. cachedToken.oauthAccessToken === oauthAccessToken &&
  56. cachedToken.expiresAt - ZAI_BUSINESS_TOKEN_REFRESH_SKEW_MS > this.now(),
  57. );
  58. }
  59. private async exchangeBusinessToken(oauthAccessToken: string): Promise<string> {
  60. let payload: ZaiBusinessLoginEnvelope;
  61. try {
  62. payload = await readApiJson<ZaiBusinessLoginEnvelope>(this.apiClient, this.loginUrl, {
  63. method: "POST",
  64. timeoutMs: this.timeoutMs,
  65. headers: {
  66. "Content-Type": "application/json",
  67. },
  68. body: JSON.stringify({ token: oauthAccessToken }),
  69. });
  70. } catch {
  71. throw new Error("zai_oauth_required");
  72. }
  73. if (!isSuccessfulZaiBusinessCode(payload.code) || payload.success === false) {
  74. throw new Error("zai_oauth_required");
  75. }
  76. const accessToken =
  77. payload.data?.access_token?.trim() ?? payload.data?.accessToken?.trim() ?? "";
  78. if (!accessToken) {
  79. throw new Error("zai_oauth_required");
  80. }
  81. const expiresIn = payload.data?.expires_in;
  82. if (expiresIn && Number.isFinite(expiresIn)) {
  83. this.cachedToken = {
  84. oauthAccessToken,
  85. accessToken,
  86. expiresAt: this.now() + expiresIn * 1000,
  87. };
  88. }
  89. return accessToken;
  90. }
  91. }
  92. function isSuccessfulZaiBusinessCode(code: unknown): boolean {
  93. if (code === null || code === undefined) {
  94. return true;
  95. }
  96. if (typeof code === "number") {
  97. return code === 0 || code === 200;
  98. }
  99. if (typeof code === "string") {
  100. return code === "0" || code === "200";
  101. }
  102. return false;
  103. }