feishu-onboard-http.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. import {
  2. isPendingText,
  3. parseJsonObject,
  4. readNumber,
  5. readPositiveNumber,
  6. readRecord,
  7. readString,
  8. type FeishuOnboardSession,
  9. } from './feishu-onboard-helpers.js';
  10. export type FeishuFetch = (input: string, init?: RequestInit) => Promise<Response>;
  11. export interface FeishuOnboardHttpOptions {
  12. readonly fetchImpl?: FeishuFetch;
  13. readonly accountsBaseUrl?: string;
  14. readonly openApiBaseUrl?: string;
  15. }
  16. export class LocalFeishuOnboardHttpClient {
  17. private readonly fetchImpl: FeishuFetch;
  18. private readonly accountsBaseUrl: string;
  19. private readonly openApiBaseUrl: string;
  20. constructor(options: FeishuOnboardHttpOptions) {
  21. this.fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init));
  22. this.accountsBaseUrl = (options.accountsBaseUrl ?? 'https://accounts.feishu.cn').replace(/\/$/u, '');
  23. this.openApiBaseUrl = (options.openApiBaseUrl ?? 'https://open.feishu.cn').replace(/\/$/u, '');
  24. }
  25. async beginAppRegistration(): Promise<
  26. | { ok: true; deviceCode: string; verificationUriComplete: string; userCode?: string; expiresInSec: number; intervalSec: number }
  27. | { ok: false; error: string }
  28. > {
  29. const begin = await this.postRegistration({
  30. action: 'begin',
  31. archetype: 'PersonalAgent',
  32. auth_method: 'client_secret',
  33. request_user_info: 'open_id tenant_brand',
  34. });
  35. if (!begin.ok) return begin;
  36. const deviceCode = readString(begin.data, 'device_code');
  37. const userCode = readString(begin.data, 'user_code');
  38. const verificationUriComplete =
  39. readString(begin.data, 'verification_uri_complete') ??
  40. (userCode
  41. ? `${this.openApiBaseUrl}/page/launcher?user_code=${encodeURIComponent(userCode)}`
  42. : readString(begin.data, 'verification_uri'));
  43. if (!deviceCode || !verificationUriComplete) {
  44. return { ok: false, error: 'app registration device_code or verification_uri missing' };
  45. }
  46. return {
  47. ok: true,
  48. deviceCode,
  49. verificationUriComplete,
  50. ...(userCode ? { userCode } : {}),
  51. expiresInSec: readPositiveNumber(begin.data, 'expires_in') ?? 300,
  52. intervalSec: readPositiveNumber(begin.data, 'interval') ?? 5,
  53. };
  54. }
  55. async pollAppRegistration(
  56. deviceCode: string,
  57. ): Promise<
  58. | { ok: true; pending: true }
  59. | { ok: true; pending: false; appId: string; appSecret: string }
  60. | { ok: false; error: string }
  61. > {
  62. const poll = await this.postRegistration({ action: 'poll', device_code: deviceCode });
  63. if (!poll.ok) return isPendingText(poll.error) ? { ok: true, pending: true } : poll;
  64. const appId = readString(poll.data, 'client_id');
  65. const appSecret = readString(poll.data, 'client_secret');
  66. return appId && appSecret
  67. ? { ok: true, pending: false, appId, appSecret }
  68. : { ok: true, pending: true };
  69. }
  70. async beginUserDeviceCode(appId: string): Promise<
  71. | { ok: true; deviceCode: string; verificationUriComplete: string; userCode?: string; expiresInSec: number; intervalSec: number }
  72. | { ok: false; error: string }
  73. > {
  74. const body = await this.postForm(`${this.openApiBaseUrl}/open-apis/authen/v1/oidc/device_code`, {
  75. app_id: appId,
  76. scope: 'im:message contact:user.id:readonly',
  77. });
  78. if (!body.ok) return body;
  79. const deviceCode = readString(body.data, 'device_code');
  80. const verificationUriComplete = readString(body.data, 'verification_uri_complete') ?? readString(body.data, 'verification_uri');
  81. if (!deviceCode || !verificationUriComplete) {
  82. return { ok: false, error: 'user device_code or verification_uri missing' };
  83. }
  84. const userCode = readString(body.data, 'user_code');
  85. return {
  86. ok: true,
  87. deviceCode,
  88. verificationUriComplete,
  89. ...(userCode ? { userCode } : {}),
  90. expiresInSec: readPositiveNumber(body.data, 'expires_in') ?? 300,
  91. intervalSec: readPositiveNumber(body.data, 'interval') ?? 5,
  92. };
  93. }
  94. async pollUserToken(
  95. session: FeishuOnboardSession,
  96. ): Promise<
  97. | { ok: true; pending: true }
  98. | { ok: true; pending: false; openId?: string; name?: string }
  99. | { ok: false; error: string }
  100. > {
  101. const body = await this.postForm(`${this.openApiBaseUrl}/open-apis/authen/v1/oidc/device_token`, {
  102. app_id: session.appId ?? '',
  103. app_secret: session.appSecret ?? '',
  104. device_code: session.userDeviceCode ?? '',
  105. });
  106. if (!body.ok) return isPendingText(body.error) ? { ok: true, pending: true } : body;
  107. const payload = readRecord(body.data, 'data') ?? body.data;
  108. const accessToken = readString(payload, 'access_token');
  109. if (!accessToken) return { ok: true, pending: true };
  110. const openId = readString(payload, 'open_id');
  111. const name = readString(payload, 'name');
  112. return { ok: true, pending: false, ...(openId ? { openId } : {}), ...(name ? { name } : {}) };
  113. }
  114. private postRegistration(
  115. fields: Record<string, string>,
  116. ): Promise<{ ok: true; data: Record<string, unknown> } | { ok: false; error: string }> {
  117. return this.postForm(`${this.accountsBaseUrl}/oauth/v1/app/registration`, fields);
  118. }
  119. private async postForm(
  120. url: string,
  121. fields: Record<string, string>,
  122. ): Promise<{ ok: true; data: Record<string, unknown> } | { ok: false; error: string }> {
  123. const response = await this.fetchImpl(url, {
  124. method: 'POST',
  125. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  126. body: new URLSearchParams(fields).toString(),
  127. });
  128. const text = await response.text().catch(() => '');
  129. const data = parseJsonObject(text);
  130. if (!response.ok) return { ok: false, error: text || `HTTP ${response.status}` };
  131. if (readString(data, 'error') && readString(data, 'error') !== 'authorization_pending') {
  132. return { ok: false, error: readString(data, 'error') ?? 'request failed' };
  133. }
  134. const code = readNumber(data, 'code');
  135. if (code !== undefined && code !== 0) return { ok: false, error: readString(data, 'msg') ?? `code ${code}` };
  136. return { ok: true, data };
  137. }
  138. }