File size: 14,616 Bytes
476094d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ec990d
476094d
 
 
 
 
7ec990d
476094d
 
 
7ec990d
476094d
 
 
 
 
 
7ec990d
476094d
7ec990d
 
476094d
 
 
7ec990d
 
476094d
 
7ec990d
 
 
 
 
 
 
476094d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ec990d
 
 
 
 
 
476094d
 
 
 
 
 
 
 
7ec990d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476094d
 
 
7ec990d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476094d
 
 
7ec990d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476094d
7ec990d
 
 
476094d
7ec990d
 
476094d
 
 
7ec990d
 
 
 
 
 
 
 
 
 
476094d
 
 
 
 
 
 
 
 
 
 
7ec990d
476094d
 
 
 
 
 
 
 
 
 
7ec990d
476094d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import { constants as fsConstants } from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";

import { decryptJson, encryptJson } from "../shared/pool-crypto.mjs";
import { maskSecret } from "../shared/secret-sanitizer.mjs";
import { PoolStore } from "../ui-server/pool-store.mjs";

function makeDefinitions(resolveFilePath) {
  return [
    {
      id: "codex-accounts",
      label: "Codex 账号池",
      category: "accounts",
      provider: "codex",
      filePath: resolveFilePath("pools/codex-accounts.enc"),
      storagePath: "pools/codex-accounts.enc",
    },
    {
      id: "codex-api",
      label: "Codex API 池",
      category: "api",
      provider: "codex",
      filePath: resolveFilePath("pools/codex-api.enc"),
      storagePath: "pools/codex-api.enc",
    },
    {
      id: "claude-code-api",
      label: "Claude Code API 池",
      category: "api",
      provider: "claude-code",
      filePath: resolveFilePath("pools/claude-code-api.enc"),
      storagePath: "pools/claude-code-api.enc",
    },
  ];
}

async function fileExists(filePath) {
  try {
    await fs.access(filePath);
    return true;
  } catch {
    return false;
  }
}

function maskCodexAccount(item) {
  const tokenSource = item?.tokens && typeof item.tokens === "object" ? item.tokens : {};
  return {
    ...item,
    OPENAI_API_KEY: "",
    OPENAI_API_KEY_MASKED: item?.OPENAI_API_KEY ? maskSecret(item.OPENAI_API_KEY) : "",
    tokens: {
      ...tokenSource,
      access_token: "",
      id_token: "",
      refresh_token: "",
      access_token_masked: tokenSource.access_token ? maskSecret(tokenSource.access_token) : "",
      id_token_masked: tokenSource.id_token ? maskSecret(tokenSource.id_token) : "",
      refresh_token_masked: tokenSource.refresh_token ? maskSecret(tokenSource.refresh_token) : "",
    },
  };
}

function maskApiItem(item) {
  return {
    ...item,
    apiKey: "",
    apiKeyMasked: item?.apiKey ? maskSecret(item.apiKey) : "",
  };
}

function mergeAccountSecrets(item, previous = {}) {
  const nextTokens = item?.tokens && typeof item.tokens === "object" ? item.tokens : {};
  const prevTokens = previous?.tokens && typeof previous.tokens === "object" ? previous.tokens : {};
  return {
    ...item,
    OPENAI_API_KEY: item?.OPENAI_API_KEY || previous?.OPENAI_API_KEY || "",
    tokens: {
      ...nextTokens,
      access_token: nextTokens.access_token || prevTokens.access_token || "",
      id_token: nextTokens.id_token || prevTokens.id_token || "",
      refresh_token: nextTokens.refresh_token || prevTokens.refresh_token || "",
    },
  };
}

function mergeApiSecrets(item, previous = {}) {
  return {
    ...item,
    apiKey: item?.apiKey || previous?.apiKey || "",
  };
}

class LocalFsStorageBackend {
  constructor({ dataDir }) {
    this.dataDir = dataDir;
    this.storageBackend = path.resolve(dataDir) === "/data" ? "bucket-mounted-fs" : "local-fs";
    this.readOnly = false;
    this.readOnlyReason = "";
  }

  describeLocation(relativePath) {
    return path.join(this.dataDir, relativePath);
  }

  resolvePath(relativePath) {
    return path.join(this.dataDir, relativePath);
  }

  async init() {
    if (path.resolve(this.dataDir) === "/data") {
      try {
        const stat = await fs.stat(this.dataDir);
        if (!stat.isDirectory()) {
          this.readOnly = true;
          this.readOnlyReason = "DATA_DIR is not a directory.";
          return;
        }
        await fs.access(this.dataDir, fsConstants.R_OK | fsConstants.W_OK);
      } catch {
        this.readOnly = true;
        this.readOnlyReason = "Storage bucket is not mounted at /data.";
        return;
      }
    } else {
      await fs.mkdir(this.dataDir, { recursive: true });
    }

    await fs.mkdir(path.join(this.dataDir, "pools"), { recursive: true });
    await fs.mkdir(path.join(this.dataDir, "config"), { recursive: true });
  }

  async exists(relativePath) {
    return fileExists(this.resolvePath(relativePath));
  }

  async readText(relativePath) {
    return fs.readFile(this.resolvePath(relativePath), "utf8");
  }

  async writeText(relativePath, content) {
    const filePath = this.resolvePath(relativePath);
    await fs.mkdir(path.dirname(filePath), { recursive: true });
    await fs.writeFile(filePath, content, "utf8");
    return filePath;
  }

  async stat(relativePath) {
    return fs.stat(this.resolvePath(relativePath));
  }
}

class HfDatasetStorageBackend {
  constructor({
    dataDir,
    repoId,
    token,
    branch = "main",
    fetchFn = globalThis.fetch,
  }) {
    this.dataDir = dataDir;
    this.repoId = repoId;
    this.token = token;
    this.branch = branch;
    this.fetchFn = fetchFn;
    this.storageBackend = "hf-dataset";
    this.readOnly = false;
    this.readOnlyReason = "";
    this.fileMeta = new Map();
  }

  describeLocation(relativePath) {
    return `hf://datasets/${this.repoId}/${this.branch}/${relativePath}`;
  }

  headers(extra = {}) {
    return {
      authorization: `Bearer ${this.token}`,
      ...extra,
    };
  }

  resolveUrl(relativePath) {
    return `https://huggingface.co/datasets/${this.repoId}/resolve/${encodeURIComponent(this.branch)}/${relativePath}`;
  }

  commitUrl() {
    return `https://huggingface.co/api/datasets/${this.repoId}/commit/${encodeURIComponent(this.branch)}`;
  }

  async request(url, options = {}) {
    const response = await this.fetchFn(url, options);
    return response;
  }

  async init() {
    await fs.mkdir(this.dataDir, { recursive: true });

    if (!this.repoId) {
      this.readOnly = true;
      this.readOnlyReason = "HF_DATASET_REPO is required when using the hf dataset backend.";
      return;
    }
    if (!this.token) {
      this.readOnly = true;
      this.readOnlyReason = "HF_TOKEN is required to read and write the private hf dataset.";
      return;
    }

    try {
      const response = await this.request(
        `https://huggingface.co/api/datasets/${this.repoId}`,
        { headers: this.headers() },
      );
      if (!response.ok) {
        throw new Error(`Dataset API returned ${response.status}`);
      }
    } catch (error) {
      this.readOnly = true;
      this.readOnlyReason = `Unable to sync private hf dataset: ${error?.message || String(error)}`;
    }
  }

  async exists(relativePath) {
    const response = await this.request(this.resolveUrl(relativePath), {
      method: "HEAD",
      headers: this.headers(),
    });
    if (response.ok) {
      const lastModified = response.headers.get("last-modified");
      this.fileMeta.set(relativePath, {
        mtime: lastModified ? new Date(lastModified) : new Date(),
      });
      return true;
    }
    if (response.status === 404) {
      this.fileMeta.delete(relativePath);
      return false;
    }
    throw new Error(`Failed to check dataset file ${relativePath}: ${response.status}`);
  }

  async readText(relativePath) {
    const response = await this.request(this.resolveUrl(relativePath), {
      headers: this.headers(),
    });
    if (response.status === 404) {
      const error = new Error(`Dataset file not found: ${relativePath}`);
      error.statusCode = 404;
      throw error;
    }
    if (!response.ok) {
      throw new Error(`Failed to read dataset file ${relativePath}: ${response.status}`);
    }
    const lastModified = response.headers.get("last-modified");
    this.fileMeta.set(relativePath, {
      mtime: lastModified ? new Date(lastModified) : new Date(),
    });
    return response.text();
  }

  async writeText(relativePath, content) {
    const payload = [
      {
        key: "header",
        value: {
          summary: `Update ${relativePath}`,
          description: "",
        },
      },
      {
        key: "file",
        value: {
          content: Buffer.from(content, "utf8").toString("base64"),
          path: relativePath,
          encoding: "base64",
        },
      },
    ]
      .map((item) => JSON.stringify(item))
      .join("\n");

    const response = await this.request(this.commitUrl(), {
      method: "POST",
      headers: this.headers({
        "content-type": "application/x-ndjson",
      }),
      body: `${payload}\n`,
    });
    if (!response.ok) {
      const message = await response.text();
      throw new Error(`Failed to write dataset file ${relativePath}: ${response.status} ${message}`.trim());
    }
    this.fileMeta.set(relativePath, { mtime: new Date() });
    return this.describeLocation(relativePath);
  }

  async stat(relativePath) {
    const meta = this.fileMeta.get(relativePath);
    if (meta?.mtime) {
      return { mtime: meta.mtime };
    }
    if (await this.exists(relativePath)) {
      return { mtime: this.fileMeta.get(relativePath)?.mtime || new Date() };
    }
    const error = new Error(`Dataset file not found: ${relativePath}`);
    error.statusCode = 404;
    throw error;
  }
}

export class EncryptedPoolStore {
  constructor({
    dataDir,
    cryptoKey,
    storageBackend = "local-fs",
    hfDatasetRepo = "",
    hfToken = "",
    hfDatasetBranch = "main",
    fetchFn,
  }) {
    this.dataDir = dataDir;
    this.cryptoKey = cryptoKey;
    this.backend =
      storageBackend === "hf-dataset"
        ? new HfDatasetStorageBackend({
            dataDir,
            repoId: hfDatasetRepo,
            token: hfToken,
            branch: hfDatasetBranch,
            fetchFn,
          })
        : new LocalFsStorageBackend({ dataDir });
    this.definitions = makeDefinitions((relativePath) => this.backend.describeLocation(relativePath));
    this.validator = new PoolStore(this.definitions);
    this.readOnly = false;
    this.readOnlyReason = "";
    this.storageBackend = this.backend.storageBackend;
  }

  async init() {
    if (!this.cryptoKey) {
      throw new Error("POOL_CRYPTO_KEY is required.");
    }
    await this.backend.init();
    this.readOnly = this.backend.readOnly;
    this.readOnlyReason = this.backend.readOnlyReason;
    this.storageBackend = this.backend.storageBackend;
  }

  listPools() {
    return this.definitions.map((item) => ({
      id: item.id,
      label: item.label,
      category: item.category,
      provider: item.provider,
      filePath: item.filePath,
    }));
  }

  getDefinition(poolId) {
    const definition = this.definitions.find((item) => item.id === poolId) || null;
    if (!definition) {
      const error = new Error(`Unknown pool: ${poolId}`);
      error.statusCode = 404;
      throw error;
    }
    return definition;
  }

  async loadRawPoolItems(poolId) {
    const definition = this.getDefinition(poolId);
    if (!(await this.backend.exists(definition.storagePath))) {
      return [];
    }
    const encrypted = await this.backend.readText(definition.storagePath);
    const items = decryptJson(encrypted, this.cryptoKey);
    return Array.isArray(items) ? items : [];
  }

  maskItems(poolId, items) {
    if (poolId === "codex-accounts") {
      return items.map(maskCodexAccount);
    }
    return items.map(maskApiItem);
  }

  async loadPool(poolId) {
    const definition = this.getDefinition(poolId);
    const items = await this.loadRawPoolItems(poolId);
    let savedAt = null;
    if (await this.backend.exists(definition.storagePath)) {
      const stat = await this.backend.stat(definition.storagePath);
      savedAt = stat.mtime.toISOString();
    }

    return {
      pool: {
        id: definition.id,
        label: definition.label,
        category: definition.category,
        provider: definition.provider,
        filePath: definition.filePath,
      },
      items: this.maskItems(poolId, items),
      savedAt,
      readOnly: this.readOnly,
      readOnlyReason: this.readOnlyReason,
      storageBackend: this.storageBackend,
    };
  }

  async mergeSecrets(poolId, items) {
    const previousItems = await this.loadRawPoolItems(poolId);
    return items.map((item, index) => {
      const previous = previousItems[index] || {};
      if (poolId === "codex-accounts") {
        return mergeAccountSecrets(item, previous);
      }
      return mergeApiSecrets(item, previous);
    });
  }

  async validatePoolItems(poolId, items) {
    const mergedItems = await this.mergeSecrets(poolId, items);
    return this.validator.validatePoolItems(poolId, mergedItems);
  }

  async writeEncryptedPool(poolId, items) {
    if (this.readOnly) {
      const error = new Error(this.readOnlyReason || "Encrypted pool store is read-only.");
      error.statusCode = 503;
      throw error;
    }
    const definition = this.getDefinition(poolId);
    const encrypted = encryptJson(items, this.cryptoKey);
    await this.backend.writeText(definition.storagePath, `${encrypted}\n`);
    return definition.filePath;
  }

  async savePool(poolId, items) {
    const definition = this.getDefinition(poolId);
    const validation = await this.validatePoolItems(poolId, items);
    if (!validation.ok) {
      const error = new Error("Pool validation failed");
      error.statusCode = 400;
      error.details = validation.errors;
      throw error;
    }

    await this.writeEncryptedPool(poolId, validation.normalizedItems);
    const stat = await this.backend.stat(definition.storagePath);
    return {
      pool: {
        id: definition.id,
        label: definition.label,
        category: definition.category,
        provider: definition.provider,
        filePath: definition.filePath,
      },
      items: this.maskItems(poolId, validation.normalizedItems),
      savedAt: stat.mtime.toISOString(),
      count: validation.normalizedItems.length,
      readOnly: this.readOnly,
      readOnlyReason: this.readOnlyReason,
      storageBackend: this.storageBackend,
    };
  }

  async importPool(poolId, items) {
    return this.savePool(poolId, items);
  }

  runtimeConfigPath(configId) {
    return `config/${configId}.json`;
  }

  async loadRuntimeConfig(configId, defaults = {}) {
    const filePath = this.runtimeConfigPath(configId);
    if (!(await this.backend.exists(filePath))) {
      return { ...defaults };
    }
    const content = await this.backend.readText(filePath);
    const parsed = JSON.parse(content);
    return {
      ...defaults,
      ...(parsed && typeof parsed === "object" ? parsed : {}),
    };
  }

  async saveRuntimeConfig(configId, value) {
    if (this.readOnly) {
      const error = new Error(this.readOnlyReason || "Encrypted pool store is read-only.");
      error.statusCode = 503;
      throw error;
    }
    const filePath = this.runtimeConfigPath(configId);
    await this.backend.writeText(filePath, `${JSON.stringify(value, null, 2)}\n`);
    return value;
  }
}