@seaveyon/harness-switch 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +20 -3
  2. package/dist/harness-switch.js +407 -51
  3. package/package.json +1 -1
  4. package/public/06ac09dcb8ec7d56.woff2 +0 -0
  5. package/public/110e2a7693b4a5f3.woff2 +0 -0
  6. package/public/192d14b24f70b621.woff2 +0 -0
  7. package/public/2258ff2f7eae77c2.woff +0 -0
  8. package/public/2a0db5363856276c.woff2 +0 -0
  9. package/public/5a49cbe35ab2dd3c.woff2 +0 -0
  10. package/public/60bbe6c85a6afad1.woff2 +0 -0
  11. package/public/651bc97e3669e21f.woff2 +0 -0
  12. package/public/66a2e8650a2dcd92.woff2 +0 -0
  13. package/public/7d495472d32ca07d.woff +0 -0
  14. package/public/88f8fd5b09b976bb.woff +0 -0
  15. package/public/9533b5204f120066.woff +0 -0
  16. package/public/994c96595d20046b.woff +0 -0
  17. package/public/9faee8e8b774991c.woff2 +0 -0
  18. package/public/a7358d2e3dd919a9.woff2 +0 -0
  19. package/public/a8a9073d6f10c294.woff2 +0 -0
  20. package/public/assets/{4952.5b132c3d.js → 4952.58f3b893.js} +1 -1
  21. package/public/assets/{5646.a72b2c1e.js → 5646.1b33e69c.js} +1 -1
  22. package/public/assets/{6150.910aaed9.js → 6150.5cb126a5.js} +1 -1
  23. package/public/assets/main.5b6d51f1.css +2 -0
  24. package/public/assets/main.5e14383f.js +1 -0
  25. package/public/b0b919fcf36c2073.woff2 +0 -0
  26. package/public/bdc4ddcb892cb87b.woff2 +0 -0
  27. package/public/cd8df815c9344be0.woff2 +0 -0
  28. package/public/d2ac083e197becc1.woff +0 -0
  29. package/public/dece0821e8ed059f.woff2 +0 -0
  30. package/public/e32cf7a40c90e778.woff +0 -0
  31. package/public/e53d79b9a7d8ae7b.woff +0 -0
  32. package/public/ef1c8a30e0ed6275.woff2 +0 -0
  33. package/public/f14ffb91743624fd.woff +0 -0
  34. package/public/f9f2cfdc8f44d943.woff +0 -0
  35. package/public/index.html +1 -1
  36. package/public/assets/main.9128def8.css +0 -2
  37. package/public/assets/main.95434834.js +0 -1
@@ -9034,7 +9034,7 @@ var deleteCookie = (c, name, opt) => {
9034
9034
  };
9035
9035
 
9036
9036
  // src/services/auth.ts
9037
- import { randomBytes as randomBytes3 } from "crypto";
9037
+ import { createHash, randomBytes as randomBytes3 } from "crypto";
9038
9038
 
9039
9039
  // src/di/collection.ts
9040
9040
  class ServiceCollection {
@@ -9195,14 +9195,15 @@ class EnvironmentService {
9195
9195
  homeDir = process.env.HSW_HOME_DIR || homedir();
9196
9196
  dataDir = process.env.HSW_DATA_DIR || join2(this.homeDir, ".harness-switch");
9197
9197
  publicDir = process.env.HSW_PUBLIC_DIR || resolvePublicDir();
9198
- sessionTtlMs = 24 * 60 * 60 * 1000;
9198
+ sessionTtlMs = resolveSessionTtlMs();
9199
9199
  cookieName = "hsw_session";
9200
9200
  files = {
9201
9201
  profiles: join2(this.dataDir, "profiles.json"),
9202
9202
  active: join2(this.dataDir, "active.json"),
9203
9203
  password: join2(this.dataDir, "web_password"),
9204
9204
  key: join2(this.dataDir, "aes-256-gcm.key"),
9205
- env: join2(this.dataDir, "env.sh")
9205
+ env: join2(this.dataDir, "env.sh"),
9206
+ sessions: join2(this.dataDir, "sessions.json")
9206
9207
  };
9207
9208
  backupsDir = join2(this.dataDir, "backups");
9208
9209
  backupRetainCount = Math.max(1, Number(process.env.HSW_BACKUP_RETAIN || 10));
@@ -9217,6 +9218,10 @@ class EnvironmentService {
9217
9218
  mkdirSync(this.dataDir, { recursive: true, mode: 448 });
9218
9219
  }
9219
9220
  }
9221
+ function resolveSessionTtlMs() {
9222
+ const hours = Number(process.env.HSW_SESSION_TTL_HOURS || 24);
9223
+ return (Number.isFinite(hours) && hours > 0 ? hours : 24) * 60 * 60 * 1000;
9224
+ }
9220
9225
  function resolvePublicDir() {
9221
9226
  const candidates = [
9222
9227
  join2(import.meta.dir, "../public"),
@@ -9239,7 +9244,7 @@ import {
9239
9244
  statSync,
9240
9245
  writeFileSync
9241
9246
  } from "fs";
9242
- import { dirname as dirname2 } from "path";
9247
+ import { basename, dirname as dirname2 } from "path";
9243
9248
  var IFileService = createDecorator("fileService");
9244
9249
  var _dec = [
9245
9250
  inject(IEnvironmentService)
@@ -9260,8 +9265,33 @@ class FileService {
9260
9265
  readOptional(file) {
9261
9266
  try {
9262
9267
  return readFileSync(file, "utf8");
9268
+ } catch (error) {
9269
+ if (error.code === "ENOENT") {
9270
+ return;
9271
+ }
9272
+ throw error;
9273
+ }
9274
+ }
9275
+ readJsonStrict(file, fallback) {
9276
+ if (!existsSync2(file)) {
9277
+ return fallback;
9278
+ }
9279
+ let text;
9280
+ try {
9281
+ text = this.readText(file);
9263
9282
  } catch {
9264
- return;
9283
+ throw new HttpError(500, `\u6570\u636E\u5B58\u50A8\u4E0D\u53EF\u8BFB\uFF1A${file}`);
9284
+ }
9285
+ try {
9286
+ return JSON.parse(text);
9287
+ } catch {
9288
+ const quarantine = `${file}.corrupt-${Date.now()}`;
9289
+ try {
9290
+ renameSync(file, quarantine);
9291
+ } catch {
9292
+ throw new HttpError(500, `\u6570\u636E\u5B58\u50A8\u635F\u574F\u4E14\u65E0\u6CD5\u9694\u79BB\uFF1A${file}`);
9293
+ }
9294
+ throw new HttpError(500, `\u6570\u636E\u5B58\u50A8\u5DF2\u635F\u574F\uFF0C\u539F\u6587\u4EF6\u5DF2\u9694\u79BB\u4E3A ${basename(quarantine)}\uFF0C\u8BF7\u4ECE\u5907\u4EFD\u6062\u590D\u540E\u518D\u7EE7\u7EED`);
9265
9295
  }
9266
9296
  }
9267
9297
  writeSecure(file, text) {
@@ -9404,6 +9434,7 @@ class LogService {
9404
9434
  }
9405
9435
 
9406
9436
  // src/services/auth.ts
9437
+ var STORE_VERSION = 1;
9407
9438
  var IAuthService = createDecorator("authService");
9408
9439
  var _dec = [
9409
9440
  inject(IEnvironmentService, IFileService, ICryptoService, ILogService)
@@ -9415,7 +9446,8 @@ class AuthService {
9415
9446
  files;
9416
9447
  crypto;
9417
9448
  log;
9418
- sessions = new Map;
9449
+ sessions;
9450
+ fingerprint = "";
9419
9451
  constructor(environment, files, crypto2, log) {
9420
9452
  this.environment = environment;
9421
9453
  this.files = files;
@@ -9438,30 +9470,77 @@ class AuthService {
9438
9470
  return null;
9439
9471
  }
9440
9472
  const token = randomBytes3(32).toString("base64url");
9441
- this.sessions.set(token, { expires: Date.now() + this.environment.sessionTtlMs });
9473
+ this.load().set(digest("session", token), {
9474
+ expires: Date.now() + this.environment.sessionTtlMs
9475
+ });
9476
+ this.persist();
9442
9477
  return token;
9443
9478
  }
9444
9479
  logout(token) {
9445
- if (token) {
9446
- this.sessions.delete(token);
9480
+ if (token && this.load().delete(digest("session", token))) {
9481
+ this.persist();
9447
9482
  }
9448
9483
  }
9449
9484
  isAuthenticated(token) {
9450
9485
  if (!token) {
9451
9486
  return false;
9452
9487
  }
9453
- const session = this.sessions.get(token);
9488
+ const sessions = this.load();
9489
+ const key = digest("session", token);
9490
+ const session = sessions.get(key);
9454
9491
  if (!session || session.expires < Date.now()) {
9455
- this.sessions.delete(token);
9492
+ if (sessions.delete(key)) {
9493
+ this.persist();
9494
+ }
9456
9495
  return false;
9457
9496
  }
9458
9497
  return true;
9459
9498
  }
9499
+ load() {
9500
+ const loaded = this.sessions;
9501
+ if (loaded) {
9502
+ return loaded;
9503
+ }
9504
+ this.fingerprint = digest("password", this.ensurePassword());
9505
+ const store = this.files.readJson(this.environment.files.sessions, {
9506
+ version: STORE_VERSION,
9507
+ password: this.fingerprint,
9508
+ sessions: {}
9509
+ });
9510
+ const sessions = new Map;
9511
+ if (store.version === STORE_VERSION && store.password === this.fingerprint) {
9512
+ const now = Date.now();
9513
+ for (const [key, session] of Object.entries(store.sessions ?? {})) {
9514
+ if (typeof session?.expires === "number" && session.expires > now) {
9515
+ sessions.set(key, { expires: session.expires });
9516
+ }
9517
+ }
9518
+ }
9519
+ this.sessions = sessions;
9520
+ if (sessions.size > 0) {
9521
+ this.log.info(`restored ${sessions.size} web session(s)`);
9522
+ }
9523
+ return sessions;
9524
+ }
9525
+ persist() {
9526
+ const sessions = this.sessions;
9527
+ if (!sessions) {
9528
+ return;
9529
+ }
9530
+ this.files.writeJson(this.environment.files.sessions, {
9531
+ version: STORE_VERSION,
9532
+ password: this.fingerprint,
9533
+ sessions: Object.fromEntries(sessions)
9534
+ });
9535
+ }
9460
9536
  }
9461
9537
  AuthService = __decorateElement(_init, 0, "AuthService", _dec, AuthService);
9462
9538
  __runInitializers(_init, 1, AuthService);
9463
9539
  __decoratorMetadata(_init, AuthService);
9464
9540
  let _AuthService = AuthService;
9541
+ function digest(kind, value) {
9542
+ return createHash("sha256").update(`${kind}:${value}`).digest("base64url");
9543
+ }
9465
9544
 
9466
9545
  // src/http/middleware.ts
9467
9546
  function createServiceMiddleware(services) {
@@ -9532,7 +9611,7 @@ function createAuthRoutes(services) {
9532
9611
  }
9533
9612
 
9534
9613
  // src/services/backup.ts
9535
- import { basename, join as join3 } from "path";
9614
+ import { basename as basename2, join as join3 } from "path";
9536
9615
  var IBackupService = createDecorator("backupService");
9537
9616
  var MANIFEST = "manifest.json";
9538
9617
  var _dec = [
@@ -9558,7 +9637,7 @@ class BackupService {
9558
9637
  if (snapshot.content === undefined) {
9559
9638
  return { path: snapshot.path, existed: false };
9560
9639
  }
9561
- const name = `${index}-${basename(snapshot.path)}`;
9640
+ const name = `${index}-${basename2(snapshot.path)}`;
9562
9641
  this.files.writeSecure(join3(dir, name), snapshot.content);
9563
9642
  return { path: snapshot.path, existed: true, stored: name };
9564
9643
  });
@@ -11166,28 +11245,19 @@ class CodexAdapter {
11166
11245
  }
11167
11246
  return rendered;
11168
11247
  }
11169
- renderOfficial(profile, current) {
11248
+ renderOfficial(_profile, current) {
11170
11249
  const config = parseTomlObject(current[CONFIG]);
11171
- const activeProviderId = readString(config, "model_provider");
11172
11250
  delete config.model_provider;
11173
11251
  delete config.model;
11174
11252
  delete config.model_reasoning_effort;
11175
- if (isPlainObject(config.model_providers)) {
11176
- if (profile) {
11177
- delete config.model_providers[this.providerId(profile)];
11178
- }
11179
- if (activeProviderId) {
11180
- delete config.model_providers[activeProviderId];
11181
- }
11182
- if (Object.keys(config.model_providers).length === 0) {
11183
- delete config.model_providers;
11184
- }
11185
- }
11253
+ delete config.model_providers;
11186
11254
  const rendered = { [CONFIG]: stringifyToml(config) };
11187
- if (profile && this.authMode(profile) === "openai_auth") {
11255
+ if (current[AUTH] !== undefined) {
11188
11256
  const auth = parseJsonObject(current[AUTH]);
11189
- delete auth[DEFAULT_ENV_KEY];
11190
- rendered[AUTH] = stringifyJson(auth);
11257
+ if (DEFAULT_ENV_KEY in auth) {
11258
+ delete auth[DEFAULT_ENV_KEY];
11259
+ rendered[AUTH] = stringifyJson(auth);
11260
+ }
11191
11261
  }
11192
11262
  return rendered;
11193
11263
  }
@@ -11998,7 +12068,7 @@ class ProfileService {
11998
12068
  this.files.writeJson(this.environment.files.profiles, store);
11999
12069
  }
12000
12070
  read() {
12001
- return this.files.readJson(this.environment.files.profiles, {});
12071
+ return this.files.readJsonStrict(this.environment.files.profiles, {});
12002
12072
  }
12003
12073
  toPublic(harness, name, profile) {
12004
12074
  return {
@@ -12171,14 +12241,10 @@ class ActivationService {
12171
12241
  if (!adapter.revoke) {
12172
12242
  return;
12173
12243
  }
12174
- try {
12175
- const profile = this.profiles.decrypt(harness, name);
12176
- const targets = adapter.targets();
12177
- const rendered = adapter.revoke(profile, this.readCurrent(targets));
12178
- this.liveWrite.apply(harness, name, this.toWrites(targets, rendered));
12179
- } catch (error) {
12180
- this.log.error(`failed to revoke ${harness}/${name} from live config`, error);
12181
- }
12244
+ const profile = this.profiles.decrypt(harness, name);
12245
+ const targets = adapter.targets();
12246
+ const rendered = adapter.revoke(profile, this.readCurrent(targets));
12247
+ this.liveWrite.apply(harness, name, this.toWrites(targets, rendered));
12182
12248
  }
12183
12249
  backfillPrevious(adapter, previous, nextName, warnings) {
12184
12250
  if (!adapter.backfill || !previous || previous.official || previous.name === nextName) {
@@ -12230,7 +12296,7 @@ class ActivationService {
12230
12296
  return current;
12231
12297
  }
12232
12298
  read() {
12233
- return this.files.readJson(this.environment.files.active, {});
12299
+ return this.files.readJsonStrict(this.environment.files.active, {});
12234
12300
  }
12235
12301
  writeEnv(active) {
12236
12302
  const lines = [
@@ -12289,6 +12355,8 @@ function createHarnessRoutes(services) {
12289
12355
  const activation = services.get(IActivationService);
12290
12356
  const adapters = services.get(IAdapterRegistry);
12291
12357
  const environment = services.get(IEnvironmentService);
12358
+ const files = services.get(IFileService);
12359
+ const log = services.get(ILogService);
12292
12360
  function summary(id) {
12293
12361
  const adapter = adapters.get(id);
12294
12362
  return {
@@ -12327,18 +12395,36 @@ function createHarnessRoutes(services) {
12327
12395
  const harnessId = harnesses.require(c.req.param("harnessId"));
12328
12396
  const name = decodeURIComponent(c.req.param("name"));
12329
12397
  const body = await readBody(c.req.json.bind(c.req));
12330
- const profile = profiles.upsert(harnessId, {
12331
- name: String(body.name ?? name),
12332
- sourceName: name,
12333
- baseUrl: body.baseUrl,
12334
- apiKey: body.apiKey,
12335
- model: body.model,
12336
- notes: body.notes,
12337
- extras: body.extras,
12338
- overrides: body.overrides
12339
- }, false);
12340
- activation.reconcileProfileUpdate(harnessId, name, profile.name);
12341
- return c.json(profile);
12398
+ const wasActive = activation.getActive(harnessId)?.name === name;
12399
+ const snapshot = files.readOptional(environment.files.profiles);
12400
+ let persisted = false;
12401
+ try {
12402
+ const profile = profiles.upsert(harnessId, {
12403
+ name: String(body.name ?? name),
12404
+ sourceName: name,
12405
+ baseUrl: body.baseUrl,
12406
+ apiKey: body.apiKey,
12407
+ model: body.model,
12408
+ notes: body.notes,
12409
+ extras: body.extras,
12410
+ overrides: body.overrides
12411
+ }, false);
12412
+ persisted = true;
12413
+ activation.reconcileProfileUpdate(harnessId, name, profile.name);
12414
+ return c.json(profile);
12415
+ } catch (error) {
12416
+ if (persisted) {
12417
+ restoreProfileStore(files, environment.files.profiles, snapshot);
12418
+ if (wasActive) {
12419
+ try {
12420
+ activation.activate(harnessId, name);
12421
+ } catch (rollbackError) {
12422
+ log.error(`edit rollback: failed to re-activate ${harnessId}/${name}`, rollbackError);
12423
+ }
12424
+ }
12425
+ }
12426
+ throw error;
12427
+ }
12342
12428
  });
12343
12429
  app.delete("/:harnessId/profiles/:name", (c) => {
12344
12430
  const harnessId = harnesses.require(c.req.param("harnessId"));
@@ -12370,6 +12456,273 @@ async function readBody(read) {
12370
12456
  throw new HttpError(400, "invalid json");
12371
12457
  });
12372
12458
  }
12459
+ function restoreProfileStore(files, path, snapshot) {
12460
+ if (snapshot === undefined) {
12461
+ files.remove(path);
12462
+ return;
12463
+ }
12464
+ files.writeSecure(path, snapshot);
12465
+ }
12466
+
12467
+ // src/services/transfer.ts
12468
+ import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes4, scryptSync } from "crypto";
12469
+ var FORMAT = "harness-switch-encrypted-export";
12470
+ var VERSION = 1;
12471
+ var MAX_ENCRYPTED_BYTES = 10 * 1024 * 1024;
12472
+ var ITransferService = createDecorator("transferService");
12473
+ var _dec = [
12474
+ inject(IEnvironmentService, IFileService, ICryptoService, IAdapterRegistry, IActivationService)
12475
+ ];
12476
+ var _init = __decoratorStart(undefined);
12477
+
12478
+ class TransferService {
12479
+ environment;
12480
+ files;
12481
+ crypto;
12482
+ adapters;
12483
+ activation;
12484
+ constructor(environment, files, crypto2, adapters, activation) {
12485
+ this.environment = environment;
12486
+ this.files = files;
12487
+ this.crypto = crypto2;
12488
+ this.adapters = adapters;
12489
+ this.activation = activation;
12490
+ }
12491
+ exportAll(passphrase) {
12492
+ this.assertPassphrase(passphrase);
12493
+ const store = this.readStore();
12494
+ const profiles = [];
12495
+ for (const harness of HARNESS_IDS) {
12496
+ for (const [name, stored] of Object.entries(store[harness] ?? {})) {
12497
+ profiles.push({
12498
+ harness,
12499
+ name,
12500
+ baseUrl: stored.base_url || "",
12501
+ apiKey: this.crypto.decrypt(stored.api_key),
12502
+ model: stored.model || "",
12503
+ notes: stored.notes || "",
12504
+ extras: stored.extras ?? {},
12505
+ overrides: stored.overrides ?? {}
12506
+ });
12507
+ }
12508
+ }
12509
+ const active = HARNESS_IDS.flatMap((harness) => {
12510
+ const entry = this.activation.getActive(harness);
12511
+ return entry ? [
12512
+ {
12513
+ harness,
12514
+ name: entry.name,
12515
+ official: entry.official === true
12516
+ }
12517
+ ] : [];
12518
+ });
12519
+ return encrypt({
12520
+ format: "harness-switch-portable-config",
12521
+ version: VERSION,
12522
+ exportedAt: new Date().toISOString(),
12523
+ profiles,
12524
+ active
12525
+ }, passphrase);
12526
+ }
12527
+ preview(envelope, passphrase) {
12528
+ const payload = this.decrypt(envelope, passphrase);
12529
+ const store = this.readStore();
12530
+ return {
12531
+ exportedAt: payload.exportedAt,
12532
+ profileCount: payload.profiles.length,
12533
+ harnesses: HARNESS_IDS.map((harness) => ({
12534
+ harness,
12535
+ profiles: payload.profiles.filter((profile) => profile.harness === harness).length
12536
+ })).filter((item) => item.profiles > 0),
12537
+ conflicts: payload.profiles.filter((profile) => store[profile.harness]?.[profile.name] !== undefined).map(({ harness, name }) => ({ harness, name })),
12538
+ activeCount: payload.active.length
12539
+ };
12540
+ }
12541
+ importAll(envelope, passphrase, conflictPolicy, restoreActive) {
12542
+ if (conflictPolicy !== "skip" && conflictPolicy !== "overwrite") {
12543
+ throw new HttpError(400, "invalid conflict policy");
12544
+ }
12545
+ const payload = this.decrypt(envelope, passphrase);
12546
+ const store = structuredClone(this.readStore());
12547
+ let imported = 0;
12548
+ let overwritten = 0;
12549
+ let skipped = 0;
12550
+ for (const profile of payload.profiles) {
12551
+ this.validateProfile(profile);
12552
+ store[profile.harness] ||= {};
12553
+ const exists = store[profile.harness][profile.name] !== undefined;
12554
+ if (exists && conflictPolicy === "skip") {
12555
+ skipped++;
12556
+ continue;
12557
+ }
12558
+ store[profile.harness][profile.name] = this.toStored(profile);
12559
+ if (exists) {
12560
+ overwritten++;
12561
+ } else {
12562
+ imported++;
12563
+ }
12564
+ }
12565
+ this.files.writeJson(this.environment.files.profiles, store);
12566
+ const warnings = [];
12567
+ let activeRestored = 0;
12568
+ if (restoreActive) {
12569
+ for (const active of payload.active) {
12570
+ try {
12571
+ if (active.official) {
12572
+ this.activation.activateOfficial(active.harness);
12573
+ } else if (store[active.harness]?.[active.name]) {
12574
+ this.activation.activate(active.harness, active.name);
12575
+ } else {
12576
+ throw new Error("\u5BF9\u5E94\u914D\u7F6E\u4E0D\u5B58\u5728");
12577
+ }
12578
+ activeRestored++;
12579
+ } catch (error) {
12580
+ warnings.push(`${active.harness}/${active.name} \u672A\u80FD\u6062\u590D\u6FC0\u6D3B\u72B6\u6001\uFF1A${error.message}`);
12581
+ }
12582
+ }
12583
+ }
12584
+ return { ok: true, imported, overwritten, skipped, activeRestored, warnings };
12585
+ }
12586
+ decrypt(envelope, passphrase) {
12587
+ this.assertPassphrase(passphrase);
12588
+ const payload = decrypt(envelope, passphrase);
12589
+ if (payload.format !== "harness-switch-portable-config" || payload.version !== VERSION || !Array.isArray(payload.profiles) || !Array.isArray(payload.active) || typeof payload.exportedAt !== "string") {
12590
+ throw new HttpError(400, "\u4E0D\u652F\u6301\u7684\u5BFC\u51FA\u6587\u4EF6\u683C\u5F0F");
12591
+ }
12592
+ if (payload.profiles.length > 1e4) {
12593
+ throw new HttpError(400, "\u5BFC\u51FA\u6587\u4EF6\u5305\u542B\u8FC7\u591A\u914D\u7F6E");
12594
+ }
12595
+ for (const profile of payload.profiles) {
12596
+ if (!isPortableProfile(profile)) {
12597
+ throw new HttpError(400, "\u5BFC\u51FA\u6587\u4EF6\u4E2D\u7684\u914D\u7F6E\u6570\u636E\u65E0\u6548");
12598
+ }
12599
+ }
12600
+ for (const active of payload.active) {
12601
+ if (!isPortableActive(active)) {
12602
+ throw new HttpError(400, "\u5BFC\u51FA\u6587\u4EF6\u4E2D\u7684\u6FC0\u6D3B\u72B6\u6001\u65E0\u6548");
12603
+ }
12604
+ }
12605
+ return payload;
12606
+ }
12607
+ validateProfile(profile) {
12608
+ if (!profile.name || profile.name.length > 120 || /[\\/]/.test(profile.name)) {
12609
+ throw new HttpError(400, "\u5BFC\u51FA\u6587\u4EF6\u5305\u542B\u65E0\u6548\u7684\u914D\u7F6E\u540D\u79F0");
12610
+ }
12611
+ this.adapters.get(profile.harness).validate?.({
12612
+ name: profile.name,
12613
+ baseUrl: profile.baseUrl,
12614
+ apiKey: profile.apiKey,
12615
+ model: profile.model,
12616
+ extras: profile.extras
12617
+ });
12618
+ }
12619
+ toStored(profile) {
12620
+ return {
12621
+ base_url: profile.baseUrl,
12622
+ api_key: this.crypto.encrypt(profile.apiKey),
12623
+ model: profile.model,
12624
+ notes: profile.notes,
12625
+ extras: profile.extras,
12626
+ overrides: profile.overrides,
12627
+ updated_at: new Date().toISOString()
12628
+ };
12629
+ }
12630
+ readStore() {
12631
+ return this.files.readJsonStrict(this.environment.files.profiles, {});
12632
+ }
12633
+ assertPassphrase(passphrase) {
12634
+ if (passphrase.length < 8) {
12635
+ throw new HttpError(400, "\u8FC1\u79FB\u5BC6\u7801\u81F3\u5C11\u9700\u8981 8 \u4E2A\u5B57\u7B26");
12636
+ }
12637
+ }
12638
+ }
12639
+ TransferService = __decorateElement(_init, 0, "TransferService", _dec, TransferService);
12640
+ __runInitializers(_init, 1, TransferService);
12641
+ __decoratorMetadata(_init, TransferService);
12642
+ let _TransferService = TransferService;
12643
+ function encrypt(payload, passphrase) {
12644
+ const salt = randomBytes4(16);
12645
+ const iv = randomBytes4(12);
12646
+ const key = scryptSync(passphrase, salt, 32);
12647
+ const cipher = createCipheriv2("aes-256-gcm", key, iv);
12648
+ const data = Buffer.concat([cipher.update(JSON.stringify(payload), "utf8"), cipher.final()]);
12649
+ return {
12650
+ format: FORMAT,
12651
+ version: VERSION,
12652
+ kdf: { name: "scrypt", salt: salt.toString("base64url") },
12653
+ cipher: {
12654
+ name: "aes-256-gcm",
12655
+ iv: iv.toString("base64url"),
12656
+ tag: cipher.getAuthTag().toString("base64url"),
12657
+ data: data.toString("base64url")
12658
+ }
12659
+ };
12660
+ }
12661
+ function decrypt(envelope, passphrase) {
12662
+ try {
12663
+ if (envelope?.format !== FORMAT || envelope.version !== VERSION || envelope.kdf?.name !== "scrypt" || envelope.cipher?.name !== "aes-256-gcm" || typeof envelope.kdf.salt !== "string" || typeof envelope.cipher.iv !== "string" || typeof envelope.cipher.tag !== "string" || typeof envelope.cipher.data !== "string" || envelope.cipher.data.length > MAX_ENCRYPTED_BYTES) {
12664
+ throw new Error("invalid envelope");
12665
+ }
12666
+ const salt = Buffer.from(envelope.kdf.salt, "base64url");
12667
+ const key = scryptSync(passphrase, salt, 32);
12668
+ const decipher = createDecipheriv2("aes-256-gcm", key, Buffer.from(envelope.cipher.iv, "base64url"));
12669
+ decipher.setAuthTag(Buffer.from(envelope.cipher.tag, "base64url"));
12670
+ const plain = Buffer.concat([
12671
+ decipher.update(Buffer.from(envelope.cipher.data, "base64url")),
12672
+ decipher.final()
12673
+ ]).toString("utf8");
12674
+ return JSON.parse(plain);
12675
+ } catch {
12676
+ throw new HttpError(400, "\u8FC1\u79FB\u5BC6\u7801\u9519\u8BEF\u6216\u5BFC\u51FA\u6587\u4EF6\u5DF2\u635F\u574F");
12677
+ }
12678
+ }
12679
+ function isStringRecord(value) {
12680
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((item) => typeof item === "string");
12681
+ }
12682
+ function isPortableProfile(value) {
12683
+ if (typeof value !== "object" || value === null) {
12684
+ return false;
12685
+ }
12686
+ const profile = value;
12687
+ return typeof profile.harness === "string" && isHarnessId(profile.harness) && typeof profile.name === "string" && typeof profile.baseUrl === "string" && typeof profile.apiKey === "string" && typeof profile.model === "string" && typeof profile.notes === "string" && isStringRecord(profile.extras) && isStringRecord(profile.overrides);
12688
+ }
12689
+ function isPortableActive(value) {
12690
+ if (typeof value !== "object" || value === null) {
12691
+ return false;
12692
+ }
12693
+ const active = value;
12694
+ return typeof active.harness === "string" && isHarnessId(active.harness) && typeof active.name === "string" && typeof active.official === "boolean";
12695
+ }
12696
+
12697
+ // src/http/routes/transfer.ts
12698
+ function createTransferRoutes(services) {
12699
+ const app = new Hono2;
12700
+ const transfer = services.get(ITransferService);
12701
+ app.post("/export", async (c) => {
12702
+ const body = await readBody2(c.req.json.bind(c.req));
12703
+ return c.json(transfer.exportAll(String(body.passphrase ?? "")));
12704
+ });
12705
+ app.post("/preview", async (c) => {
12706
+ const body = await readBody2(c.req.json.bind(c.req));
12707
+ return c.json(transfer.preview(requireEnvelope(body.envelope), String(body.passphrase ?? "")));
12708
+ });
12709
+ app.post("/import", async (c) => {
12710
+ const body = await readBody2(c.req.json.bind(c.req));
12711
+ return c.json(transfer.importAll(requireEnvelope(body.envelope), String(body.passphrase ?? ""), body.conflictPolicy ?? "skip", body.restoreActive === true));
12712
+ });
12713
+ return app;
12714
+ }
12715
+ function requireEnvelope(envelope) {
12716
+ if (!envelope || typeof envelope !== "object") {
12717
+ throw new HttpError(400, "\u7F3A\u5C11\u6709\u6548\u7684\u5BFC\u51FA\u6587\u4EF6");
12718
+ }
12719
+ return envelope;
12720
+ }
12721
+ async function readBody2(read) {
12722
+ return read().catch(() => {
12723
+ throw new HttpError(400, "invalid json");
12724
+ });
12725
+ }
12373
12726
 
12374
12727
  // src/app.ts
12375
12728
  function createApp(services) {
@@ -12387,6 +12740,8 @@ function createApp(services) {
12387
12740
  api.use("/backups/*", createAuthGuard(services));
12388
12741
  api.use("/backups", createAuthGuard(services));
12389
12742
  api.route("/backups", createBackupRoutes(services));
12743
+ api.use("/transfer/*", createAuthGuard(services));
12744
+ api.route("/transfer", createTransferRoutes(services));
12390
12745
  app.route("/api", api);
12391
12746
  const publicDir = environment.publicDir;
12392
12747
  if (existsSync3(publicDir)) {
@@ -12432,6 +12787,7 @@ function createServices() {
12432
12787
  collection.set(ILiveWriteService, new SyncDescriptor(LiveWriteService));
12433
12788
  collection.set(IProfileService, new SyncDescriptor(ProfileService));
12434
12789
  collection.set(IActivationService, new SyncDescriptor(ActivationService));
12790
+ collection.set(ITransferService, new SyncDescriptor(TransferService));
12435
12791
  return new InstantiationService(collection);
12436
12792
  }
12437
12793
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seaveyon/harness-switch",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "A secure web control plane that switches API providers for Claude Code, Codex, Kimi Code, Pi and DeepSeek Harness by writing their native config files on SSH servers.",
5
5
  "keywords": [
6
6
  "claude-code",
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -1 +1 @@
1
- "use strict";(self.webpackChunk_seaveyon_harness_switch_web=self.webpackChunk_seaveyon_harness_switch_web||[]).push([["4952"],{1419(e,n,l){l.r(n),l.d(n,{PierreFileDiff:()=>s});var t=l(1085),o=l(8437),r={themeType:"dark",theme:"pierre-dark",diffStyle:"unified",overflow:"wrap",expandUnchanged:!0,stickyHeader:!0};function s(e){var n=e.file,l=n.path,s=null===n.currentContent?null:{name:l,contents:n.currentContent},i=null===n.content?null:{name:l,contents:n.content};return null===s&&null===i?(0,t.jsx)("p",{className:"px-3 py-4 text-sm text-muted-foreground",children:"两侧都不存在"}):null===s?(0,t.jsx)(o.T,{disableWorkerPool:!0,oldFile:null,newFile:i,options:r}):null===i?(0,t.jsx)(o.T,{disableWorkerPool:!0,oldFile:s,newFile:null,options:r}):(0,t.jsx)(o.T,{disableWorkerPool:!0,oldFile:s,newFile:i,options:r})}}}]);
1
+ "use strict";(self.webpackChunk_seaveyon_harness_switch_web=self.webpackChunk_seaveyon_harness_switch_web||[]).push([["4952"],{1419(e,n,l){l.r(n),l.d(n,{PierreFileDiff:()=>s});var t=l(1085),o=l(8437),r={themeType:"dark",theme:"pierre-dark",diffStyle:"unified",overflow:"wrap",expandUnchanged:!0,stickyHeader:!0};function s(e){var n=e.file,l=n.path,s=null===n.currentContent?null:{name:l,contents:n.currentContent},i=null===n.content?null:{name:l,contents:n.content};return null!==s&&null!==i?(0,t.jsx)(o.T,{disableWorkerPool:!0,oldFile:s,newFile:i,options:r}):null!==s?(0,t.jsx)(o.T,{disableWorkerPool:!0,oldFile:s,newFile:null,options:r}):null!==i?(0,t.jsx)(o.T,{disableWorkerPool:!0,oldFile:null,newFile:i,options:r}):(0,t.jsx)("p",{className:"px-3 py-4 text-sm text-muted-foreground",children:"两侧都不存在"})}}}]);