project-access-token.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. import { z } from "zod";
  2. import { projectTokenSuccessCodeSchema } from "./project-access-token-response.js";
  3. import type { ApiKeyCreationUsageScene } from "./api-key-usage-scene.js";
  4. const SECOND_MS = 1_000;
  5. const REFRESH_LEAD_MS = 120 * SECOND_MS;
  6. const REFRESH_JITTER_MS = 60 * SECOND_MS;
  7. const REFRESH_RETRY_BACKOFF_MS = 5 * SECOND_MS;
  8. const responseSchema = z.preprocess(
  9. (raw) => {
  10. if (
  11. raw &&
  12. typeof raw === "object" &&
  13. "data" in raw &&
  14. raw.data &&
  15. typeof raw.data === "object" &&
  16. !("enable" in raw.data)
  17. ) {
  18. return { ...raw, data: { ...raw.data, enable: true } };
  19. }
  20. return raw;
  21. },
  22. z.object({
  23. code: projectTokenSuccessCodeSchema,
  24. data: z.discriminatedUnion("enable", [
  25. z.object({ enable: z.literal(false) }),
  26. z.object({
  27. enable: z.literal(true),
  28. accessToken: z.string().trim().min(1),
  29. tokenType: z.literal("Bearer"),
  30. expiresIn: z.number().finite().positive(),
  31. expiresAt: z.number().finite().positive(),
  32. }),
  33. ]),
  34. }),
  35. );
  36. export interface ProjectAccessTokenScope {
  37. readonly origin: string;
  38. readonly family: "bigmodel" | "zai";
  39. readonly accountId: string;
  40. readonly organizationId: string;
  41. readonly projectId: string;
  42. readonly apiKeyId: string;
  43. readonly usageScene: ApiKeyCreationUsageScene;
  44. /** 登录生命周期标识,不能使用 Token 原文或短期 Token 的哈希。 */
  45. readonly loginGeneration: string;
  46. }
  47. export type ProjectAccessTokenResult =
  48. | { readonly enabled: false }
  49. | {
  50. readonly enabled: true;
  51. readonly token: string;
  52. readonly expiresAt: number;
  53. };
  54. export class ProjectAccessTokenError extends Error {
  55. constructor(readonly code: "project_token_invalid_response" | "project_token_scope_invalidated") {
  56. // 响应包含凭据;不把 zod issues、原始响应或 Token 放进异常/日志。
  57. super(code);
  58. this.name = "ProjectAccessTokenError";
  59. }
  60. }
  61. /** I/O adapter 确认的临时故障;不携带原始响应、URL、Token 或 cause。 */
  62. export class ProjectAccessTokenTransientError extends Error {
  63. constructor() {
  64. super("project_token_transient_failure");
  65. this.name = "ProjectAccessTokenTransientError";
  66. }
  67. }
  68. interface CacheEntry {
  69. fingerprint?: string;
  70. value?: Extract<ProjectAccessTokenResult, { enabled: true }>;
  71. refreshAt?: number;
  72. pending?: Promise<ProjectAccessTokenResult>;
  73. }
  74. /**
  75. * 账号鉴权 owner 的纯内存状态,不含网络、存储、定时器或全局单例。
  76. * Host 和 Standalone 分别持有实例;签发由其已有 I/O adapter 注入。
  77. */
  78. export class ProjectAccessTokenCache {
  79. readonly #entries = new Map<string, CacheEntry>();
  80. readonly #now: () => number;
  81. readonly #random: () => number;
  82. readonly #onRefreshDeferred?: () => void;
  83. constructor(
  84. options: { now?: () => number; random?: () => number; onRefreshDeferred?: () => void } = {},
  85. ) {
  86. this.#now = options.now ?? Date.now;
  87. this.#random = options.random ?? Math.random;
  88. this.#onRefreshDeferred = options.onRefreshDeferred;
  89. }
  90. async resolve(
  91. scope: ProjectAccessTokenScope,
  92. issue: () => Promise<unknown>,
  93. rejectedFingerprint?: string,
  94. ): Promise<ProjectAccessTokenResult> {
  95. const key = scopeKey(scope);
  96. let entry = this.#entries.get(key);
  97. // 仅清理被拒绝的那一代 PAT;迟到的 401 不得废弃新凭据或打断正在进行的换证。
  98. if (rejectedFingerprint && entry?.fingerprint === rejectedFingerprint) {
  99. entry.value = undefined;
  100. entry.refreshAt = undefined;
  101. }
  102. if (entry?.pending) return entry.pending;
  103. if (entry?.value && this.#now() < Math.min(entry.refreshAt!, entry.value.expiresAt)) {
  104. return entry.value;
  105. }
  106. if (!entry) {
  107. entry = {};
  108. this.#entries.set(key, entry);
  109. }
  110. const current = entry;
  111. const startedAt = this.#now();
  112. // 延迟到微任务执行签发,先登记 pending,确保同步重入也只生成一个请求。
  113. const pending = Promise.resolve()
  114. .then(() => {
  115. // 退出可能先于签发微任务发生;此时连旧登录态的网络请求也不得发出。
  116. if (this.#entries.get(key) !== current) {
  117. throw new ProjectAccessTokenError("project_token_scope_invalidated");
  118. }
  119. return issue();
  120. })
  121. .then(async (raw) => {
  122. if (this.#entries.get(key) !== current) {
  123. throw new ProjectAccessTokenError("project_token_scope_invalidated");
  124. }
  125. const response = responseSchema.safeParse(raw);
  126. if (!response.success) throw new ProjectAccessTokenError("project_token_invalid_response");
  127. const data = response.data.data;
  128. if (!data.enable) {
  129. this.#entries.delete(key);
  130. return Object.freeze({ enabled: false } as const);
  131. }
  132. // expiresIn 从发出签发请求时保守起算,不能把网络耗时变成额外有效期。
  133. const expiresAt = Math.min(
  134. data.expiresAt * SECOND_MS,
  135. startedAt + data.expiresIn * SECOND_MS,
  136. );
  137. if (!Number.isFinite(expiresAt) || expiresAt <= this.#now()) {
  138. throw new ProjectAccessTokenError("project_token_invalid_response");
  139. }
  140. const jitter = Math.max(0, Math.min(1, this.#random())) * REFRESH_JITTER_MS;
  141. const fingerprint = await projectAccessTokenFingerprint(data.accessToken);
  142. if (this.#entries.get(key) !== current)
  143. throw new ProjectAccessTokenError("project_token_scope_invalidated");
  144. current.fingerprint = fingerprint;
  145. current.value = Object.freeze({
  146. enabled: true,
  147. token: data.accessToken,
  148. expiresAt,
  149. });
  150. current.refreshAt = expiresAt - REFRESH_LEAD_MS - jitter;
  151. return current.value;
  152. })
  153. .catch((error: unknown) => {
  154. if (this.#entries.get(key) !== current)
  155. throw new ProjectAccessTokenError("project_token_scope_invalidated");
  156. // 只保留仍有效且未被 401 指纹清除的 PAT;认证拒绝和格式错误必须失败。
  157. // 降级属于同一个 pending,使所有并发调用获得一致结果,不延长原有效期。
  158. if (
  159. error instanceof ProjectAccessTokenTransientError &&
  160. current.value &&
  161. this.#now() < current.value.expiresAt
  162. ) {
  163. current.refreshAt = Math.min(
  164. this.#now() + REFRESH_RETRY_BACKOFF_MS,
  165. current.value.expiresAt,
  166. );
  167. this.#onRefreshDeferred?.();
  168. return current.value;
  169. }
  170. this.#entries.delete(key);
  171. throw error;
  172. })
  173. .finally(() => {
  174. if (current.pending === pending) current.pending = undefined;
  175. });
  176. current.pending = pending;
  177. return pending;
  178. }
  179. invalidate(scope: ProjectAccessTokenScope): void {
  180. this.#entries.delete(scopeKey(scope));
  181. }
  182. clear(): void {
  183. this.#entries.clear();
  184. }
  185. }
  186. /** 仅用于拒绝某一代 PAT 的比较,不作为账号身份,也不传给模型上游。 */
  187. export async function projectAccessTokenFingerprint(token: string): Promise<string> {
  188. const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
  189. return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
  190. }
  191. function scopeKey(scope: ProjectAccessTokenScope): string {
  192. return JSON.stringify([
  193. scope.origin,
  194. scope.family,
  195. scope.accountId,
  196. scope.organizationId,
  197. scope.projectId,
  198. scope.apiKeyId,
  199. scope.usageScene,
  200. scope.loginGeneration,
  201. ]);
  202. }