@seaveyon/harness-switch 0.21.1 → 0.22.0

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.
@@ -8644,6 +8644,11 @@ var ERROR_CODES = {
8644
8644
  transferEnvelopeInvalid: "transfer.envelopeInvalid",
8645
8645
  syncSourceCacheMissing: "sync.sourceCodexLoginCacheMissing",
8646
8646
  syncSourceEqualsTarget: "sync.sourceEqualsTarget",
8647
+ githubNotConnected: "github.notConnected",
8648
+ githubAuthFailed: "github.authFailed",
8649
+ githubGistNotFound: "github.gistNotFound",
8650
+ githubDeviceCodeExpired: "github.deviceCodeExpired",
8651
+ githubRateLimitExceeded: "github.rateLimitExceeded",
8647
8652
  userNotManageable: "user.notManageable",
8648
8653
  userNotSwitchable: "user.notSwitchable",
8649
8654
  storageUnreadable: "storage.unreadable",
@@ -23090,6 +23095,31 @@ var probeRequestSchema = exports_external.object({
23090
23095
  var probeStoredRequestSchema = exports_external.object({
23091
23096
  endpoint: optionalText(MAX_NAME).optional()
23092
23097
  });
23098
+ var gitHubDeviceCodeRequestSchema = exports_external.object({
23099
+ clientId: optionalText(100).optional()
23100
+ });
23101
+ var gitHubDevicePollRequestSchema = exports_external.object({
23102
+ deviceCode: exports_external.string().min(1).max(200),
23103
+ clientId: optionalText(100).optional()
23104
+ });
23105
+ var gitHubTokenAuthRequestSchema = exports_external.object({
23106
+ token: exports_external.string().trim().min(1, "Token 不能为空").max(500)
23107
+ });
23108
+ var gitHubPushRequestSchema = exports_external.object({
23109
+ passphrase: optionalText(MAX_KEY),
23110
+ includeCodexLoginCache: exports_external.boolean().optional()
23111
+ });
23112
+ var gitHubPullPreviewRequestSchema = exports_external.object({
23113
+ passphrase: optionalText(MAX_KEY),
23114
+ conflictPolicy: conflictPolicySchema.optional(),
23115
+ restoreActive: exports_external.boolean().optional()
23116
+ });
23117
+ var gitHubPullRequestSchema = exports_external.object({
23118
+ passphrase: optionalText(MAX_KEY),
23119
+ conflictPolicy: conflictPolicySchema.optional(),
23120
+ restoreActive: exports_external.boolean().optional(),
23121
+ migrateCodexLoginCache: exports_external.boolean().optional()
23122
+ });
23093
23123
  var emptyRequestSchema = exports_external.object({});
23094
23124
  function formatSchemaError(error51) {
23095
23125
  const parts = error51.issues.slice(0, 3).map((issue2) => {
@@ -23487,7 +23517,8 @@ class EnvironmentService {
23487
23517
  key: join2(dataDir, "aes-256-gcm.key"),
23488
23518
  env: join2(dataDir, "env.sh"),
23489
23519
  sessions: join2(dataDir, "sessions.json"),
23490
- vault: join2(dataDir, "vault.json")
23520
+ vault: join2(dataDir, "vault.json"),
23521
+ github: join2(dataDir, "github.json")
23491
23522
  };
23492
23523
  }
23493
23524
  get backupsDir() {
@@ -28653,1118 +28684,1559 @@ function createDriftRoutes(services) {
28653
28684
  return app;
28654
28685
  }
28655
28686
 
28656
- // src/http/routes/harnesses.ts
28657
- function createHarnessRoutes(services) {
28658
- const app = new Hono2;
28659
- const harnesses = services.get(IHarnessRegistry);
28660
- const profiles = services.get(IProfileService);
28661
- const activation = services.get(IActivationService);
28662
- const adapters = services.get(IAdapterRegistry);
28663
- const environment = services.get(IEnvironmentService);
28664
- const files = services.get(IFileService);
28665
- const log = services.get(ILogService);
28666
- const probe = services.get(IProbeService);
28667
- function summary(id) {
28668
- const adapter = adapters.get(id);
28669
- return {
28670
- id,
28671
- label: harnesses.label(id),
28672
- mode: adapter.mode,
28673
- active: activation.getActive(id),
28674
- profiles: profiles.list(id),
28675
- fields: adapter.fields,
28676
- modelRequired: adapter.modelRequired,
28677
- targets: adapter.targets(),
28678
- envVars: adapter.envVarNames,
28679
- envNote: adapter.envNote,
28680
- supportsOfficialAuth: adapter.renderOfficial !== undefined
28681
- };
28687
+ // src/services/transfer.ts
28688
+ import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes4, scryptSync } from "node:crypto";
28689
+
28690
+ // src/services/codex-login-cache.ts
28691
+ import { lstatSync as lstatSync2 } from "node:fs";
28692
+ import { join as join12 } from "node:path";
28693
+ import { isDeepStrictEqual } from "node:util";
28694
+ var AUTH_FILE = "auth.json";
28695
+ var MAX_CACHE_BYTES = 1024 * 1024;
28696
+ var ICodexLoginCacheService = createDecorator("codexLoginCacheService");
28697
+ var _dec = [
28698
+ inject(IEnvironmentService, IFileService)
28699
+ ];
28700
+ var _init = __decoratorStart(undefined);
28701
+
28702
+ class CodexLoginCacheService {
28703
+ environment;
28704
+ files;
28705
+ constructor(environment, files) {
28706
+ this.environment = environment;
28707
+ this.files = files;
28682
28708
  }
28683
- app.get("/", (c) => c.json({
28684
- envFile: environment.files.env,
28685
- items: harnesses.list().map((item) => summary(item.id))
28686
- }));
28687
- app.get("/:harnessId", (c) => c.json(summary(harnesses.require(c.req.param("harnessId")))));
28688
- app.post("/:harnessId/profiles", async (c) => {
28689
- const harnessId = harnesses.require(c.req.param("harnessId"));
28690
- const body = await readJsonBody(c, createProfileRequestSchema);
28691
- const profile = profiles.upsert(harnessId, {
28692
- name: body.name,
28693
- baseUrl: body.baseUrl,
28694
- apiKey: body.apiKey,
28695
- model: body.model,
28696
- notes: body.notes,
28697
- extras: body.extras,
28698
- overrides: body.overrides,
28699
- providerId: body.providerId,
28700
- providerEndpoint: body.providerEndpoint
28701
- }, true);
28702
- return c.json(profile, 201);
28703
- });
28704
- app.patch("/:harnessId/profiles/:name", async (c) => {
28705
- const harnessId = harnesses.require(c.req.param("harnessId"));
28706
- const name = decodeURIComponent(c.req.param("name"));
28707
- const body = await readJsonBody(c, updateProfileRequestSchema);
28708
- const wasActive = activation.getActive(harnessId)?.name === name;
28709
- const snapshot = files.readOptional(environment.files.profiles);
28710
- let persisted = false;
28709
+ exists() {
28710
+ const file2 = this.path();
28711
+ this.assertDirectory(false);
28712
+ return this.assertRegularFile(file2, false);
28713
+ }
28714
+ readOptional() {
28715
+ const file2 = this.path();
28716
+ this.assertDirectory(false);
28717
+ if (!this.assertRegularFile(file2, false)) {
28718
+ return;
28719
+ }
28720
+ const content = this.files.readOptional(file2);
28721
+ if (content === undefined) {
28722
+ return;
28723
+ }
28724
+ this.validate(content);
28725
+ return content;
28726
+ }
28727
+ matchesCurrent(content) {
28728
+ this.validate(content);
28729
+ const current = this.readOptional();
28730
+ return current !== undefined && isDeepStrictEqual(JSON.parse(content), JSON.parse(current));
28731
+ }
28732
+ validate(content) {
28733
+ if (Buffer.byteLength(content, "utf8") > MAX_CACHE_BYTES) {
28734
+ throw new HttpError(400, "Codex 登录缓存过大,拒绝迁移", {
28735
+ code: ERROR_CODES.codexCacheTooLarge
28736
+ });
28737
+ }
28711
28738
  try {
28712
- const profile = profiles.upsert(harnessId, {
28713
- name: body.name ?? name,
28714
- sourceName: name,
28715
- baseUrl: body.baseUrl,
28716
- apiKey: body.apiKey,
28717
- model: body.model,
28718
- notes: body.notes,
28719
- extras: body.extras,
28720
- overrides: body.overrides,
28721
- providerId: body.providerId,
28722
- providerEndpoint: body.providerEndpoint
28723
- }, false);
28724
- persisted = true;
28725
- activation.reconcileProfileUpdate(harnessId, name, profile.name);
28726
- return c.json(profile);
28739
+ const value = JSON.parse(content);
28740
+ if (!isPlainObject3(value)) {
28741
+ throw new Error("not an object");
28742
+ }
28743
+ } catch {
28744
+ throw new HttpError(400, "Codex 登录缓存不是有效的 JSON 对象,拒绝迁移", {
28745
+ code: ERROR_CODES.codexCacheInvalidJson
28746
+ });
28747
+ }
28748
+ }
28749
+ prepareWrite(content) {
28750
+ this.validate(content);
28751
+ const directory = this.assertDirectory(true);
28752
+ const path = join12(directory, AUTH_FILE);
28753
+ this.assertRegularFile(path, false);
28754
+ return { key: CODEX_AUTH_TARGET, path, content };
28755
+ }
28756
+ write(content) {
28757
+ const write = this.prepareWrite(content);
28758
+ this.files.writeUserSecretFile(write.path, write.content);
28759
+ }
28760
+ path() {
28761
+ return join12(this.environment.harnessHomes.codex, AUTH_FILE);
28762
+ }
28763
+ assertDirectory(create) {
28764
+ const directory = this.environment.harnessHomes.codex;
28765
+ try {
28766
+ const stat = lstatSync2(directory);
28767
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
28768
+ throw new HttpError(400, "Codex 配置目录必须是普通目录,拒绝迁移登录缓存", {
28769
+ code: ERROR_CODES.codexConfigDirNotRegular
28770
+ });
28771
+ }
28772
+ return directory;
28727
28773
  } catch (error52) {
28728
- if (persisted) {
28729
- restoreProfileStore(files, environment.files.profiles, snapshot);
28730
- if (wasActive) {
28731
- try {
28732
- activation.activate(harnessId, name);
28733
- } catch (rollbackError) {
28734
- log.error(`edit rollback: failed to re-activate ${harnessId}/${name}`, rollbackError);
28735
- }
28736
- }
28774
+ if (error52.code !== "ENOENT") {
28775
+ throw error52;
28776
+ }
28777
+ if (!create) {
28778
+ return directory;
28779
+ }
28780
+ this.files.ensureDir(directory);
28781
+ const created = lstatSync2(directory);
28782
+ if (created.isSymbolicLink() || !created.isDirectory()) {
28783
+ throw new HttpError(400, "Codex 配置目录必须是普通目录,拒绝迁移登录缓存", {
28784
+ code: ERROR_CODES.codexConfigDirNotRegular
28785
+ });
28786
+ }
28787
+ return directory;
28788
+ }
28789
+ }
28790
+ assertRegularFile(file2, required2) {
28791
+ try {
28792
+ const stat = lstatSync2(file2);
28793
+ if (stat.isSymbolicLink() || !stat.isFile()) {
28794
+ throw new HttpError(400, "Codex 登录缓存必须是普通文件,拒绝迁移", {
28795
+ code: ERROR_CODES.codexCacheNotRegular
28796
+ });
28797
+ }
28798
+ if (stat.size > MAX_CACHE_BYTES) {
28799
+ throw new HttpError(400, "Codex 登录缓存过大,拒绝迁移", {
28800
+ code: ERROR_CODES.codexCacheTooLarge
28801
+ });
28802
+ }
28803
+ return true;
28804
+ } catch (error52) {
28805
+ if (error52.code === "ENOENT" && !required2) {
28806
+ return false;
28737
28807
  }
28738
28808
  throw error52;
28739
28809
  }
28740
- });
28741
- app.delete("/:harnessId/profiles/:name", (c) => {
28742
- const harnessId = harnesses.require(c.req.param("harnessId"));
28743
- const name = decodeURIComponent(c.req.param("name"));
28744
- activation.prepareDelete(harnessId, name);
28745
- profiles.remove(harnessId, name);
28746
- return c.json({ ok: true });
28747
- });
28748
- app.get("/:harnessId/profiles/:name/preview", (c) => {
28749
- const harnessId = harnesses.require(c.req.param("harnessId"));
28750
- const name = decodeURIComponent(c.req.param("name"));
28751
- return c.json({ targets: activation.preview(harnessId, name) });
28752
- });
28753
- app.post("/:harnessId/profiles/:name/probe", async (c) => {
28754
- const harnessId = harnesses.require(c.req.param("harnessId"));
28755
- const name = decodeURIComponent(c.req.param("name"));
28756
- parseWith(probeStoredRequestSchema, await c.req.json().catch(() => ({})));
28757
- const decrypted = profiles.decrypt(harnessId, name);
28758
- return c.json({ result: await probe.probe(decrypted) });
28759
- });
28760
- app.post("/:harnessId/profiles/:name/activate", (c) => {
28761
- const harnessId = harnesses.require(c.req.param("harnessId"));
28762
- const name = decodeURIComponent(c.req.param("name"));
28763
- const result = activation.activate(harnessId, name);
28764
- return c.json({ ok: true, envFile: result.envFile, warnings: result.warnings });
28765
- });
28766
- app.post("/:harnessId/official/activate", (c) => {
28767
- const harnessId = harnesses.require(c.req.param("harnessId"));
28768
- const result = activation.activateOfficial(harnessId);
28769
- return c.json({ ok: true, envFile: result.envFile, warnings: result.warnings });
28770
- });
28771
- return app;
28772
- }
28773
- function restoreProfileStore(files, path, snapshot) {
28774
- if (snapshot === undefined) {
28775
- files.remove(path);
28776
- return;
28777
28810
  }
28778
- files.writeSecure(path, snapshot);
28811
+ }
28812
+ CodexLoginCacheService = __decorateElement(_init, 0, "CodexLoginCacheService", _dec, CodexLoginCacheService);
28813
+ __runInitializers(_init, 1, CodexLoginCacheService);
28814
+ __decoratorMetadata(_init, CodexLoginCacheService);
28815
+ let _CodexLoginCacheService = CodexLoginCacheService;
28816
+ function isPlainObject3(value) {
28817
+ return typeof value === "object" && value !== null && !Array.isArray(value);
28779
28818
  }
28780
28819
 
28781
- // src/http/routes/operations.ts
28782
- function createOperationRoutes(services) {
28783
- const app = new Hono2;
28784
- const journal = services.get(IJournalService);
28785
- app.get("/", (c) => {
28786
- const harnessParam = c.req.query("harness");
28787
- const items = harnessParam && harnessParam.length > 0 ? journal.list().filter((item) => item.harness === harnessParam) : journal.list();
28788
- return c.json({ items });
28789
- });
28790
- app.get("/:id", (c) => c.json(journal.detail(decodeURIComponent(c.req.param("id")))));
28791
- app.post("/:id/undo", (c) => c.json({
28792
- ok: true,
28793
- receipt: journal.undo(decodeURIComponent(c.req.param("id")))
28794
- }));
28795
- return app;
28796
- }
28797
-
28798
- // src/http/routes/probe.ts
28799
- function createProbeRoutes(services) {
28800
- const app = new Hono2;
28801
- const vault = services.get(IVaultService);
28802
- const probe = services.get(IProbeService);
28803
- app.post("/", async (c) => {
28804
- const body = await readJsonBody(c, probeRequestSchema);
28805
- const apiKey = draftKey(vault, body);
28806
- if (!apiKey) {
28807
- return c.json({
28808
- result: {
28809
- ok: false,
28810
- code: PROBE_CODES.missingApiKey,
28811
- message: "未提供 API Key,也无法从凭据库解析,无法测试"
28812
- }
28813
- });
28814
- }
28815
- return c.json({
28816
- result: await probe.probe({ baseUrl: body.baseUrl, apiKey })
28817
- });
28818
- });
28819
- return app;
28820
- }
28821
- function draftKey(vault, body) {
28822
- if (body.providerId?.trim()) {
28823
- return vault.decrypt(body.providerId.trim());
28824
- }
28825
- return body.apiKey?.trim() ?? "";
28826
- }
28827
-
28828
- // src/http/routes/providers.ts
28829
- function createProviderRoutes(services) {
28830
- const app = new Hono2;
28831
- const vault = services.get(IVaultService);
28832
- const profiles = services.get(IProfileService);
28833
- const activation = services.get(IActivationService);
28834
- const log = services.get(ILogService);
28835
- const probe = services.get(IProbeService);
28836
- app.get("/", (c) => c.json({ items: vault.list() }));
28837
- app.get("/:id", (c) => c.json(vault.get(decodeURIComponent(c.req.param("id")))));
28838
- app.post("/", async (c) => {
28839
- const body = await readJsonBody(c, createProviderRequestSchema);
28840
- return c.json({ provider: vault.create(body), warnings: [] }, 201);
28841
- });
28842
- app.patch("/:id", async (c) => {
28843
- const id = decodeURIComponent(c.req.param("id"));
28844
- const body = await readJsonBody(c, updateProviderRequestSchema);
28845
- const { provider, affected } = vault.update(id, body);
28846
- profiles.sweepVaultCache(id, vault.decrypt(id), provider.endpoints);
28847
- const warnings = [];
28848
- for (const ref of affected) {
28849
- if (activation.getActive(ref.harness)?.name !== ref.name) {
28850
- continue;
28851
- }
28852
- const profile = profiles.get(ref.harness, ref.name);
28853
- if (profile?.providerEndpoint && !provider.endpoints.some((ep) => ep.key === profile.providerEndpoint)) {
28854
- warnings.push({
28855
- message: `${ref.harness}/${ref.name}: endpoint ${profile.providerEndpoint} 已不存在,将回退到 provider 首个 endpoint`,
28856
- code: WARNING_CODES.endpointFallback,
28857
- params: {
28858
- harness: ref.harness,
28859
- profile: ref.name,
28860
- endpoint: profile.providerEndpoint
28861
- }
28862
- });
28863
- }
28864
- try {
28865
- activation.activate(ref.harness, ref.name);
28866
- } catch (error52) {
28867
- log.error(`providers update: failed to re-apply ${ref.harness}/${ref.name}`, error52);
28868
- warnings.push({
28869
- message: `${ref.harness}/${ref.name} 重新应用失败:${error52.message}`,
28870
- code: WARNING_CODES.reapplyFailed,
28871
- params: { harness: ref.harness, profile: ref.name, reason: error52.message }
28872
- });
28873
- }
28874
- }
28875
- return c.json({ provider, warnings });
28876
- });
28877
- app.post("/:id/probe", async (c) => {
28878
- const id = decodeURIComponent(c.req.param("id"));
28879
- const body = parseWith(probeStoredRequestSchema, await c.req.json().catch(() => ({})));
28880
- const apiKey = vault.decrypt(id);
28881
- const baseUrl = resolveEndpointBaseUrl(vault.get(id), body.endpoint);
28882
- if (!baseUrl) {
28883
- return c.json({
28884
- result: {
28885
- ok: false,
28886
- code: PROBE_CODES.missingBaseUrl,
28887
- message: `provider ${id} 未配置任何 endpoint,无法测试`
28888
- }
28889
- });
28890
- }
28891
- return c.json({ result: await probe.probe({ baseUrl, apiKey }) });
28892
- });
28893
- app.delete("/:id", (c) => {
28894
- vault.remove(decodeURIComponent(c.req.param("id")));
28895
- return c.json({ ok: true });
28896
- });
28897
- return app;
28898
- }
28899
- function resolveEndpointBaseUrl(entry, endpointKey) {
28900
- if (endpointKey?.trim()) {
28901
- const named = entry.endpoints.find((candidate) => candidate.key === endpointKey.trim());
28902
- if (named) {
28903
- return named.baseUrl;
28904
- }
28905
- }
28906
- return entry.endpoints[0]?.baseUrl ?? null;
28907
- }
28908
-
28909
- // src/services/scan.ts
28910
- var IScanService = createDecorator("scanService");
28820
+ // src/services/transfer.ts
28821
+ var FORMAT = "harness-switch-encrypted-export";
28822
+ var VERSION = 1;
28823
+ var MAX_ENCRYPTED_BYTES = 10 * 1024 * 1024;
28824
+ var ITransferService = createDecorator("transferService");
28911
28825
  var _dec = [
28912
- inject(IAdapterRegistry, IHarnessRegistry, IProfileService, IVaultService, IFileService, ILogService)
28826
+ inject(IEnvironmentService, IFileService, ICryptoService, ICodexLoginCacheService, ILiveWriteService, IAdapterRegistry, IActivationService, IVaultService)
28913
28827
  ];
28914
28828
  var _init = __decoratorStart(undefined);
28915
28829
 
28916
- class ScanService {
28830
+ class TransferService {
28831
+ environment;
28832
+ files;
28833
+ crypto;
28834
+ codexLoginCache;
28835
+ liveWrite;
28917
28836
  adapters;
28918
- harnesses;
28919
- profiles;
28837
+ activation;
28920
28838
  vault;
28921
- files;
28922
- log;
28923
- constructor(adapters, harnesses, profiles, vault, files, log) {
28839
+ constructor(environment, files, crypto2, codexLoginCache, liveWrite, adapters, activation, vault) {
28840
+ this.environment = environment;
28841
+ this.files = files;
28842
+ this.crypto = crypto2;
28843
+ this.codexLoginCache = codexLoginCache;
28844
+ this.liveWrite = liveWrite;
28924
28845
  this.adapters = adapters;
28925
- this.harnesses = harnesses;
28926
- this.profiles = profiles;
28846
+ this.activation = activation;
28927
28847
  this.vault = vault;
28928
- this.files = files;
28929
- this.log = log;
28930
28848
  }
28931
- scan() {
28932
- return this.harnesses.list().map((harness) => this.scanOne(harness.id, harness.label));
28849
+ exportPreview() {
28850
+ return { codexLoginCacheAvailable: this.codexLoginCache.exists() };
28933
28851
  }
28934
- importSelections(selections) {
28935
- const found = new Map;
28936
- for (const result of this.harnesses.list()) {
28937
- const adapter = this.adapters.get(result.id);
28938
- for (const candidate of this.detect(adapter)) {
28939
- found.set(candidateId(result.id, candidate.key), {
28940
- harness: result.id,
28941
- candidate
28942
- });
28943
- }
28852
+ exportAll(passphrase, includeCodexLoginCache) {
28853
+ this.assertPassphrase(passphrase);
28854
+ const codexLoginCache = includeCodexLoginCache ? this.codexLoginCache.readOptional() : undefined;
28855
+ if (includeCodexLoginCache && codexLoginCache === undefined) {
28856
+ throw new HttpError(400, "当前用户没有可导出的 Codex 登录缓存");
28944
28857
  }
28945
- const warnings = [];
28946
- let imported = 0;
28947
- let skipped = 0;
28948
- let providersCreated = 0;
28949
- for (const selection of selections) {
28950
- const entry = found.get(selection.id);
28951
- if (!entry) {
28952
- warnings.push({ message: `${selection.name}:配置已不在磁盘上,已跳过` });
28953
- skipped += 1;
28954
- continue;
28955
- }
28956
- const exists = this.profiles.get(entry.harness, selection.name) !== undefined;
28957
- if (exists && !selection.overwrite) {
28958
- warnings.push({ message: `${selection.name}:同名配置已存在,已跳过` });
28959
- skipped += 1;
28960
- continue;
28961
- }
28962
- try {
28963
- providersCreated += this.save(entry.harness, entry.candidate, selection, exists);
28964
- imported += 1;
28965
- } catch (error52) {
28966
- this.log.error(`scan import failed for ${entry.harness}/${selection.name}`, error52);
28967
- warnings.push({
28968
- message: `${selection.name}:${error52 instanceof Error ? error52.message : String(error52)}`
28858
+ const store = this.readStore();
28859
+ const vault = this.readVault();
28860
+ const providers = Object.values(vault.entries).map((entry) => ({
28861
+ id: entry.id,
28862
+ name: entry.name,
28863
+ apiKey: this.crypto.decrypt(entry.api_key),
28864
+ notes: entry.notes,
28865
+ endpoints: entry.endpoints
28866
+ }));
28867
+ const profiles = [];
28868
+ for (const harness of HARNESS_IDS) {
28869
+ for (const [name, stored] of Object.entries(store[harness] ?? {})) {
28870
+ profiles.push({
28871
+ harness,
28872
+ name,
28873
+ baseUrl: stored.base_url || "",
28874
+ apiKey: this.resolveKey(stored),
28875
+ model: stored.model || "",
28876
+ notes: stored.notes || "",
28877
+ extras: stored.extras ?? {},
28878
+ overrides: stored.overrides ?? {},
28879
+ ...stored.provider_id && vault.entries[stored.provider_id] ? {
28880
+ providerId: stored.provider_id,
28881
+ ...stored.provider_endpoint ? { providerEndpoint: stored.provider_endpoint } : {}
28882
+ } : {}
28969
28883
  });
28970
- skipped += 1;
28971
28884
  }
28972
28885
  }
28973
- return { ok: true, imported, skipped, providersCreated, warnings };
28974
- }
28975
- save(harness, candidate, selection, replacing) {
28976
- let providerId;
28977
- let created = 0;
28978
- const apiKey = candidate.apiKey || selection.apiKey?.trim() || "";
28979
- if (selection.target === "vault") {
28980
- if (selection.providerId) {
28981
- this.vault.get(selection.providerId);
28982
- providerId = selection.providerId;
28983
- } else {
28984
- if (!apiKey) {
28985
- throw new HttpError(400, "这条配置里没有可提取的凭据,请先填写 API key");
28886
+ const active = HARNESS_IDS.flatMap((harness) => {
28887
+ const entry = this.activation.getActive(harness);
28888
+ return entry ? [
28889
+ {
28890
+ harness,
28891
+ name: entry.name,
28892
+ official: entry.official === true
28986
28893
  }
28987
- providerId = this.vault.create({
28988
- name: selection.providerName ?? selection.name,
28989
- apiKey,
28990
- endpoints: candidate.baseUrl ? [{ key: "default", label: "默认", baseUrl: candidate.baseUrl }] : []
28991
- }).id;
28992
- created = 1;
28993
- }
28994
- } else if (!apiKey) {
28995
- throw new HttpError(400, "这条配置里没有可提取的凭据,请先填写 API key");
28996
- }
28997
- this.profiles.upsert(harness, {
28998
- name: selection.name,
28999
- sourceName: replacing ? selection.name : undefined,
29000
- baseUrl: candidate.baseUrl,
29001
- apiKey,
29002
- model: candidate.model,
29003
- notes: `从 ${harness} 现有配置导入(${candidate.key})`,
29004
- extras: candidate.extras,
29005
- ...providerId ? { providerId, providerEndpoint: "default" } : {}
29006
- }, !replacing);
29007
- return created;
28894
+ ] : [];
28895
+ });
28896
+ return encrypt({
28897
+ format: "harness-switch-portable-config",
28898
+ version: VERSION,
28899
+ exportedAt: new Date().toISOString(),
28900
+ profiles,
28901
+ providers,
28902
+ active,
28903
+ codexLoginCache
28904
+ }, passphrase);
29008
28905
  }
29009
- scanOne(harness, label) {
29010
- const adapter = this.adapters.get(harness);
29011
- const targets = adapter.targets();
29012
- const sources = targets.map((target) => {
29013
- const content = this.readSafely(target.path);
29014
- let parsable = content !== undefined;
29015
- if (content !== undefined) {
28906
+ preview(envelope, passphrase, conflictPolicy, restoreActive) {
28907
+ this.assertConflictPolicy(conflictPolicy);
28908
+ const payload = this.decrypt(envelope, passphrase);
28909
+ const existing = this.readStore();
28910
+ const plan = this.planImport(payload, existing, this.readVault(), conflictPolicy, restoreActive);
28911
+ const targetCodexLoginCacheExists = this.codexLoginCache.exists();
28912
+ return {
28913
+ exportedAt: payload.exportedAt,
28914
+ profileCount: payload.profiles.length,
28915
+ providerCount: payload.providers?.length ?? 0,
28916
+ harnesses: HARNESS_IDS.map((harness) => ({
28917
+ harness,
28918
+ profiles: payload.profiles.filter((profile) => profile.harness === harness).length
28919
+ })).filter((item) => item.profiles > 0),
28920
+ conflicts: payload.profiles.filter((profile) => existing[profile.harness]?.[profile.name] !== undefined).map(({ harness, name }) => ({ harness, name })),
28921
+ activeCount: payload.active.length,
28922
+ conflictPolicy,
28923
+ restoreActive,
28924
+ codexActivationAuthEffect: plan.codexActivationAuthEffect,
28925
+ codexLoginCache: {
28926
+ available: payload.codexLoginCache !== undefined,
28927
+ targetExists: targetCodexLoginCacheExists,
28928
+ migrationNeeded: payload.codexLoginCache !== undefined && !this.codexLoginCache.matchesCurrent(payload.codexLoginCache)
28929
+ }
28930
+ };
28931
+ }
28932
+ importAll(envelope, passphrase, conflictPolicy, restoreActive, migrateCodexLoginCache) {
28933
+ this.assertConflictPolicy(conflictPolicy);
28934
+ const payload = this.decrypt(envelope, passphrase);
28935
+ if (migrateCodexLoginCache && payload.codexLoginCache === undefined) {
28936
+ throw new HttpError(400, "导出包不包含可迁移的 Codex 登录缓存");
28937
+ }
28938
+ const cacheWrite = migrateCodexLoginCache && !this.codexLoginCache.matchesCurrent(payload.codexLoginCache) ? [
28939
+ {
28940
+ ...this.codexLoginCache.prepareWrite(payload.codexLoginCache),
28941
+ format: "json",
28942
+ secret: true
28943
+ }
28944
+ ] : [];
28945
+ const plan = this.planImport(payload, this.readStore(), this.readVault(), conflictPolicy, restoreActive);
28946
+ const profilesPath = this.environment.files.profiles;
28947
+ const vaultPath = this.environment.files.vault;
28948
+ const profileSnapshot = this.files.readOptional(profilesPath);
28949
+ const vaultSnapshot = this.files.readOptional(vaultPath);
28950
+ this.liveWrite.transaction({
28951
+ kind: "import",
28952
+ harness: "codex",
28953
+ profile: "导入登录缓存",
28954
+ writes: cacheWrite,
28955
+ metadata: ["profiles", "vault"]
28956
+ }, () => {
28957
+ try {
28958
+ this.files.writeJson(vaultPath, plan.vault);
28959
+ this.files.writeJson(profilesPath, plan.store);
28960
+ } catch (error52) {
28961
+ this.restore(vaultPath, vaultSnapshot);
28962
+ this.restore(profilesPath, profileSnapshot);
28963
+ throw error52;
28964
+ }
28965
+ });
28966
+ const warnings = [];
28967
+ let activeRestored = 0;
28968
+ if (restoreActive) {
28969
+ for (const active of payload.active) {
29016
28970
  try {
29017
- assertParsable(target.format, target.path, content);
29018
- } catch {
29019
- parsable = false;
28971
+ if (active.official) {
28972
+ this.activation.activateOfficial(active.harness);
28973
+ } else if (plan.store[active.harness]?.[active.name]) {
28974
+ this.activation.activate(active.harness, active.name);
28975
+ } else {
28976
+ throw new Error("对应配置不存在");
28977
+ }
28978
+ activeRestored++;
28979
+ } catch (error52) {
28980
+ const reason2 = error52.message;
28981
+ warnings.push({
28982
+ message: `${active.harness}/${active.name} 未能恢复激活状态:${reason2}`,
28983
+ code: WARNING_CODES.transferActiveRestoreFailed,
28984
+ params: { harness: active.harness, profile: active.name, reason: reason2 }
28985
+ });
29020
28986
  }
29021
28987
  }
29022
- return {
29023
- key: target.key,
29024
- label: target.label,
29025
- path: target.path,
29026
- exists: content !== undefined,
29027
- parsable
29028
- };
29029
- });
29030
- if (!adapter.detect) {
29031
- return {
29032
- harness,
29033
- label,
29034
- sources,
29035
- candidates: [],
29036
- note: "该工具暂不支持扫描导入",
29037
- noteCode: SCAN_NOTE_CODES.unsupported
29038
- };
29039
- }
29040
- if (sources.every((source) => !source.exists)) {
29041
- return {
29042
- harness,
29043
- label,
29044
- sources,
29045
- candidates: [],
29046
- note: "磁盘上没有找到该工具的配置文件",
29047
- noteCode: SCAN_NOTE_CODES.noConfigFiles
29048
- };
29049
- }
29050
- if (sources.some((source) => source.exists && !source.parsable)) {
29051
- return {
29052
- harness,
29053
- label,
29054
- sources,
29055
- candidates: [],
29056
- note: "配置文件存在但无法解析,导入前请先修复它",
29057
- noteCode: SCAN_NOTE_CODES.unparsable
29058
- };
29059
28988
  }
29060
- const candidates = this.detect(adapter).map((candidate) => this.describe(harness, candidate, this.existingNames(harness)));
29061
- return {
29062
- harness,
29063
- label,
29064
- sources,
29065
- candidates,
29066
- note: candidates.length === 0 ? "配置文件里没有找到可导入的 provider" : undefined,
29067
- noteCode: candidates.length === 0 ? SCAN_NOTE_CODES.noCandidates : undefined
29068
- };
29069
- }
29070
- describe(harness, candidate, existing) {
29071
- const suggestedName = uniqueName(candidate.key || harness, existing);
29072
28989
  return {
29073
- id: candidateId(harness, candidate.key),
29074
- harness,
29075
- sourceKey: candidate.key,
29076
- suggestedName,
29077
- baseUrl: candidate.baseUrl,
29078
- model: candidate.model,
29079
- extras: candidate.extras,
29080
- apiKeyPreview: mask(candidate.apiKey),
29081
- apiKeyPresent: candidate.apiKey !== "",
29082
- active: candidate.active,
29083
- conflictsWith: existing.has(candidate.key) ? candidate.key : undefined,
29084
- matchesProvider: this.matchProvider(candidate)
28990
+ ok: true,
28991
+ imported: plan.imported,
28992
+ overwritten: plan.overwritten,
28993
+ skipped: plan.skipped,
28994
+ providersCopied: plan.providersCopied,
28995
+ activeRestored,
28996
+ codexLoginCacheMigrated: cacheWrite.length > 0,
28997
+ warnings
29085
28998
  };
29086
28999
  }
29087
- detect(adapter) {
29088
- if (!adapter.detect) {
29089
- return [];
29000
+ decrypt(envelope, passphrase) {
29001
+ this.assertPassphrase(passphrase);
29002
+ const payload = decrypt(envelope, passphrase);
29003
+ if (payload.format !== "harness-switch-portable-config" || payload.version !== VERSION || !Array.isArray(payload.profiles) || !Array.isArray(payload.active) || typeof payload.exportedAt !== "string") {
29004
+ throw new HttpError(400, "不支持的导出文件格式");
29090
29005
  }
29091
- try {
29092
- return adapter.detect(this.readCurrent(adapter));
29093
- } catch (error52) {
29094
- this.log.error(`scan failed for ${adapter.id}`, error52);
29095
- return [];
29006
+ if (payload.profiles.length > 1e4) {
29007
+ throw new HttpError(400, "导出文件包含过多配置");
29096
29008
  }
29097
- }
29098
- matchProvider(candidate) {
29099
- if (!candidate.apiKey) {
29100
- return;
29009
+ for (const profile of payload.profiles) {
29010
+ if (!isPortableProfile(profile)) {
29011
+ throw new HttpError(400, "导出文件中的配置数据无效");
29012
+ }
29101
29013
  }
29102
- for (const provider of this.vault.list()) {
29103
- try {
29104
- if (this.vault.decrypt(provider.id) === candidate.apiKey) {
29105
- return provider.id;
29014
+ for (const active of payload.active) {
29015
+ if (!isPortableActive(active)) {
29016
+ throw new HttpError(400, "导出文件中的激活状态无效");
29017
+ }
29018
+ }
29019
+ if (payload.providers !== undefined) {
29020
+ if (!Array.isArray(payload.providers) || payload.providers.length > 1e4) {
29021
+ throw new HttpError(400, "导出文件中的凭据库数据无效");
29022
+ }
29023
+ for (const provider of payload.providers) {
29024
+ if (!isPortableProvider(provider)) {
29025
+ throw new HttpError(400, "导出文件中的凭据库数据无效");
29106
29026
  }
29107
- } catch {}
29027
+ }
29108
29028
  }
29109
- return;
29110
- }
29111
- existingNames(harness) {
29112
- return new Set(this.profiles.list(harness).map((profile) => profile.name));
29113
- }
29114
- readCurrent(adapter) {
29115
- const current = {};
29116
- for (const target of adapter.targets()) {
29117
- current[target.key] = this.readSafely(target.path);
29029
+ if (payload.codexLoginCache !== undefined) {
29030
+ if (typeof payload.codexLoginCache !== "string") {
29031
+ throw new HttpError(400, "导出文件中的 Codex 登录缓存无效");
29032
+ }
29033
+ this.codexLoginCache.validate(payload.codexLoginCache);
29118
29034
  }
29119
- return current;
29035
+ this.validatePayload(payload);
29036
+ return payload;
29120
29037
  }
29121
- readSafely(path) {
29122
- try {
29123
- return this.files.readRegularOptional(path);
29124
- } catch {
29125
- return;
29038
+ assertConflictPolicy(conflictPolicy) {
29039
+ if (conflictPolicy !== "skip" && conflictPolicy !== "overwrite") {
29040
+ throw new HttpError(400, "invalid conflict policy");
29126
29041
  }
29127
29042
  }
29128
- }
29129
- ScanService = __decorateElement(_init, 0, "ScanService", _dec, ScanService);
29130
- __runInitializers(_init, 1, ScanService);
29131
- __decoratorMetadata(_init, ScanService);
29132
- let _ScanService = ScanService;
29133
- function candidateId(harness, key) {
29134
- return `${harness}:${key}`;
29135
- }
29136
- function mask(apiKey) {
29137
- if (!apiKey) {
29138
- return "";
29043
+ validatePayload(payload) {
29044
+ const profileIds = new Set;
29045
+ const providerIds = new Set;
29046
+ for (const provider of payload.providers ?? []) {
29047
+ if (providerIds.has(provider.id)) {
29048
+ throw new HttpError(400, "导出文件包含重复的凭据库条目");
29049
+ }
29050
+ providerIds.add(provider.id);
29051
+ }
29052
+ for (const profile of payload.profiles) {
29053
+ this.validateProfile(profile);
29054
+ const id = profileId(profile.harness, profile.name);
29055
+ if (profileIds.has(id)) {
29056
+ throw new HttpError(400, "导出文件包含重复的配置");
29057
+ }
29058
+ profileIds.add(id);
29059
+ if (profile.providerId && !providerIds.has(profile.providerId)) {
29060
+ throw new HttpError(400, "导出文件中的配置引用了不存在的凭据库条目");
29061
+ }
29062
+ }
29063
+ const activeHarnesses = new Set;
29064
+ for (const active of payload.active) {
29065
+ if (activeHarnesses.has(active.harness)) {
29066
+ throw new HttpError(400, "导出文件包含重复的激活状态");
29067
+ }
29068
+ activeHarnesses.add(active.harness);
29069
+ const adapter = this.adapters.get(active.harness);
29070
+ if (active.official) {
29071
+ if (active.name !== "官方登录" || !adapter.renderOfficial) {
29072
+ throw new HttpError(400, "导出文件中的官方登录状态无效");
29073
+ }
29074
+ } else if (!profileIds.has(profileId(active.harness, active.name))) {
29075
+ throw new HttpError(400, "导出文件中的激活状态引用了不存在的配置");
29076
+ }
29077
+ }
29139
29078
  }
29140
- if (apiKey.length <= 8) {
29141
- return "•".repeat(apiKey.length);
29079
+ planImport(payload, existing, existingVault, conflictPolicy, restoreActive) {
29080
+ const store = structuredClone(existing);
29081
+ const vault = structuredClone(existingVault);
29082
+ let imported = 0;
29083
+ let overwritten = 0;
29084
+ let skipped = 0;
29085
+ const selected = [];
29086
+ for (const profile of payload.profiles) {
29087
+ store[profile.harness] ||= {};
29088
+ const exists = store[profile.harness][profile.name] !== undefined;
29089
+ if (exists && conflictPolicy === "skip") {
29090
+ skipped++;
29091
+ continue;
29092
+ }
29093
+ selected.push(profile);
29094
+ }
29095
+ const providerMap = new Map;
29096
+ for (const provider of payload.providers ?? []) {
29097
+ const targetId = this.availableProviderId(provider.id, vault);
29098
+ vault.entries[targetId] = {
29099
+ id: targetId,
29100
+ name: provider.name,
29101
+ api_key: this.crypto.encrypt(provider.apiKey),
29102
+ notes: provider.notes,
29103
+ endpoints: provider.endpoints,
29104
+ created_at: new Date().toISOString(),
29105
+ updated_at: new Date().toISOString()
29106
+ };
29107
+ providerMap.set(provider.id, targetId);
29108
+ }
29109
+ for (const profile of selected) {
29110
+ store[profile.harness] ||= {};
29111
+ const exists = store[profile.harness][profile.name] !== undefined;
29112
+ store[profile.harness][profile.name] = this.toStored(profile);
29113
+ const mappedProvider = profile.providerId ? providerMap.get(profile.providerId) : undefined;
29114
+ if (mappedProvider) {
29115
+ store[profile.harness][profile.name].provider_id = mappedProvider;
29116
+ store[profile.harness][profile.name].provider_endpoint = profile.providerEndpoint;
29117
+ }
29118
+ if (exists) {
29119
+ overwritten++;
29120
+ } else {
29121
+ imported++;
29122
+ }
29123
+ }
29124
+ return {
29125
+ store,
29126
+ vault,
29127
+ imported,
29128
+ overwritten,
29129
+ skipped,
29130
+ providersCopied: providerMap.size,
29131
+ codexActivationAuthEffect: this.codexActivationAuthEffect(payload, store, restoreActive)
29132
+ };
29142
29133
  }
29143
- return `${apiKey.slice(0, 4)}${"•".repeat(6)}${apiKey.slice(-4)}`;
29144
- }
29145
- function uniqueName(base, existing) {
29146
- if (!existing.has(base)) {
29147
- return base;
29134
+ codexActivationAuthEffect(payload, store, restoreActive) {
29135
+ if (!restoreActive) {
29136
+ return "none";
29137
+ }
29138
+ const active = payload.active.find((item) => item.harness === "codex");
29139
+ if (!active) {
29140
+ return "none";
29141
+ }
29142
+ if (active.official) {
29143
+ return "official-cleanup";
29144
+ }
29145
+ const profile = store.codex?.[active.name];
29146
+ if (!profile) {
29147
+ return "none";
29148
+ }
29149
+ if (profile.overrides?.auth !== undefined) {
29150
+ return "auth-override";
29151
+ }
29152
+ return profile.extras?.authMode === "openai_auth" ? "openai-api-key" : "none";
29148
29153
  }
29149
- let suffix = 2;
29150
- while (existing.has(`${base}-${suffix}`)) {
29151
- suffix += 1;
29154
+ validateProfile(profile) {
29155
+ if (!profile.name || profile.name.length > 120 || /[\\/]/.test(profile.name)) {
29156
+ throw new HttpError(400, "导出文件包含无效的配置名称");
29157
+ }
29158
+ this.adapters.get(profile.harness).validate?.({
29159
+ name: profile.name,
29160
+ baseUrl: profile.baseUrl,
29161
+ apiKey: profile.apiKey,
29162
+ model: profile.model,
29163
+ extras: profile.extras
29164
+ });
29152
29165
  }
29153
- return `${base}-${suffix}`;
29154
- }
29155
-
29156
- // src/http/routes/scan.ts
29157
- function createScanRoutes(services) {
29158
- const app = new Hono2;
29159
- const scan = services.get(IScanService);
29160
- app.get("/", (c) => c.json({ items: scan.scan() }));
29161
- app.post("/import", async (c) => {
29162
- const body = await readJsonBody(c, scanImportRequestSchema);
29163
- return c.json(scan.importSelections(body.selections));
29164
- });
29165
- return app;
29166
- }
29167
-
29168
- // src/services/transfer.ts
29169
- import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes4, scryptSync } from "node:crypto";
29170
-
29171
- // src/services/codex-login-cache.ts
29172
- import { lstatSync as lstatSync2 } from "node:fs";
29173
- import { join as join12 } from "node:path";
29174
- import { isDeepStrictEqual } from "node:util";
29175
- var AUTH_FILE = "auth.json";
29176
- var MAX_CACHE_BYTES = 1024 * 1024;
29177
- var ICodexLoginCacheService = createDecorator("codexLoginCacheService");
29178
- var _dec = [
29179
- inject(IEnvironmentService, IFileService)
29180
- ];
29181
- var _init = __decoratorStart(undefined);
29182
-
29183
- class CodexLoginCacheService {
29184
- environment;
29185
- files;
29186
- constructor(environment, files) {
29187
- this.environment = environment;
29188
- this.files = files;
29166
+ toStored(profile) {
29167
+ return {
29168
+ base_url: profile.baseUrl,
29169
+ api_key: this.crypto.encrypt(profile.apiKey),
29170
+ model: profile.model,
29171
+ notes: profile.notes,
29172
+ extras: profile.extras,
29173
+ overrides: profile.overrides,
29174
+ updated_at: new Date().toISOString()
29175
+ };
29189
29176
  }
29190
- exists() {
29191
- const file2 = this.path();
29192
- this.assertDirectory(false);
29193
- return this.assertRegularFile(file2, false);
29177
+ readStore() {
29178
+ return this.files.readJsonStrict(this.environment.files.profiles, {});
29194
29179
  }
29195
- readOptional() {
29196
- const file2 = this.path();
29197
- this.assertDirectory(false);
29198
- if (!this.assertRegularFile(file2, false)) {
29199
- return;
29200
- }
29201
- const content = this.files.readOptional(file2);
29202
- if (content === undefined) {
29203
- return;
29180
+ readVault() {
29181
+ return this.files.readJsonStrict(this.environment.files.vault, {
29182
+ version: 1,
29183
+ entries: {}
29184
+ });
29185
+ }
29186
+ availableProviderId(sourceId, vault) {
29187
+ if (!vault.entries[sourceId])
29188
+ return sourceId;
29189
+ const base = `${sourceId}-imported`.slice(0, 60);
29190
+ let candidate = base;
29191
+ let index = 2;
29192
+ while (vault.entries[candidate]) {
29193
+ candidate = `${base}-${index}`.slice(0, 64);
29194
+ index++;
29204
29195
  }
29205
- this.validate(content);
29206
- return content;
29196
+ return candidate;
29207
29197
  }
29208
- matchesCurrent(content) {
29209
- this.validate(content);
29210
- const current = this.readOptional();
29211
- return current !== undefined && isDeepStrictEqual(JSON.parse(content), JSON.parse(current));
29198
+ restore(path, snapshot) {
29199
+ try {
29200
+ if (snapshot === undefined)
29201
+ this.files.remove(path);
29202
+ else
29203
+ this.files.writeSecure(path, snapshot);
29204
+ } catch {}
29212
29205
  }
29213
- validate(content) {
29214
- if (Buffer.byteLength(content, "utf8") > MAX_CACHE_BYTES) {
29215
- throw new HttpError(400, "Codex 登录缓存过大,拒绝迁移", {
29216
- code: ERROR_CODES.codexCacheTooLarge
29217
- });
29206
+ resolveKey(stored) {
29207
+ if (!stored.provider_id) {
29208
+ return this.crypto.decrypt(stored.api_key);
29218
29209
  }
29219
29210
  try {
29220
- const value = JSON.parse(content);
29221
- if (!isPlainObject3(value)) {
29222
- throw new Error("not an object");
29223
- }
29211
+ return this.vault.decrypt(stored.provider_id);
29224
29212
  } catch {
29225
- throw new HttpError(400, "Codex 登录缓存不是有效的 JSON 对象,拒绝迁移", {
29226
- code: ERROR_CODES.codexCacheInvalidJson
29227
- });
29213
+ return this.crypto.decrypt(stored.api_key);
29228
29214
  }
29229
29215
  }
29230
- prepareWrite(content) {
29231
- this.validate(content);
29232
- const directory = this.assertDirectory(true);
29233
- const path = join12(directory, AUTH_FILE);
29234
- this.assertRegularFile(path, false);
29235
- return { key: CODEX_AUTH_TARGET, path, content };
29236
- }
29237
- write(content) {
29238
- const write = this.prepareWrite(content);
29239
- this.files.writeUserSecretFile(write.path, write.content);
29240
- }
29241
- path() {
29242
- return join12(this.environment.harnessHomes.codex, AUTH_FILE);
29216
+ assertPassphrase(passphrase) {
29217
+ if (passphrase.length < 8) {
29218
+ throw new HttpError(400, "迁移密码至少需要 8 个字符");
29219
+ }
29243
29220
  }
29244
- assertDirectory(create) {
29245
- const directory = this.environment.harnessHomes.codex;
29246
- try {
29247
- const stat = lstatSync2(directory);
29248
- if (stat.isSymbolicLink() || !stat.isDirectory()) {
29249
- throw new HttpError(400, "Codex 配置目录必须是普通目录,拒绝迁移登录缓存", {
29250
- code: ERROR_CODES.codexConfigDirNotRegular
29251
- });
29252
- }
29253
- return directory;
29254
- } catch (error52) {
29255
- if (error52.code !== "ENOENT") {
29256
- throw error52;
29257
- }
29258
- if (!create) {
29259
- return directory;
29260
- }
29261
- this.files.ensureDir(directory);
29262
- const created = lstatSync2(directory);
29263
- if (created.isSymbolicLink() || !created.isDirectory()) {
29264
- throw new HttpError(400, "Codex 配置目录必须是普通目录,拒绝迁移登录缓存", {
29265
- code: ERROR_CODES.codexConfigDirNotRegular
29266
- });
29267
- }
29268
- return directory;
29221
+ }
29222
+ TransferService = __decorateElement(_init, 0, "TransferService", _dec, TransferService);
29223
+ __runInitializers(_init, 1, TransferService);
29224
+ __decoratorMetadata(_init, TransferService);
29225
+ let _TransferService = TransferService;
29226
+ function encrypt(payload, passphrase) {
29227
+ const salt = randomBytes4(16);
29228
+ const iv = randomBytes4(12);
29229
+ const key = scryptSync(passphrase, salt, 32);
29230
+ const cipher = createCipheriv2("aes-256-gcm", key, iv);
29231
+ const data = Buffer.concat([cipher.update(JSON.stringify(payload), "utf8"), cipher.final()]);
29232
+ return {
29233
+ format: FORMAT,
29234
+ version: VERSION,
29235
+ kdf: { name: "scrypt", salt: salt.toString("base64url") },
29236
+ cipher: {
29237
+ name: "aes-256-gcm",
29238
+ iv: iv.toString("base64url"),
29239
+ tag: cipher.getAuthTag().toString("base64url"),
29240
+ data: data.toString("base64url")
29269
29241
  }
29270
- }
29271
- assertRegularFile(file2, required2) {
29272
- try {
29273
- const stat = lstatSync2(file2);
29274
- if (stat.isSymbolicLink() || !stat.isFile()) {
29275
- throw new HttpError(400, "Codex 登录缓存必须是普通文件,拒绝迁移", {
29276
- code: ERROR_CODES.codexCacheNotRegular
29277
- });
29278
- }
29279
- if (stat.size > MAX_CACHE_BYTES) {
29280
- throw new HttpError(400, "Codex 登录缓存过大,拒绝迁移", {
29281
- code: ERROR_CODES.codexCacheTooLarge
29282
- });
29283
- }
29284
- return true;
29285
- } catch (error52) {
29286
- if (error52.code === "ENOENT" && !required2) {
29287
- return false;
29288
- }
29289
- throw error52;
29242
+ };
29243
+ }
29244
+ function decrypt(envelope, passphrase) {
29245
+ try {
29246
+ 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) {
29247
+ throw new Error("invalid envelope");
29290
29248
  }
29249
+ const salt = Buffer.from(envelope.kdf.salt, "base64url");
29250
+ const key = scryptSync(passphrase, salt, 32);
29251
+ const decipher = createDecipheriv2("aes-256-gcm", key, Buffer.from(envelope.cipher.iv, "base64url"));
29252
+ decipher.setAuthTag(Buffer.from(envelope.cipher.tag, "base64url"));
29253
+ const plain = Buffer.concat([
29254
+ decipher.update(Buffer.from(envelope.cipher.data, "base64url")),
29255
+ decipher.final()
29256
+ ]).toString("utf8");
29257
+ return JSON.parse(plain);
29258
+ } catch {
29259
+ throw new HttpError(400, "迁移密码错误或导出文件已损坏");
29291
29260
  }
29292
29261
  }
29293
- CodexLoginCacheService = __decorateElement(_init, 0, "CodexLoginCacheService", _dec, CodexLoginCacheService);
29294
- __runInitializers(_init, 1, CodexLoginCacheService);
29295
- __decoratorMetadata(_init, CodexLoginCacheService);
29296
- let _CodexLoginCacheService = CodexLoginCacheService;
29297
- function isPlainObject3(value) {
29298
- return typeof value === "object" && value !== null && !Array.isArray(value);
29262
+ function profileId(harness, name) {
29263
+ return `${harness}\x00${name}`;
29264
+ }
29265
+ function isStringRecord(value) {
29266
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((item) => typeof item === "string");
29267
+ }
29268
+ function isPortableProfile(value) {
29269
+ if (typeof value !== "object" || value === null) {
29270
+ return false;
29271
+ }
29272
+ const profile = value;
29273
+ 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) && (profile.providerId === undefined || typeof profile.providerId === "string") && (profile.providerEndpoint === undefined || typeof profile.providerEndpoint === "string");
29274
+ }
29275
+ function isPortableProvider(value) {
29276
+ if (typeof value !== "object" || value === null)
29277
+ return false;
29278
+ const provider = value;
29279
+ return typeof provider.id === "string" && provider.id.length > 0 && provider.id.length <= 64 && !/[\\/]/.test(provider.id) && provider.id !== "__proto__" && provider.id !== "constructor" && typeof provider.name === "string" && provider.name.length > 0 && typeof provider.apiKey === "string" && provider.apiKey.length > 0 && (provider.notes === undefined || typeof provider.notes === "string") && Array.isArray(provider.endpoints) && provider.endpoints.every((endpoint) => typeof endpoint?.key === "string" && typeof endpoint.label === "string" && typeof endpoint.baseUrl === "string");
29280
+ }
29281
+ function isPortableActive(value) {
29282
+ if (typeof value !== "object" || value === null) {
29283
+ return false;
29284
+ }
29285
+ const active = value;
29286
+ return typeof active.harness === "string" && isHarnessId(active.harness) && typeof active.name === "string" && typeof active.official === "boolean";
29299
29287
  }
29300
29288
 
29301
- // src/services/transfer.ts
29302
- var FORMAT = "harness-switch-encrypted-export";
29303
- var VERSION = 1;
29304
- var MAX_ENCRYPTED_BYTES = 10 * 1024 * 1024;
29305
- var ITransferService = createDecorator("transferService");
29289
+ // src/services/github-sync.ts
29290
+ var DEFAULT_CLIENT_ID = process.env.GITHUB_CLIENT_ID || "178c6fc778ccc68e1d6a";
29291
+ var GIST_FILENAME = "harness-switch-backup.json";
29292
+ var GIST_DESCRIPTION = "harness-switch sync vault (Encrypted backup)";
29293
+ var USER_AGENT = "harness-switch";
29294
+ var IGitHubSyncService = createDecorator("githubSyncService");
29306
29295
  var _dec = [
29307
- inject(IEnvironmentService, IFileService, ICryptoService, ICodexLoginCacheService, ILiveWriteService, IAdapterRegistry, IActivationService, IVaultService)
29296
+ inject(IEnvironmentService, IFileService, ICryptoService, ITransferService, IProfileService, IVaultService, ILogService)
29308
29297
  ];
29309
29298
  var _init = __decoratorStart(undefined);
29310
29299
 
29311
- class TransferService {
29300
+ class GitHubSyncService {
29312
29301
  environment;
29313
29302
  files;
29314
29303
  crypto;
29315
- codexLoginCache;
29316
- liveWrite;
29317
- adapters;
29318
- activation;
29304
+ transfer;
29305
+ profiles;
29319
29306
  vault;
29320
- constructor(environment, files, crypto2, codexLoginCache, liveWrite, adapters, activation, vault) {
29307
+ log;
29308
+ constructor(environment, files, crypto2, transfer, profiles, vault, log) {
29321
29309
  this.environment = environment;
29322
29310
  this.files = files;
29323
29311
  this.crypto = crypto2;
29324
- this.codexLoginCache = codexLoginCache;
29325
- this.liveWrite = liveWrite;
29326
- this.adapters = adapters;
29327
- this.activation = activation;
29312
+ this.transfer = transfer;
29313
+ this.profiles = profiles;
29328
29314
  this.vault = vault;
29315
+ this.log = log;
29329
29316
  }
29330
- exportPreview() {
29331
- return { codexLoginCacheAvailable: this.codexLoginCache.exists() };
29317
+ readStore() {
29318
+ return this.files.readJson(this.environment.files.github, {});
29332
29319
  }
29333
- exportAll(passphrase, includeCodexLoginCache) {
29334
- this.assertPassphrase(passphrase);
29335
- const codexLoginCache = includeCodexLoginCache ? this.codexLoginCache.readOptional() : undefined;
29336
- if (includeCodexLoginCache && codexLoginCache === undefined) {
29337
- throw new HttpError(400, "当前用户没有可导出的 Codex 登录缓存");
29338
- }
29320
+ writeStore(store) {
29321
+ this.files.writeJson(this.environment.files.github, store);
29322
+ }
29323
+ getToken() {
29339
29324
  const store = this.readStore();
29340
- const vault = this.readVault();
29341
- const providers = Object.values(vault.entries).map((entry) => ({
29342
- id: entry.id,
29343
- name: entry.name,
29344
- apiKey: this.crypto.decrypt(entry.api_key),
29345
- notes: entry.notes,
29346
- endpoints: entry.endpoints
29347
- }));
29348
- const profiles = [];
29349
- for (const harness of HARNESS_IDS) {
29350
- for (const [name, stored] of Object.entries(store[harness] ?? {})) {
29351
- profiles.push({
29352
- harness,
29353
- name,
29354
- baseUrl: stored.base_url || "",
29355
- apiKey: this.resolveKey(stored),
29356
- model: stored.model || "",
29357
- notes: stored.notes || "",
29358
- extras: stored.extras ?? {},
29359
- overrides: stored.overrides ?? {},
29360
- ...stored.provider_id && vault.entries[stored.provider_id] ? {
29361
- providerId: stored.provider_id,
29362
- ...stored.provider_endpoint ? { providerEndpoint: stored.provider_endpoint } : {}
29363
- } : {}
29325
+ if (!store.token)
29326
+ return;
29327
+ const token = this.crypto.decrypt(store.token);
29328
+ return token ? token.trim() : undefined;
29329
+ }
29330
+ requireToken() {
29331
+ const token = this.getToken();
29332
+ if (!token) {
29333
+ throw new HttpError(401, "未连接 GitHub,请先登录", { code: ERROR_CODES.githubNotConnected });
29334
+ }
29335
+ return token;
29336
+ }
29337
+ countAllProfiles() {
29338
+ return HARNESS_IDS.reduce((acc, harness) => acc + this.profiles.list(harness).length, 0);
29339
+ }
29340
+ async githubFetch(path, options = {}, token) {
29341
+ const bearer = token || this.requireToken();
29342
+ const headers = {
29343
+ Accept: "application/vnd.github+json",
29344
+ "User-Agent": USER_AGENT,
29345
+ "X-GitHub-Api-Version": "2022-11-28",
29346
+ Authorization: `Bearer ${bearer}`,
29347
+ ...options.headers
29348
+ };
29349
+ const url2 = path.startsWith("http") ? path : `https://api.github.com${path}`;
29350
+ const response = await fetch(url2, {
29351
+ ...options,
29352
+ headers
29353
+ });
29354
+ if (response.status === 401) {
29355
+ throw new HttpError(401, "GitHub 授权已失效或无效,请重新登录", {
29356
+ code: ERROR_CODES.githubAuthFailed
29357
+ });
29358
+ }
29359
+ if (response.status === 403) {
29360
+ const remaining = response.headers.get("x-ratelimit-remaining");
29361
+ if (remaining === "0") {
29362
+ throw new HttpError(403, "GitHub API 请求速率超限,请稍后再试", {
29363
+ code: ERROR_CODES.githubRateLimitExceeded
29364
29364
  });
29365
29365
  }
29366
29366
  }
29367
- const active = HARNESS_IDS.flatMap((harness) => {
29368
- const entry = this.activation.getActive(harness);
29369
- return entry ? [
29370
- {
29371
- harness,
29372
- name: entry.name,
29373
- official: entry.official === true
29367
+ if (!response.ok) {
29368
+ const errorText = await response.text();
29369
+ let errorMsg = `GitHub 请求失败 (${response.status})`;
29370
+ try {
29371
+ const errorJson = JSON.parse(errorText);
29372
+ if (errorJson.message) {
29373
+ errorMsg = `GitHub: ${errorJson.message}`;
29374
29374
  }
29375
- ] : [];
29376
- });
29377
- return encrypt({
29378
- format: "harness-switch-portable-config",
29379
- version: VERSION,
29380
- exportedAt: new Date().toISOString(),
29381
- profiles,
29382
- providers,
29383
- active,
29384
- codexLoginCache
29385
- }, passphrase);
29375
+ } catch {}
29376
+ throw new HttpError(response.status, errorMsg, { code: ERROR_CODES.requestFailed });
29377
+ }
29378
+ return await response.json();
29386
29379
  }
29387
- preview(envelope, passphrase, conflictPolicy, restoreActive) {
29388
- this.assertConflictPolicy(conflictPolicy);
29389
- const payload = this.decrypt(envelope, passphrase);
29390
- const existing = this.readStore();
29391
- const plan = this.planImport(payload, existing, this.readVault(), conflictPolicy, restoreActive);
29392
- const targetCodexLoginCacheExists = this.codexLoginCache.exists();
29393
- return {
29394
- exportedAt: payload.exportedAt,
29395
- profileCount: payload.profiles.length,
29396
- providerCount: payload.providers?.length ?? 0,
29397
- harnesses: HARNESS_IDS.map((harness) => ({
29398
- harness,
29399
- profiles: payload.profiles.filter((profile) => profile.harness === harness).length
29400
- })).filter((item) => item.profiles > 0),
29401
- conflicts: payload.profiles.filter((profile) => existing[profile.harness]?.[profile.name] !== undefined).map(({ harness, name }) => ({ harness, name })),
29402
- activeCount: payload.active.length,
29403
- conflictPolicy,
29404
- restoreActive,
29405
- codexActivationAuthEffect: plan.codexActivationAuthEffect,
29406
- codexLoginCache: {
29407
- available: payload.codexLoginCache !== undefined,
29408
- targetExists: targetCodexLoginCacheExists,
29409
- migrationNeeded: payload.codexLoginCache !== undefined && !this.codexLoginCache.matchesCurrent(payload.codexLoginCache)
29380
+ async getStatus() {
29381
+ const store = this.readStore();
29382
+ const token = this.getToken();
29383
+ if (!token) {
29384
+ return { connected: false };
29385
+ }
29386
+ try {
29387
+ const user = await this.githubFetch("/user", {}, token);
29388
+ let gistId = store.gistId;
29389
+ let gistUpdatedAt;
29390
+ if (gistId) {
29391
+ try {
29392
+ const gist = await this.githubFetch(`/gists/${gistId}`, {}, token);
29393
+ gistUpdatedAt = gist.updated_at;
29394
+ } catch {
29395
+ gistId = undefined;
29396
+ }
29397
+ }
29398
+ if (!gistId) {
29399
+ const existingGist = await this.findSyncGist(token);
29400
+ if (existingGist) {
29401
+ gistId = existingGist.id;
29402
+ gistUpdatedAt = existingGist.updated_at;
29403
+ this.writeStore({
29404
+ ...store,
29405
+ username: user.login,
29406
+ avatarUrl: user.avatar_url,
29407
+ gistId
29408
+ });
29409
+ }
29410
29410
  }
29411
- };
29411
+ return {
29412
+ connected: true,
29413
+ username: user.login,
29414
+ avatarUrl: user.avatar_url,
29415
+ gistId,
29416
+ gistUpdatedAt,
29417
+ lastSyncedAt: store.lastSyncedAt
29418
+ };
29419
+ } catch {
29420
+ return { connected: false };
29421
+ }
29412
29422
  }
29413
- importAll(envelope, passphrase, conflictPolicy, restoreActive, migrateCodexLoginCache) {
29414
- this.assertConflictPolicy(conflictPolicy);
29415
- const payload = this.decrypt(envelope, passphrase);
29416
- if (migrateCodexLoginCache && payload.codexLoginCache === undefined) {
29417
- throw new HttpError(400, "导出包不包含可迁移的 Codex 登录缓存");
29423
+ async findSyncGist(token) {
29424
+ try {
29425
+ const gists = await this.githubFetch("/gists?per_page=100", {}, token);
29426
+ return gists.find((g) => g.files && Boolean(g.files[GIST_FILENAME]));
29427
+ } catch {
29428
+ return;
29418
29429
  }
29419
- const cacheWrite = migrateCodexLoginCache && !this.codexLoginCache.matchesCurrent(payload.codexLoginCache) ? [
29420
- {
29421
- ...this.codexLoginCache.prepareWrite(payload.codexLoginCache),
29422
- format: "json",
29423
- secret: true
29424
- }
29425
- ] : [];
29426
- const plan = this.planImport(payload, this.readStore(), this.readVault(), conflictPolicy, restoreActive);
29427
- const profilesPath = this.environment.files.profiles;
29428
- const vaultPath = this.environment.files.vault;
29429
- const profileSnapshot = this.files.readOptional(profilesPath);
29430
- const vaultSnapshot = this.files.readOptional(vaultPath);
29431
- this.liveWrite.transaction({
29432
- kind: "import",
29433
- harness: "codex",
29434
- profile: "导入登录缓存",
29435
- writes: cacheWrite,
29436
- metadata: ["profiles", "vault"]
29437
- }, () => {
29430
+ }
29431
+ async getDeviceCode(clientId) {
29432
+ const id = clientId || DEFAULT_CLIENT_ID;
29433
+ const response = await fetch("https://github.com/login/device/code", {
29434
+ method: "POST",
29435
+ headers: {
29436
+ Accept: "application/json",
29437
+ "Content-Type": "application/json",
29438
+ "User-Agent": USER_AGENT
29439
+ },
29440
+ body: JSON.stringify({
29441
+ client_id: id,
29442
+ scope: "gist"
29443
+ })
29444
+ });
29445
+ if (!response.ok) {
29446
+ throw new HttpError(response.status, "获取 GitHub 设备验证码失败", {
29447
+ code: ERROR_CODES.requestFailed
29448
+ });
29449
+ }
29450
+ const data = await response.json();
29451
+ if (data.error) {
29452
+ throw new HttpError(400, data.error_description || data.error, {
29453
+ code: ERROR_CODES.githubAuthFailed
29454
+ });
29455
+ }
29456
+ return {
29457
+ deviceCode: data.device_code,
29458
+ userCode: data.user_code,
29459
+ verificationUri: data.verification_uri,
29460
+ expiresIn: data.expires_in,
29461
+ interval: data.interval
29462
+ };
29463
+ }
29464
+ async pollDeviceCode(deviceCode, clientId) {
29465
+ const id = clientId || DEFAULT_CLIENT_ID;
29466
+ const response = await fetch("https://github.com/login/oauth/access_token", {
29467
+ method: "POST",
29468
+ headers: {
29469
+ Accept: "application/json",
29470
+ "Content-Type": "application/json",
29471
+ "User-Agent": USER_AGENT
29472
+ },
29473
+ body: JSON.stringify({
29474
+ client_id: id,
29475
+ device_code: deviceCode,
29476
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code"
29477
+ })
29478
+ });
29479
+ if (!response.ok) {
29480
+ return { status: "error", error: "GitHub 认证请求失败" };
29481
+ }
29482
+ const data = await response.json();
29483
+ if (data.error) {
29484
+ this.log.info(`[github-sync] pollDeviceCode error response: ${data.error} - ${data.error_description || ""}`);
29485
+ if (data.error === "authorization_pending") {
29486
+ return { status: "pending", interval: data.interval };
29487
+ }
29488
+ if (data.error === "slow_down") {
29489
+ const nextInterval = (data.interval || 5) + 5;
29490
+ return { status: "pending", interval: nextInterval };
29491
+ }
29492
+ if (data.error === "expired_token") {
29493
+ return { status: "expired", error: "设备码已过期,请重新获取" };
29494
+ }
29495
+ if (data.error === "access_denied") {
29496
+ return { status: "error", error: "已拒绝授权请求" };
29497
+ }
29498
+ return { status: "error", error: data.error_description || data.error };
29499
+ }
29500
+ if (data.access_token) {
29501
+ this.log.info("[github-sync] Device code authorized successfully, saving token");
29502
+ let username;
29503
+ let avatarUrl;
29438
29504
  try {
29439
- this.files.writeJson(vaultPath, plan.vault);
29440
- this.files.writeJson(profilesPath, plan.store);
29441
- } catch (error52) {
29442
- this.restore(vaultPath, vaultSnapshot);
29443
- this.restore(profilesPath, profileSnapshot);
29444
- throw error52;
29505
+ const user = await this.githubFetch("/user", {}, data.access_token);
29506
+ username = user.login;
29507
+ avatarUrl = user.avatar_url;
29508
+ } catch (e) {
29509
+ this.log.warn(`[github-sync] 获取用户信息失败: ${String(e)}`);
29445
29510
  }
29511
+ this.saveToken(data.access_token, username, avatarUrl);
29512
+ return { status: "authorized", username };
29513
+ }
29514
+ return { status: "error", error: "未返回有效令牌" };
29515
+ }
29516
+ async authenticateWithToken(token) {
29517
+ const trimmed = token.trim();
29518
+ if (!trimmed) {
29519
+ throw new HttpError(400, "Token 不能为空", { code: ERROR_CODES.githubAuthFailed });
29520
+ }
29521
+ const user = await this.githubFetch("/user", {}, trimmed);
29522
+ this.saveToken(trimmed, user.login, user.avatar_url);
29523
+ return this.getStatus();
29524
+ }
29525
+ saveToken(token, username, avatarUrl) {
29526
+ const store = this.readStore();
29527
+ const encryptedToken = this.crypto.encrypt(token);
29528
+ this.writeStore({
29529
+ ...store,
29530
+ token: encryptedToken,
29531
+ username: username || store.username,
29532
+ avatarUrl: avatarUrl || store.avatarUrl
29446
29533
  });
29447
- const warnings = [];
29448
- let activeRestored = 0;
29449
- if (restoreActive) {
29450
- for (const active of payload.active) {
29451
- try {
29452
- if (active.official) {
29453
- this.activation.activateOfficial(active.harness);
29454
- } else if (plan.store[active.harness]?.[active.name]) {
29455
- this.activation.activate(active.harness, active.name);
29456
- } else {
29457
- throw new Error("对应配置不存在");
29534
+ }
29535
+ disconnect() {
29536
+ const store = this.readStore();
29537
+ this.writeStore({
29538
+ ...store,
29539
+ token: undefined,
29540
+ username: undefined,
29541
+ avatarUrl: undefined
29542
+ });
29543
+ }
29544
+ async push(passphrase, includeCodexLoginCache = false) {
29545
+ const token = this.requireToken();
29546
+ const envelope = this.transfer.exportAll(passphrase, includeCodexLoginCache);
29547
+ const content = JSON.stringify(envelope, null, 2);
29548
+ const store = this.readStore();
29549
+ let gistId = store.gistId;
29550
+ if (gistId) {
29551
+ try {
29552
+ const updatedGist = await this.githubFetch(`/gists/${gistId}`, {
29553
+ method: "PATCH",
29554
+ body: JSON.stringify({
29555
+ description: GIST_DESCRIPTION,
29556
+ files: {
29557
+ [GIST_FILENAME]: { content }
29558
+ }
29559
+ })
29560
+ }, token);
29561
+ const now2 = new Date().toISOString();
29562
+ this.writeStore({ ...store, gistId: updatedGist.id, lastSyncedAt: now2 });
29563
+ return {
29564
+ ok: true,
29565
+ gistId: updatedGist.id,
29566
+ gistUpdatedAt: updatedGist.updated_at,
29567
+ lastSyncedAt: now2,
29568
+ exportedProfilesCount: this.countAllProfiles(),
29569
+ exportedVaultCount: this.vault.list().length
29570
+ };
29571
+ } catch (err) {
29572
+ this.log.warn(`[github-sync] 更新 Gist 失败,尝试重新查找或创建: ${String(err)}`);
29573
+ gistId = undefined;
29574
+ }
29575
+ }
29576
+ const existingGist = await this.findSyncGist(token);
29577
+ if (existingGist) {
29578
+ const updatedGist = await this.githubFetch(`/gists/${existingGist.id}`, {
29579
+ method: "PATCH",
29580
+ body: JSON.stringify({
29581
+ description: GIST_DESCRIPTION,
29582
+ files: {
29583
+ [GIST_FILENAME]: { content }
29458
29584
  }
29459
- activeRestored++;
29460
- } catch (error52) {
29461
- const reason2 = error52.message;
29462
- warnings.push({
29463
- message: `${active.harness}/${active.name} 未能恢复激活状态:${reason2}`,
29464
- code: WARNING_CODES.transferActiveRestoreFailed,
29465
- params: { harness: active.harness, profile: active.name, reason: reason2 }
29466
- });
29585
+ })
29586
+ }, token);
29587
+ const now2 = new Date().toISOString();
29588
+ this.writeStore({ ...store, gistId: updatedGist.id, lastSyncedAt: now2 });
29589
+ return {
29590
+ ok: true,
29591
+ gistId: updatedGist.id,
29592
+ gistUpdatedAt: updatedGist.updated_at,
29593
+ lastSyncedAt: now2,
29594
+ exportedProfilesCount: this.countAllProfiles(),
29595
+ exportedVaultCount: this.vault.list().length
29596
+ };
29597
+ }
29598
+ const newGist = await this.githubFetch("/gists", {
29599
+ method: "POST",
29600
+ body: JSON.stringify({
29601
+ description: GIST_DESCRIPTION,
29602
+ public: false,
29603
+ files: {
29604
+ [GIST_FILENAME]: { content }
29467
29605
  }
29606
+ })
29607
+ }, token);
29608
+ const now = new Date().toISOString();
29609
+ this.writeStore({ ...store, gistId: newGist.id, lastSyncedAt: now });
29610
+ return {
29611
+ ok: true,
29612
+ gistId: newGist.id,
29613
+ gistUpdatedAt: newGist.updated_at,
29614
+ lastSyncedAt: now,
29615
+ exportedProfilesCount: this.countAllProfiles(),
29616
+ exportedVaultCount: this.vault.list().length
29617
+ };
29618
+ }
29619
+ async fetchGistEnvelope(token) {
29620
+ const store = this.readStore();
29621
+ let gistId = store.gistId;
29622
+ if (!gistId) {
29623
+ const existing = await this.findSyncGist(token);
29624
+ if (!existing) {
29625
+ throw new HttpError(404, "云端未找到 harness-switch 同步备份 Gist", {
29626
+ code: ERROR_CODES.githubGistNotFound
29627
+ });
29628
+ }
29629
+ gistId = existing.id;
29630
+ this.writeStore({ ...store, gistId });
29631
+ }
29632
+ const gist = await this.githubFetch(`/gists/${gistId}`, {}, token);
29633
+ const file2 = gist.files?.[GIST_FILENAME];
29634
+ if (!file2) {
29635
+ throw new HttpError(404, "Gist 中未找到配置文件", {
29636
+ code: ERROR_CODES.githubGistNotFound
29637
+ });
29638
+ }
29639
+ let rawContent = file2.content;
29640
+ if (file2.truncated && file2.raw_url) {
29641
+ const rawRes = await fetch(file2.raw_url, {
29642
+ headers: { Authorization: `Bearer ${token}`, "User-Agent": USER_AGENT }
29643
+ });
29644
+ if (rawRes.ok) {
29645
+ rawContent = await rawRes.text();
29468
29646
  }
29469
29647
  }
29648
+ if (!rawContent) {
29649
+ throw new HttpError(400, "云端备份文件内容为空", {
29650
+ code: ERROR_CODES.transferEnvelopeInvalid
29651
+ });
29652
+ }
29653
+ try {
29654
+ const envelope = JSON.parse(rawContent);
29655
+ if (envelope.format !== "harness-switch-encrypted-export") {
29656
+ throw new HttpError(400, "不支持的备份文件格式", {
29657
+ code: ERROR_CODES.transferEnvelopeInvalid
29658
+ });
29659
+ }
29660
+ return { envelope, updatedAt: gist.updated_at };
29661
+ } catch (err) {
29662
+ if (err instanceof HttpError)
29663
+ throw err;
29664
+ throw new HttpError(400, "云端备份文件损坏或非有效 JSON", {
29665
+ code: ERROR_CODES.transferEnvelopeInvalid
29666
+ });
29667
+ }
29668
+ }
29669
+ async pullPreview(passphrase, conflictPolicy = "skip", restoreActive = false) {
29670
+ const token = this.requireToken();
29671
+ const { envelope, updatedAt } = await this.fetchGistEnvelope(token);
29672
+ const preview = this.transfer.preview(envelope, passphrase, conflictPolicy, restoreActive);
29470
29673
  return {
29471
- ok: true,
29472
- imported: plan.imported,
29473
- overwritten: plan.overwritten,
29474
- skipped: plan.skipped,
29475
- providersCopied: plan.providersCopied,
29476
- activeRestored,
29477
- codexLoginCacheMigrated: cacheWrite.length > 0,
29478
- warnings
29674
+ gistUpdatedAt: updatedAt,
29675
+ preview
29479
29676
  };
29480
29677
  }
29481
- decrypt(envelope, passphrase) {
29482
- this.assertPassphrase(passphrase);
29483
- const payload = decrypt(envelope, passphrase);
29484
- if (payload.format !== "harness-switch-portable-config" || payload.version !== VERSION || !Array.isArray(payload.profiles) || !Array.isArray(payload.active) || typeof payload.exportedAt !== "string") {
29485
- throw new HttpError(400, "不支持的导出文件格式");
29678
+ async pull(passphrase, conflictPolicy = "skip", restoreActive = false, migrateCodexLoginCache = false) {
29679
+ const token = this.requireToken();
29680
+ const { envelope } = await this.fetchGistEnvelope(token);
29681
+ const result = this.transfer.importAll(envelope, passphrase, conflictPolicy, restoreActive, migrateCodexLoginCache);
29682
+ const store = this.readStore();
29683
+ this.writeStore({ ...store, lastSyncedAt: new Date().toISOString() });
29684
+ return result;
29685
+ }
29686
+ }
29687
+ GitHubSyncService = __decorateElement(_init, 0, "GitHubSyncService", _dec, GitHubSyncService);
29688
+ __runInitializers(_init, 1, GitHubSyncService);
29689
+ __decoratorMetadata(_init, GitHubSyncService);
29690
+ let _GitHubSyncService = GitHubSyncService;
29691
+
29692
+ // src/http/routes/github.ts
29693
+ function createGitHubRoutes(services) {
29694
+ const app = new Hono2;
29695
+ const github = services.get(IGitHubSyncService);
29696
+ app.get("/status", async (c) => {
29697
+ return c.json(await github.getStatus());
29698
+ });
29699
+ app.post("/device/code", async (c) => {
29700
+ const body = await readJsonBody(c, gitHubDeviceCodeRequestSchema);
29701
+ return c.json(await github.getDeviceCode(body.clientId));
29702
+ });
29703
+ app.post("/device/poll", async (c) => {
29704
+ const body = await readJsonBody(c, gitHubDevicePollRequestSchema);
29705
+ return c.json(await github.pollDeviceCode(body.deviceCode, body.clientId));
29706
+ });
29707
+ app.post("/token", async (c) => {
29708
+ const body = await readJsonBody(c, gitHubTokenAuthRequestSchema);
29709
+ return c.json(await github.authenticateWithToken(body.token));
29710
+ });
29711
+ app.post("/disconnect", (c) => {
29712
+ github.disconnect();
29713
+ return c.json({ ok: true });
29714
+ });
29715
+ app.post("/push", async (c) => {
29716
+ const body = await readJsonBody(c, gitHubPushRequestSchema);
29717
+ return c.json(await github.push(body.passphrase, body.includeCodexLoginCache === true));
29718
+ });
29719
+ app.post("/pull/preview", async (c) => {
29720
+ const body = await readJsonBody(c, gitHubPullPreviewRequestSchema);
29721
+ return c.json(await github.pullPreview(body.passphrase, body.conflictPolicy ?? "skip", body.restoreActive === true));
29722
+ });
29723
+ app.post("/pull", async (c) => {
29724
+ const body = await readJsonBody(c, gitHubPullRequestSchema);
29725
+ return c.json(await github.pull(body.passphrase, body.conflictPolicy ?? "skip", body.restoreActive === true, body.migrateCodexLoginCache === true));
29726
+ });
29727
+ return app;
29728
+ }
29729
+
29730
+ // src/http/routes/harnesses.ts
29731
+ function createHarnessRoutes(services) {
29732
+ const app = new Hono2;
29733
+ const harnesses = services.get(IHarnessRegistry);
29734
+ const profiles = services.get(IProfileService);
29735
+ const activation = services.get(IActivationService);
29736
+ const adapters = services.get(IAdapterRegistry);
29737
+ const environment = services.get(IEnvironmentService);
29738
+ const files = services.get(IFileService);
29739
+ const log = services.get(ILogService);
29740
+ const probe = services.get(IProbeService);
29741
+ function summary(id) {
29742
+ const adapter = adapters.get(id);
29743
+ return {
29744
+ id,
29745
+ label: harnesses.label(id),
29746
+ mode: adapter.mode,
29747
+ active: activation.getActive(id),
29748
+ profiles: profiles.list(id),
29749
+ fields: adapter.fields,
29750
+ modelRequired: adapter.modelRequired,
29751
+ targets: adapter.targets(),
29752
+ envVars: adapter.envVarNames,
29753
+ envNote: adapter.envNote,
29754
+ supportsOfficialAuth: adapter.renderOfficial !== undefined
29755
+ };
29756
+ }
29757
+ app.get("/", (c) => c.json({
29758
+ envFile: environment.files.env,
29759
+ items: harnesses.list().map((item) => summary(item.id))
29760
+ }));
29761
+ app.get("/:harnessId", (c) => c.json(summary(harnesses.require(c.req.param("harnessId")))));
29762
+ app.post("/:harnessId/profiles", async (c) => {
29763
+ const harnessId = harnesses.require(c.req.param("harnessId"));
29764
+ const body = await readJsonBody(c, createProfileRequestSchema);
29765
+ const profile = profiles.upsert(harnessId, {
29766
+ name: body.name,
29767
+ baseUrl: body.baseUrl,
29768
+ apiKey: body.apiKey,
29769
+ model: body.model,
29770
+ notes: body.notes,
29771
+ extras: body.extras,
29772
+ overrides: body.overrides,
29773
+ providerId: body.providerId,
29774
+ providerEndpoint: body.providerEndpoint
29775
+ }, true);
29776
+ return c.json(profile, 201);
29777
+ });
29778
+ app.patch("/:harnessId/profiles/:name", async (c) => {
29779
+ const harnessId = harnesses.require(c.req.param("harnessId"));
29780
+ const name = decodeURIComponent(c.req.param("name"));
29781
+ const body = await readJsonBody(c, updateProfileRequestSchema);
29782
+ const wasActive = activation.getActive(harnessId)?.name === name;
29783
+ const snapshot = files.readOptional(environment.files.profiles);
29784
+ let persisted = false;
29785
+ try {
29786
+ const profile = profiles.upsert(harnessId, {
29787
+ name: body.name ?? name,
29788
+ sourceName: name,
29789
+ baseUrl: body.baseUrl,
29790
+ apiKey: body.apiKey,
29791
+ model: body.model,
29792
+ notes: body.notes,
29793
+ extras: body.extras,
29794
+ overrides: body.overrides,
29795
+ providerId: body.providerId,
29796
+ providerEndpoint: body.providerEndpoint
29797
+ }, false);
29798
+ persisted = true;
29799
+ activation.reconcileProfileUpdate(harnessId, name, profile.name);
29800
+ return c.json(profile);
29801
+ } catch (error52) {
29802
+ if (persisted) {
29803
+ restoreProfileStore(files, environment.files.profiles, snapshot);
29804
+ if (wasActive) {
29805
+ try {
29806
+ activation.activate(harnessId, name);
29807
+ } catch (rollbackError) {
29808
+ log.error(`edit rollback: failed to re-activate ${harnessId}/${name}`, rollbackError);
29809
+ }
29810
+ }
29811
+ }
29812
+ throw error52;
29486
29813
  }
29487
- if (payload.profiles.length > 1e4) {
29488
- throw new HttpError(400, "导出文件包含过多配置");
29814
+ });
29815
+ app.delete("/:harnessId/profiles/:name", (c) => {
29816
+ const harnessId = harnesses.require(c.req.param("harnessId"));
29817
+ const name = decodeURIComponent(c.req.param("name"));
29818
+ activation.prepareDelete(harnessId, name);
29819
+ profiles.remove(harnessId, name);
29820
+ return c.json({ ok: true });
29821
+ });
29822
+ app.get("/:harnessId/profiles/:name/preview", (c) => {
29823
+ const harnessId = harnesses.require(c.req.param("harnessId"));
29824
+ const name = decodeURIComponent(c.req.param("name"));
29825
+ return c.json({ targets: activation.preview(harnessId, name) });
29826
+ });
29827
+ app.post("/:harnessId/profiles/:name/probe", async (c) => {
29828
+ const harnessId = harnesses.require(c.req.param("harnessId"));
29829
+ const name = decodeURIComponent(c.req.param("name"));
29830
+ parseWith(probeStoredRequestSchema, await c.req.json().catch(() => ({})));
29831
+ const decrypted = profiles.decrypt(harnessId, name);
29832
+ return c.json({ result: await probe.probe(decrypted) });
29833
+ });
29834
+ app.post("/:harnessId/profiles/:name/activate", (c) => {
29835
+ const harnessId = harnesses.require(c.req.param("harnessId"));
29836
+ const name = decodeURIComponent(c.req.param("name"));
29837
+ const result = activation.activate(harnessId, name);
29838
+ return c.json({ ok: true, envFile: result.envFile, warnings: result.warnings });
29839
+ });
29840
+ app.post("/:harnessId/official/activate", (c) => {
29841
+ const harnessId = harnesses.require(c.req.param("harnessId"));
29842
+ const result = activation.activateOfficial(harnessId);
29843
+ return c.json({ ok: true, envFile: result.envFile, warnings: result.warnings });
29844
+ });
29845
+ return app;
29846
+ }
29847
+ function restoreProfileStore(files, path, snapshot) {
29848
+ if (snapshot === undefined) {
29849
+ files.remove(path);
29850
+ return;
29851
+ }
29852
+ files.writeSecure(path, snapshot);
29853
+ }
29854
+
29855
+ // src/http/routes/operations.ts
29856
+ function createOperationRoutes(services) {
29857
+ const app = new Hono2;
29858
+ const journal = services.get(IJournalService);
29859
+ app.get("/", (c) => {
29860
+ const harnessParam = c.req.query("harness");
29861
+ const items = harnessParam && harnessParam.length > 0 ? journal.list().filter((item) => item.harness === harnessParam) : journal.list();
29862
+ return c.json({ items });
29863
+ });
29864
+ app.get("/:id", (c) => c.json(journal.detail(decodeURIComponent(c.req.param("id")))));
29865
+ app.post("/:id/undo", (c) => c.json({
29866
+ ok: true,
29867
+ receipt: journal.undo(decodeURIComponent(c.req.param("id")))
29868
+ }));
29869
+ return app;
29870
+ }
29871
+
29872
+ // src/http/routes/probe.ts
29873
+ function createProbeRoutes(services) {
29874
+ const app = new Hono2;
29875
+ const vault = services.get(IVaultService);
29876
+ const probe = services.get(IProbeService);
29877
+ app.post("/", async (c) => {
29878
+ const body = await readJsonBody(c, probeRequestSchema);
29879
+ const apiKey = draftKey(vault, body);
29880
+ if (!apiKey) {
29881
+ return c.json({
29882
+ result: {
29883
+ ok: false,
29884
+ code: PROBE_CODES.missingApiKey,
29885
+ message: "未提供 API Key,也无法从凭据库解析,无法测试"
29886
+ }
29887
+ });
29489
29888
  }
29490
- for (const profile of payload.profiles) {
29491
- if (!isPortableProfile(profile)) {
29492
- throw new HttpError(400, "导出文件中的配置数据无效");
29889
+ return c.json({
29890
+ result: await probe.probe({ baseUrl: body.baseUrl, apiKey })
29891
+ });
29892
+ });
29893
+ return app;
29894
+ }
29895
+ function draftKey(vault, body) {
29896
+ if (body.providerId?.trim()) {
29897
+ return vault.decrypt(body.providerId.trim());
29898
+ }
29899
+ return body.apiKey?.trim() ?? "";
29900
+ }
29901
+
29902
+ // src/http/routes/providers.ts
29903
+ function createProviderRoutes(services) {
29904
+ const app = new Hono2;
29905
+ const vault = services.get(IVaultService);
29906
+ const profiles = services.get(IProfileService);
29907
+ const activation = services.get(IActivationService);
29908
+ const log = services.get(ILogService);
29909
+ const probe = services.get(IProbeService);
29910
+ app.get("/", (c) => c.json({ items: vault.list() }));
29911
+ app.get("/:id", (c) => c.json(vault.get(decodeURIComponent(c.req.param("id")))));
29912
+ app.post("/", async (c) => {
29913
+ const body = await readJsonBody(c, createProviderRequestSchema);
29914
+ return c.json({ provider: vault.create(body), warnings: [] }, 201);
29915
+ });
29916
+ app.patch("/:id", async (c) => {
29917
+ const id = decodeURIComponent(c.req.param("id"));
29918
+ const body = await readJsonBody(c, updateProviderRequestSchema);
29919
+ const { provider, affected } = vault.update(id, body);
29920
+ profiles.sweepVaultCache(id, vault.decrypt(id), provider.endpoints);
29921
+ const warnings = [];
29922
+ for (const ref of affected) {
29923
+ if (activation.getActive(ref.harness)?.name !== ref.name) {
29924
+ continue;
29493
29925
  }
29494
- }
29495
- for (const active of payload.active) {
29496
- if (!isPortableActive(active)) {
29497
- throw new HttpError(400, "导出文件中的激活状态无效");
29926
+ const profile = profiles.get(ref.harness, ref.name);
29927
+ if (profile?.providerEndpoint && !provider.endpoints.some((ep) => ep.key === profile.providerEndpoint)) {
29928
+ warnings.push({
29929
+ message: `${ref.harness}/${ref.name}: endpoint ${profile.providerEndpoint} 已不存在,将回退到 provider 首个 endpoint`,
29930
+ code: WARNING_CODES.endpointFallback,
29931
+ params: {
29932
+ harness: ref.harness,
29933
+ profile: ref.name,
29934
+ endpoint: profile.providerEndpoint
29935
+ }
29936
+ });
29498
29937
  }
29499
- }
29500
- if (payload.providers !== undefined) {
29501
- if (!Array.isArray(payload.providers) || payload.providers.length > 1e4) {
29502
- throw new HttpError(400, "导出文件中的凭据库数据无效");
29938
+ try {
29939
+ activation.activate(ref.harness, ref.name);
29940
+ } catch (error52) {
29941
+ log.error(`providers update: failed to re-apply ${ref.harness}/${ref.name}`, error52);
29942
+ warnings.push({
29943
+ message: `${ref.harness}/${ref.name} 重新应用失败:${error52.message}`,
29944
+ code: WARNING_CODES.reapplyFailed,
29945
+ params: { harness: ref.harness, profile: ref.name, reason: error52.message }
29946
+ });
29503
29947
  }
29504
- for (const provider of payload.providers) {
29505
- if (!isPortableProvider(provider)) {
29506
- throw new HttpError(400, "导出文件中的凭据库数据无效");
29948
+ }
29949
+ return c.json({ provider, warnings });
29950
+ });
29951
+ app.post("/:id/probe", async (c) => {
29952
+ const id = decodeURIComponent(c.req.param("id"));
29953
+ const body = parseWith(probeStoredRequestSchema, await c.req.json().catch(() => ({})));
29954
+ const apiKey = vault.decrypt(id);
29955
+ const baseUrl = resolveEndpointBaseUrl(vault.get(id), body.endpoint);
29956
+ if (!baseUrl) {
29957
+ return c.json({
29958
+ result: {
29959
+ ok: false,
29960
+ code: PROBE_CODES.missingBaseUrl,
29961
+ message: `provider ${id} 未配置任何 endpoint,无法测试`
29507
29962
  }
29508
- }
29963
+ });
29509
29964
  }
29510
- if (payload.codexLoginCache !== undefined) {
29511
- if (typeof payload.codexLoginCache !== "string") {
29512
- throw new HttpError(400, "导出文件中的 Codex 登录缓存无效");
29513
- }
29514
- this.codexLoginCache.validate(payload.codexLoginCache);
29965
+ return c.json({ result: await probe.probe({ baseUrl, apiKey }) });
29966
+ });
29967
+ app.delete("/:id", (c) => {
29968
+ vault.remove(decodeURIComponent(c.req.param("id")));
29969
+ return c.json({ ok: true });
29970
+ });
29971
+ return app;
29972
+ }
29973
+ function resolveEndpointBaseUrl(entry, endpointKey) {
29974
+ if (endpointKey?.trim()) {
29975
+ const named = entry.endpoints.find((candidate) => candidate.key === endpointKey.trim());
29976
+ if (named) {
29977
+ return named.baseUrl;
29515
29978
  }
29516
- this.validatePayload(payload);
29517
- return payload;
29518
29979
  }
29519
- assertConflictPolicy(conflictPolicy) {
29520
- if (conflictPolicy !== "skip" && conflictPolicy !== "overwrite") {
29521
- throw new HttpError(400, "invalid conflict policy");
29522
- }
29980
+ return entry.endpoints[0]?.baseUrl ?? null;
29981
+ }
29982
+
29983
+ // src/services/scan.ts
29984
+ var IScanService = createDecorator("scanService");
29985
+ var _dec = [
29986
+ inject(IAdapterRegistry, IHarnessRegistry, IProfileService, IVaultService, IFileService, ILogService)
29987
+ ];
29988
+ var _init = __decoratorStart(undefined);
29989
+
29990
+ class ScanService {
29991
+ adapters;
29992
+ harnesses;
29993
+ profiles;
29994
+ vault;
29995
+ files;
29996
+ log;
29997
+ constructor(adapters, harnesses, profiles, vault, files, log) {
29998
+ this.adapters = adapters;
29999
+ this.harnesses = harnesses;
30000
+ this.profiles = profiles;
30001
+ this.vault = vault;
30002
+ this.files = files;
30003
+ this.log = log;
29523
30004
  }
29524
- validatePayload(payload) {
29525
- const profileIds = new Set;
29526
- const providerIds = new Set;
29527
- for (const provider of payload.providers ?? []) {
29528
- if (providerIds.has(provider.id)) {
29529
- throw new HttpError(400, "导出文件包含重复的凭据库条目");
30005
+ scan() {
30006
+ return this.harnesses.list().map((harness) => this.scanOne(harness.id, harness.label));
30007
+ }
30008
+ importSelections(selections) {
30009
+ const found = new Map;
30010
+ for (const result of this.harnesses.list()) {
30011
+ const adapter = this.adapters.get(result.id);
30012
+ for (const candidate of this.detect(adapter)) {
30013
+ found.set(candidateId(result.id, candidate.key), {
30014
+ harness: result.id,
30015
+ candidate
30016
+ });
29530
30017
  }
29531
- providerIds.add(provider.id);
29532
30018
  }
29533
- for (const profile of payload.profiles) {
29534
- this.validateProfile(profile);
29535
- const id = profileId(profile.harness, profile.name);
29536
- if (profileIds.has(id)) {
29537
- throw new HttpError(400, "导出文件包含重复的配置");
30019
+ const warnings = [];
30020
+ let imported = 0;
30021
+ let skipped = 0;
30022
+ let providersCreated = 0;
30023
+ for (const selection of selections) {
30024
+ const entry = found.get(selection.id);
30025
+ if (!entry) {
30026
+ warnings.push({ message: `${selection.name}:配置已不在磁盘上,已跳过` });
30027
+ skipped += 1;
30028
+ continue;
29538
30029
  }
29539
- profileIds.add(id);
29540
- if (profile.providerId && !providerIds.has(profile.providerId)) {
29541
- throw new HttpError(400, "导出文件中的配置引用了不存在的凭据库条目");
30030
+ const exists = this.profiles.get(entry.harness, selection.name) !== undefined;
30031
+ if (exists && !selection.overwrite) {
30032
+ warnings.push({ message: `${selection.name}:同名配置已存在,已跳过` });
30033
+ skipped += 1;
30034
+ continue;
29542
30035
  }
29543
- }
29544
- const activeHarnesses = new Set;
29545
- for (const active of payload.active) {
29546
- if (activeHarnesses.has(active.harness)) {
29547
- throw new HttpError(400, "导出文件包含重复的激活状态");
30036
+ try {
30037
+ providersCreated += this.save(entry.harness, entry.candidate, selection, exists);
30038
+ imported += 1;
30039
+ } catch (error52) {
30040
+ this.log.error(`scan import failed for ${entry.harness}/${selection.name}`, error52);
30041
+ warnings.push({
30042
+ message: `${selection.name}:${error52 instanceof Error ? error52.message : String(error52)}`
30043
+ });
30044
+ skipped += 1;
29548
30045
  }
29549
- activeHarnesses.add(active.harness);
29550
- const adapter = this.adapters.get(active.harness);
29551
- if (active.official) {
29552
- if (active.name !== "官方登录" || !adapter.renderOfficial) {
29553
- throw new HttpError(400, "导出文件中的官方登录状态无效");
30046
+ }
30047
+ return { ok: true, imported, skipped, providersCreated, warnings };
30048
+ }
30049
+ save(harness, candidate, selection, replacing) {
30050
+ let providerId;
30051
+ let created = 0;
30052
+ const apiKey = candidate.apiKey || selection.apiKey?.trim() || "";
30053
+ if (selection.target === "vault") {
30054
+ if (selection.providerId) {
30055
+ this.vault.get(selection.providerId);
30056
+ providerId = selection.providerId;
30057
+ } else {
30058
+ if (!apiKey) {
30059
+ throw new HttpError(400, "这条配置里没有可提取的凭据,请先填写 API key");
29554
30060
  }
29555
- } else if (!profileIds.has(profileId(active.harness, active.name))) {
29556
- throw new HttpError(400, "导出文件中的激活状态引用了不存在的配置");
30061
+ providerId = this.vault.create({
30062
+ name: selection.providerName ?? selection.name,
30063
+ apiKey,
30064
+ endpoints: candidate.baseUrl ? [{ key: "default", label: "默认", baseUrl: candidate.baseUrl }] : []
30065
+ }).id;
30066
+ created = 1;
29557
30067
  }
30068
+ } else if (!apiKey) {
30069
+ throw new HttpError(400, "这条配置里没有可提取的凭据,请先填写 API key");
29558
30070
  }
30071
+ this.profiles.upsert(harness, {
30072
+ name: selection.name,
30073
+ sourceName: replacing ? selection.name : undefined,
30074
+ baseUrl: candidate.baseUrl,
30075
+ apiKey,
30076
+ model: candidate.model,
30077
+ notes: `从 ${harness} 现有配置导入(${candidate.key})`,
30078
+ extras: candidate.extras,
30079
+ ...providerId ? { providerId, providerEndpoint: "default" } : {}
30080
+ }, !replacing);
30081
+ return created;
29559
30082
  }
29560
- planImport(payload, existing, existingVault, conflictPolicy, restoreActive) {
29561
- const store = structuredClone(existing);
29562
- const vault = structuredClone(existingVault);
29563
- let imported = 0;
29564
- let overwritten = 0;
29565
- let skipped = 0;
29566
- const selected = [];
29567
- for (const profile of payload.profiles) {
29568
- store[profile.harness] ||= {};
29569
- const exists = store[profile.harness][profile.name] !== undefined;
29570
- if (exists && conflictPolicy === "skip") {
29571
- skipped++;
29572
- continue;
30083
+ scanOne(harness, label) {
30084
+ const adapter = this.adapters.get(harness);
30085
+ const targets = adapter.targets();
30086
+ const sources = targets.map((target) => {
30087
+ const content = this.readSafely(target.path);
30088
+ let parsable = content !== undefined;
30089
+ if (content !== undefined) {
30090
+ try {
30091
+ assertParsable(target.format, target.path, content);
30092
+ } catch {
30093
+ parsable = false;
30094
+ }
29573
30095
  }
29574
- selected.push(profile);
30096
+ return {
30097
+ key: target.key,
30098
+ label: target.label,
30099
+ path: target.path,
30100
+ exists: content !== undefined,
30101
+ parsable
30102
+ };
30103
+ });
30104
+ if (!adapter.detect) {
30105
+ return {
30106
+ harness,
30107
+ label,
30108
+ sources,
30109
+ candidates: [],
30110
+ note: "该工具暂不支持扫描导入",
30111
+ noteCode: SCAN_NOTE_CODES.unsupported
30112
+ };
29575
30113
  }
29576
- const providerMap = new Map;
29577
- for (const provider of payload.providers ?? []) {
29578
- const targetId = this.availableProviderId(provider.id, vault);
29579
- vault.entries[targetId] = {
29580
- id: targetId,
29581
- name: provider.name,
29582
- api_key: this.crypto.encrypt(provider.apiKey),
29583
- notes: provider.notes,
29584
- endpoints: provider.endpoints,
29585
- created_at: new Date().toISOString(),
29586
- updated_at: new Date().toISOString()
30114
+ if (sources.every((source) => !source.exists)) {
30115
+ return {
30116
+ harness,
30117
+ label,
30118
+ sources,
30119
+ candidates: [],
30120
+ note: "磁盘上没有找到该工具的配置文件",
30121
+ noteCode: SCAN_NOTE_CODES.noConfigFiles
29587
30122
  };
29588
- providerMap.set(provider.id, targetId);
29589
30123
  }
29590
- for (const profile of selected) {
29591
- store[profile.harness] ||= {};
29592
- const exists = store[profile.harness][profile.name] !== undefined;
29593
- store[profile.harness][profile.name] = this.toStored(profile);
29594
- const mappedProvider = profile.providerId ? providerMap.get(profile.providerId) : undefined;
29595
- if (mappedProvider) {
29596
- store[profile.harness][profile.name].provider_id = mappedProvider;
29597
- store[profile.harness][profile.name].provider_endpoint = profile.providerEndpoint;
29598
- }
29599
- if (exists) {
29600
- overwritten++;
29601
- } else {
29602
- imported++;
29603
- }
30124
+ if (sources.some((source) => source.exists && !source.parsable)) {
30125
+ return {
30126
+ harness,
30127
+ label,
30128
+ sources,
30129
+ candidates: [],
30130
+ note: "配置文件存在但无法解析,导入前请先修复它",
30131
+ noteCode: SCAN_NOTE_CODES.unparsable
30132
+ };
29604
30133
  }
30134
+ const candidates = this.detect(adapter).map((candidate) => this.describe(harness, candidate, this.existingNames(harness)));
29605
30135
  return {
29606
- store,
29607
- vault,
29608
- imported,
29609
- overwritten,
29610
- skipped,
29611
- providersCopied: providerMap.size,
29612
- codexActivationAuthEffect: this.codexActivationAuthEffect(payload, store, restoreActive)
30136
+ harness,
30137
+ label,
30138
+ sources,
30139
+ candidates,
30140
+ note: candidates.length === 0 ? "配置文件里没有找到可导入的 provider" : undefined,
30141
+ noteCode: candidates.length === 0 ? SCAN_NOTE_CODES.noCandidates : undefined
29613
30142
  };
29614
30143
  }
29615
- codexActivationAuthEffect(payload, store, restoreActive) {
29616
- if (!restoreActive) {
29617
- return "none";
29618
- }
29619
- const active = payload.active.find((item) => item.harness === "codex");
29620
- if (!active) {
29621
- return "none";
29622
- }
29623
- if (active.official) {
29624
- return "official-cleanup";
29625
- }
29626
- const profile = store.codex?.[active.name];
29627
- if (!profile) {
29628
- return "none";
29629
- }
29630
- if (profile.overrides?.auth !== undefined) {
29631
- return "auth-override";
29632
- }
29633
- return profile.extras?.authMode === "openai_auth" ? "openai-api-key" : "none";
29634
- }
29635
- validateProfile(profile) {
29636
- if (!profile.name || profile.name.length > 120 || /[\\/]/.test(profile.name)) {
29637
- throw new HttpError(400, "导出文件包含无效的配置名称");
29638
- }
29639
- this.adapters.get(profile.harness).validate?.({
29640
- name: profile.name,
29641
- baseUrl: profile.baseUrl,
29642
- apiKey: profile.apiKey,
29643
- model: profile.model,
29644
- extras: profile.extras
29645
- });
29646
- }
29647
- toStored(profile) {
30144
+ describe(harness, candidate, existing) {
30145
+ const suggestedName = uniqueName(candidate.key || harness, existing);
29648
30146
  return {
29649
- base_url: profile.baseUrl,
29650
- api_key: this.crypto.encrypt(profile.apiKey),
29651
- model: profile.model,
29652
- notes: profile.notes,
29653
- extras: profile.extras,
29654
- overrides: profile.overrides,
29655
- updated_at: new Date().toISOString()
30147
+ id: candidateId(harness, candidate.key),
30148
+ harness,
30149
+ sourceKey: candidate.key,
30150
+ suggestedName,
30151
+ baseUrl: candidate.baseUrl,
30152
+ model: candidate.model,
30153
+ extras: candidate.extras,
30154
+ apiKeyPreview: mask(candidate.apiKey),
30155
+ apiKeyPresent: candidate.apiKey !== "",
30156
+ active: candidate.active,
30157
+ conflictsWith: existing.has(candidate.key) ? candidate.key : undefined,
30158
+ matchesProvider: this.matchProvider(candidate)
29656
30159
  };
29657
30160
  }
29658
- readStore() {
29659
- return this.files.readJsonStrict(this.environment.files.profiles, {});
29660
- }
29661
- readVault() {
29662
- return this.files.readJsonStrict(this.environment.files.vault, {
29663
- version: 1,
29664
- entries: {}
29665
- });
29666
- }
29667
- availableProviderId(sourceId, vault) {
29668
- if (!vault.entries[sourceId])
29669
- return sourceId;
29670
- const base = `${sourceId}-imported`.slice(0, 60);
29671
- let candidate = base;
29672
- let index = 2;
29673
- while (vault.entries[candidate]) {
29674
- candidate = `${base}-${index}`.slice(0, 64);
29675
- index++;
30161
+ detect(adapter) {
30162
+ if (!adapter.detect) {
30163
+ return [];
29676
30164
  }
29677
- return candidate;
29678
- }
29679
- restore(path, snapshot) {
29680
30165
  try {
29681
- if (snapshot === undefined)
29682
- this.files.remove(path);
29683
- else
29684
- this.files.writeSecure(path, snapshot);
29685
- } catch {}
30166
+ return adapter.detect(this.readCurrent(adapter));
30167
+ } catch (error52) {
30168
+ this.log.error(`scan failed for ${adapter.id}`, error52);
30169
+ return [];
30170
+ }
29686
30171
  }
29687
- resolveKey(stored) {
29688
- if (!stored.provider_id) {
29689
- return this.crypto.decrypt(stored.api_key);
30172
+ matchProvider(candidate) {
30173
+ if (!candidate.apiKey) {
30174
+ return;
29690
30175
  }
29691
- try {
29692
- return this.vault.decrypt(stored.provider_id);
29693
- } catch {
29694
- return this.crypto.decrypt(stored.api_key);
30176
+ for (const provider of this.vault.list()) {
30177
+ try {
30178
+ if (this.vault.decrypt(provider.id) === candidate.apiKey) {
30179
+ return provider.id;
30180
+ }
30181
+ } catch {}
29695
30182
  }
30183
+ return;
29696
30184
  }
29697
- assertPassphrase(passphrase) {
29698
- if (passphrase.length < 8) {
29699
- throw new HttpError(400, "迁移密码至少需要 8 个字符");
29700
- }
30185
+ existingNames(harness) {
30186
+ return new Set(this.profiles.list(harness).map((profile) => profile.name));
29701
30187
  }
29702
- }
29703
- TransferService = __decorateElement(_init, 0, "TransferService", _dec, TransferService);
29704
- __runInitializers(_init, 1, TransferService);
29705
- __decoratorMetadata(_init, TransferService);
29706
- let _TransferService = TransferService;
29707
- function encrypt(payload, passphrase) {
29708
- const salt = randomBytes4(16);
29709
- const iv = randomBytes4(12);
29710
- const key = scryptSync(passphrase, salt, 32);
29711
- const cipher = createCipheriv2("aes-256-gcm", key, iv);
29712
- const data = Buffer.concat([cipher.update(JSON.stringify(payload), "utf8"), cipher.final()]);
29713
- return {
29714
- format: FORMAT,
29715
- version: VERSION,
29716
- kdf: { name: "scrypt", salt: salt.toString("base64url") },
29717
- cipher: {
29718
- name: "aes-256-gcm",
29719
- iv: iv.toString("base64url"),
29720
- tag: cipher.getAuthTag().toString("base64url"),
29721
- data: data.toString("base64url")
30188
+ readCurrent(adapter) {
30189
+ const current = {};
30190
+ for (const target of adapter.targets()) {
30191
+ current[target.key] = this.readSafely(target.path);
29722
30192
  }
29723
- };
29724
- }
29725
- function decrypt(envelope, passphrase) {
29726
- try {
29727
- 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) {
29728
- throw new Error("invalid envelope");
30193
+ return current;
30194
+ }
30195
+ readSafely(path) {
30196
+ try {
30197
+ return this.files.readRegularOptional(path);
30198
+ } catch {
30199
+ return;
29729
30200
  }
29730
- const salt = Buffer.from(envelope.kdf.salt, "base64url");
29731
- const key = scryptSync(passphrase, salt, 32);
29732
- const decipher = createDecipheriv2("aes-256-gcm", key, Buffer.from(envelope.cipher.iv, "base64url"));
29733
- decipher.setAuthTag(Buffer.from(envelope.cipher.tag, "base64url"));
29734
- const plain = Buffer.concat([
29735
- decipher.update(Buffer.from(envelope.cipher.data, "base64url")),
29736
- decipher.final()
29737
- ]).toString("utf8");
29738
- return JSON.parse(plain);
29739
- } catch {
29740
- throw new HttpError(400, "迁移密码错误或导出文件已损坏");
29741
30201
  }
29742
30202
  }
29743
- function profileId(harness, name) {
29744
- return `${harness}\x00${name}`;
29745
- }
29746
- function isStringRecord(value) {
29747
- return typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((item) => typeof item === "string");
30203
+ ScanService = __decorateElement(_init, 0, "ScanService", _dec, ScanService);
30204
+ __runInitializers(_init, 1, ScanService);
30205
+ __decoratorMetadata(_init, ScanService);
30206
+ let _ScanService = ScanService;
30207
+ function candidateId(harness, key) {
30208
+ return `${harness}:${key}`;
29748
30209
  }
29749
- function isPortableProfile(value) {
29750
- if (typeof value !== "object" || value === null) {
29751
- return false;
30210
+ function mask(apiKey) {
30211
+ if (!apiKey) {
30212
+ return "";
29752
30213
  }
29753
- const profile = value;
29754
- 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) && (profile.providerId === undefined || typeof profile.providerId === "string") && (profile.providerEndpoint === undefined || typeof profile.providerEndpoint === "string");
29755
- }
29756
- function isPortableProvider(value) {
29757
- if (typeof value !== "object" || value === null)
29758
- return false;
29759
- const provider = value;
29760
- return typeof provider.id === "string" && provider.id.length > 0 && provider.id.length <= 64 && !/[\\/]/.test(provider.id) && provider.id !== "__proto__" && provider.id !== "constructor" && typeof provider.name === "string" && provider.name.length > 0 && typeof provider.apiKey === "string" && provider.apiKey.length > 0 && (provider.notes === undefined || typeof provider.notes === "string") && Array.isArray(provider.endpoints) && provider.endpoints.every((endpoint) => typeof endpoint?.key === "string" && typeof endpoint.label === "string" && typeof endpoint.baseUrl === "string");
30214
+ if (apiKey.length <= 8) {
30215
+ return "•".repeat(apiKey.length);
30216
+ }
30217
+ return `${apiKey.slice(0, 4)}${"•".repeat(6)}${apiKey.slice(-4)}`;
29761
30218
  }
29762
- function isPortableActive(value) {
29763
- if (typeof value !== "object" || value === null) {
29764
- return false;
30219
+ function uniqueName(base, existing) {
30220
+ if (!existing.has(base)) {
30221
+ return base;
29765
30222
  }
29766
- const active = value;
29767
- return typeof active.harness === "string" && isHarnessId(active.harness) && typeof active.name === "string" && typeof active.official === "boolean";
30223
+ let suffix = 2;
30224
+ while (existing.has(`${base}-${suffix}`)) {
30225
+ suffix += 1;
30226
+ }
30227
+ return `${base}-${suffix}`;
30228
+ }
30229
+
30230
+ // src/http/routes/scan.ts
30231
+ function createScanRoutes(services) {
30232
+ const app = new Hono2;
30233
+ const scan = services.get(IScanService);
30234
+ app.get("/", (c) => c.json({ items: scan.scan() }));
30235
+ app.post("/import", async (c) => {
30236
+ const body = await readJsonBody(c, scanImportRequestSchema);
30237
+ return c.json(scan.importSelections(body.selections));
30238
+ });
30239
+ return app;
29768
30240
  }
29769
30241
 
29770
30242
  // src/http/routes/transfer.ts
@@ -30254,6 +30726,9 @@ function createApp(services) {
30254
30726
  api2.route("/operations", createOperationRoutes(services));
30255
30727
  api2.use("/transfer/*", createAuthGuard(services));
30256
30728
  api2.route("/transfer", createTransferRoutes(services));
30729
+ api2.use("/github/*", createAuthGuard(services));
30730
+ api2.use("/github", createAuthGuard(services));
30731
+ api2.route("/github", createGitHubRoutes(services));
30257
30732
  api2.use("/update/*", createAuthGuard(services));
30258
30733
  api2.use("/update", createAuthGuard(services));
30259
30734
  api2.route("/update", createUpdateRoutes(services));
@@ -30353,6 +30828,7 @@ function createServices() {
30353
30828
  collection.set(IProbeService, new SyncDescriptor(ProbeService));
30354
30829
  collection.set(IActivationService, new SyncDescriptor(ActivationService));
30355
30830
  collection.set(ITransferService, new SyncDescriptor(TransferService));
30831
+ collection.set(IGitHubSyncService, new SyncDescriptor(GitHubSyncService));
30356
30832
  collection.set(IDriftService, new SyncDescriptor(DriftService));
30357
30833
  collection.set(IDoctorService, new SyncDescriptor(DoctorService));
30358
30834
  return new InstantiationService(collection);