feishuAppRegistration.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. type FeishuAppRegistrationDomain = "feishu" | "lark";
  2. interface FeishuAppRegistrationBeginResult {
  3. deviceCode: string;
  4. qrUrl: string;
  5. userCode: string;
  6. interval: number;
  7. expiresAt: number;
  8. domain: FeishuAppRegistrationDomain;
  9. pollDomain?: FeishuAppRegistrationDomain;
  10. }
  11. type FeishuAppRegistrationPollResult =
  12. | {
  13. status: "pending";
  14. interval: number;
  15. domain: FeishuAppRegistrationDomain;
  16. pollDomain?: FeishuAppRegistrationDomain;
  17. }
  18. | {
  19. status: "success";
  20. appId: string;
  21. appSecret: string;
  22. domain: FeishuAppRegistrationDomain;
  23. appName?: string;
  24. openId?: string;
  25. }
  26. | {
  27. status: "access_denied" | "expired" | "error";
  28. message?: string;
  29. domain: FeishuAppRegistrationDomain;
  30. };
  31. interface FeishuAppRegistrationInitResponse {
  32. supported_auth_methods?: string[];
  33. }
  34. interface FeishuAppRegistrationBeginResponse {
  35. device_code?: string;
  36. verification_uri_complete?: string;
  37. verification_uri?: string;
  38. user_code?: string;
  39. interval?: number;
  40. expire_in?: number;
  41. }
  42. interface FeishuAppRegistrationPollResponse {
  43. client_id?: string;
  44. client_secret?: string;
  45. app_name?: string;
  46. client_name?: string;
  47. name?: string;
  48. app?: {
  49. app_name?: string;
  50. name?: string;
  51. };
  52. user_info?: {
  53. open_id?: string;
  54. tenant_brand?: FeishuAppRegistrationDomain;
  55. };
  56. error?: string;
  57. error_description?: string;
  58. }
  59. const FEISHU_ACCOUNTS_URL = "https://accounts.feishu.cn";
  60. const LARK_ACCOUNTS_URL = "https://accounts.larksuite.com";
  61. const FEISHU_APP_REGISTRATION_PATH = "/oauth/v1/app/registration";
  62. const FEISHU_APP_REGISTRATION_TIMEOUT_MS = 10_000;
  63. const FEISHU_APP_REGISTRATION_SOURCE = "node-sdk/zcode";
  64. function getAccountsBaseUrl(domain: FeishuAppRegistrationDomain): string {
  65. return domain === "lark" ? LARK_ACCOUNTS_URL : FEISHU_ACCOUNTS_URL;
  66. }
  67. function readString(record: Record<string, unknown> | null | undefined, key: string): string {
  68. const value = record?.[key];
  69. return typeof value === "string" ? value : "";
  70. }
  71. function readRegistrationAppName(response: FeishuAppRegistrationPollResponse): string | undefined {
  72. const app = typeof response.app === "object" && response.app !== null ? response.app as Record<string, unknown> : null;
  73. return (
  74. response.app_name?.trim() ||
  75. response.client_name?.trim() ||
  76. response.name?.trim() ||
  77. readString(app, "app_name").trim() ||
  78. readString(app, "name").trim() ||
  79. undefined
  80. );
  81. }
  82. async function postRegistration<T>(
  83. domain: FeishuAppRegistrationDomain,
  84. body: Record<string, string>,
  85. ): Promise<T> {
  86. const response = await fetch(`${getAccountsBaseUrl(domain)}${FEISHU_APP_REGISTRATION_PATH}`, {
  87. method: "POST",
  88. headers: { "content-type": "application/x-www-form-urlencoded" },
  89. body: new URLSearchParams(body).toString(),
  90. signal: AbortSignal.timeout(FEISHU_APP_REGISTRATION_TIMEOUT_MS),
  91. });
  92. return (await response.json()) as T;
  93. }
  94. export async function beginFeishuAppRegistration(
  95. domain: FeishuAppRegistrationDomain = "feishu",
  96. ): Promise<FeishuAppRegistrationBeginResult> {
  97. // Bugfix: 对齐 @larksuiteoapi/node-sdk registerApp:一键创建应用总是先从 Feishu accounts issuer
  98. // 获取二维码,Lark 租户在 poll 阶段根据 tenant_brand 再切到 accounts.larksuite.com。
  99. const pollDomain: FeishuAppRegistrationDomain = "feishu";
  100. const initResponse = await postRegistration<FeishuAppRegistrationInitResponse>(pollDomain, {
  101. action: "init",
  102. });
  103. if (!initResponse.supported_auth_methods?.includes("client_secret")) {
  104. throw new Error("Current Feishu environment does not support client_secret registration.");
  105. }
  106. const beginResponse = await postRegistration<FeishuAppRegistrationBeginResponse>(pollDomain, {
  107. action: "begin",
  108. archetype: "PersonalAgent",
  109. auth_method: "client_secret",
  110. request_user_info: "open_id",
  111. });
  112. if (!beginResponse.device_code || !beginResponse.verification_uri_complete) {
  113. throw new Error("Feishu app registration did not return a device code.");
  114. }
  115. const qrUrl = new URL(beginResponse.verification_uri_complete);
  116. // SDK registerApp 使用 from=sdk/source=node-sdk[/source]/tp=sdk;这里保留 zcode 来源方便排查。
  117. qrUrl.searchParams.set("from", "sdk");
  118. qrUrl.searchParams.set("source", FEISHU_APP_REGISTRATION_SOURCE);
  119. qrUrl.searchParams.set("tp", "sdk");
  120. const expireInSeconds = beginResponse.expire_in ?? 600;
  121. return {
  122. deviceCode: beginResponse.device_code,
  123. qrUrl: qrUrl.toString(),
  124. userCode: beginResponse.user_code ?? "",
  125. interval: beginResponse.interval ?? 5,
  126. expiresAt: Date.now() + expireInSeconds * 1000,
  127. domain,
  128. pollDomain,
  129. };
  130. }
  131. export async function pollFeishuAppRegistration(params: {
  132. deviceCode: string;
  133. domain?: FeishuAppRegistrationDomain;
  134. pollDomain?: FeishuAppRegistrationDomain;
  135. }): Promise<FeishuAppRegistrationPollResult> {
  136. const domain = params.domain ?? "feishu";
  137. const pollDomain = params.pollDomain ?? domain;
  138. const pollResponse = await postRegistration<FeishuAppRegistrationPollResponse>(pollDomain, {
  139. action: "poll",
  140. device_code: params.deviceCode,
  141. });
  142. const resultDomain = pollResponse.user_info?.tenant_brand ?? domain;
  143. if (pollResponse.user_info?.tenant_brand === "lark" && pollDomain !== "lark") {
  144. return {
  145. status: "pending",
  146. interval: 0,
  147. domain: resultDomain,
  148. pollDomain: "lark",
  149. };
  150. }
  151. if (pollResponse.client_id && pollResponse.client_secret) {
  152. const appName = readRegistrationAppName(pollResponse);
  153. return {
  154. status: "success",
  155. appId: pollResponse.client_id,
  156. appSecret: pollResponse.client_secret,
  157. domain: resultDomain,
  158. ...(appName ? { appName } : {}),
  159. openId: pollResponse.user_info?.open_id,
  160. };
  161. }
  162. if (!pollResponse.error || pollResponse.error === "authorization_pending") {
  163. return { status: "pending", interval: 5, domain: resultDomain };
  164. }
  165. if (pollResponse.error === "slow_down") {
  166. return { status: "pending", interval: 10, domain: resultDomain };
  167. }
  168. if (pollResponse.error === "access_denied") {
  169. return { status: "access_denied", domain: resultDomain };
  170. }
  171. if (pollResponse.error === "expired_token") {
  172. return { status: "expired", domain: resultDomain };
  173. }
  174. return {
  175. status: "error",
  176. message: `${pollResponse.error}: ${pollResponse.error_description ?? "unknown"}`,
  177. domain: resultDomain,
  178. };
  179. }