nls-token.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * 取阿里云 NLS 的 token(实时语音识别用)。
  3. *
  4. * 2026-10-28 起**不再走 `/api` 反向代理**,直接请求 HTTPS 地址
  5. * `https://kdyjs-proxy.metamaker.cn/proxy_proxy/proxy/verify/getALYToken`
  6. * (该地址带 `Access-Control-Allow-Origin: *`,浏览器可跨域直连)。
  7. * 返回形态:`{ code: 200, message: "成功", content: "<32 位 token>" }`。
  8. *
  9. * **前端不持有任何阿里云凭据**:签名要 AccessKeySecret,而前端 bundle 是公开的,
  10. * 签名在网关侧做,前端只拿结果。网关**不返回过期时间**,按官方文档的 24 小时估。
  11. *
  12. * 缓存策略:缓存到**过期前 5 分钟**;并发调用共用同一个在途请求。
  13. */
  14. import { getNlsAppkey, getNlsTokenApiUrl } from "@/utils/runtime-config";
  15. export interface NlsTokenResult {
  16. token: string;
  17. /** 过期时间(epoch 毫秒)—— 网关不给,按 24 小时估 */
  18. expireAt: number;
  19. }
  20. /** NLS token 的有效期(官方文档 24 小时;网关不返回,所以按它估) */
  21. const TOKEN_LIFETIME_MS = 24 * 60 * 60 * 1000;
  22. /** 提前多久视为过期(留出换 token + 重连的余量) */
  23. const REFRESH_AHEAD_MS = 5 * 60 * 1000;
  24. let cached: NlsTokenResult | null = null;
  25. let inflight: Promise<NlsTokenResult> | null = null;
  26. const isValid = () => !!cached && cached.expireAt - Date.now() > REFRESH_AHEAD_MS;
  27. export const fetchNlsToken = async (): Promise<NlsTokenResult> => {
  28. if (isValid()) {
  29. return cached as NlsTokenResult;
  30. }
  31. if (inflight) {
  32. return inflight;
  33. }
  34. inflight = (async () => {
  35. const response = await fetch(getNlsTokenApiUrl(), { method: "GET" });
  36. let body: any = null;
  37. try {
  38. body = await response.json();
  39. } catch {
  40. /* 非 JSON 时按状态码报错 */
  41. }
  42. if (!response.ok) {
  43. throw new Error(body?.message || `获取语音识别 token 失败(HTTP ${response.status})`);
  44. }
  45. // 网关用 code 表达业务结果(HTTP 200 也可能是失败)
  46. if (Number(body?.code) !== 200 || !body?.content) {
  47. throw new Error(body?.message || "获取语音识别 token 失败:响应里没有 token");
  48. }
  49. cached = {
  50. token: String(body.content).trim(),
  51. expireAt: Date.now() + TOKEN_LIFETIME_MS,
  52. };
  53. return cached;
  54. })();
  55. try {
  56. return await inflight;
  57. } finally {
  58. inflight = null;
  59. }
  60. };
  61. /** NLS 的 appkey(识别请求要带)—— 见 `getNlsAppkey` 的说明 */
  62. export const getNlsTokenAppkey = (): string => getNlsAppkey();
  63. /** 丢掉缓存(怀疑 token 失效时强制重取) */
  64. export const clearNlsTokenCache = (): void => {
  65. cached = null;
  66. };