@seaveyon/harness-switch 0.12.0 → 0.13.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.
@@ -7014,7 +7014,7 @@ var require_public_api = __commonJS((exports) => {
7014
7014
  });
7015
7015
 
7016
7016
  // src/app.ts
7017
- import { existsSync as existsSync3 } from "fs";
7017
+ import { existsSync as existsSync4 } from "fs";
7018
7018
  import { join as join11 } from "path";
7019
7019
 
7020
7020
  // ../../node_modules/hono/dist/compose.js
@@ -9184,40 +9184,75 @@ class InstantiationService {
9184
9184
  import { createCipheriv, createDecipheriv, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
9185
9185
 
9186
9186
  // src/services/environment.ts
9187
+ import { AsyncLocalStorage } from "async_hooks";
9187
9188
  import { existsSync, mkdirSync } from "fs";
9188
- import { homedir } from "os";
9189
+ import { homedir, userInfo } from "os";
9189
9190
  import { join as join2 } from "path";
9190
9191
  var IEnvironmentService = createDecorator("environmentService");
9191
9192
 
9192
9193
  class EnvironmentService {
9193
9194
  host = process.env.HOST || "127.0.0.1";
9194
9195
  port = Number(process.env.PORT || 8787);
9195
- homeDir = process.env.HSW_HOME_DIR || homedir();
9196
- dataDir = process.env.HSW_DATA_DIR || join2(this.homeDir, ".harness-switch");
9197
9196
  publicDir = process.env.HSW_PUBLIC_DIR || resolvePublicDir();
9198
9197
  sessionTtlMs = resolveSessionTtlMs();
9199
9198
  cookieName = "hsw_session";
9200
- files = {
9201
- profiles: join2(this.dataDir, "profiles.json"),
9202
- active: join2(this.dataDir, "active.json"),
9203
- password: join2(this.dataDir, "web_password"),
9204
- key: join2(this.dataDir, "aes-256-gcm.key"),
9205
- env: join2(this.dataDir, "env.sh"),
9206
- sessions: join2(this.dataDir, "sessions.json"),
9207
- vault: join2(this.dataDir, "vault.json")
9208
- };
9209
- backupsDir = join2(this.dataDir, "backups");
9210
9199
  backupRetainCount = Math.max(1, Number(process.env.HSW_BACKUP_RETAIN || 10));
9211
- harnessHomes = {
9212
- claude: join2(this.homeDir, ".claude"),
9213
- codex: process.env.CODEX_HOME || join2(this.homeDir, ".codex"),
9214
- kimiCode: process.env.KIMI_CODE_HOME || join2(this.homeDir, ".kimi-code"),
9215
- piAgent: process.env.PI_CODING_AGENT_DIR || join2(this.homeDir, ".pi", "agent"),
9216
- dsh: process.env.DSH_HOME || join2(this.homeDir, ".dsh")
9200
+ defaultUser = resolveDefaultUser();
9201
+ managerDataDir = process.env.HSW_DATA_DIR || join2(this.defaultUser.homeDir, ".harness-switch");
9202
+ managerFiles = {
9203
+ password: join2(this.managerDataDir, "web_password"),
9204
+ sessions: join2(this.managerDataDir, "sessions.json")
9217
9205
  };
9206
+ userContext = new AsyncLocalStorage;
9207
+ get currentUser() {
9208
+ return this.userContext.getStore() ?? this.defaultUser;
9209
+ }
9210
+ get homeDir() {
9211
+ return this.currentUser.homeDir;
9212
+ }
9213
+ get dataDir() {
9214
+ return this.currentUser.username === this.defaultUser.username ? this.managerDataDir : join2(this.homeDir, ".harness-switch");
9215
+ }
9216
+ get files() {
9217
+ const dataDir = this.dataDir;
9218
+ return {
9219
+ profiles: join2(dataDir, "profiles.json"),
9220
+ active: join2(dataDir, "active.json"),
9221
+ password: join2(dataDir, "web_password"),
9222
+ key: join2(dataDir, "aes-256-gcm.key"),
9223
+ env: join2(dataDir, "env.sh"),
9224
+ sessions: join2(dataDir, "sessions.json"),
9225
+ vault: join2(dataDir, "vault.json")
9226
+ };
9227
+ }
9228
+ get backupsDir() {
9229
+ return join2(this.dataDir, "backups");
9230
+ }
9231
+ get harnessHomes() {
9232
+ const isDefault = this.currentUser.username === this.defaultUser.username;
9233
+ return {
9234
+ claude: join2(this.homeDir, ".claude"),
9235
+ codex: isDefault && process.env.CODEX_HOME ? process.env.CODEX_HOME : join2(this.homeDir, ".codex"),
9236
+ kimiCode: isDefault && process.env.KIMI_CODE_HOME ? process.env.KIMI_CODE_HOME : join2(this.homeDir, ".kimi-code"),
9237
+ piAgent: isDefault && process.env.PI_CODING_AGENT_DIR ? process.env.PI_CODING_AGENT_DIR : join2(this.homeDir, ".pi", "agent"),
9238
+ dsh: isDefault && process.env.DSH_HOME ? process.env.DSH_HOME : join2(this.homeDir, ".dsh")
9239
+ };
9240
+ }
9218
9241
  ensureDataDir() {
9219
9242
  mkdirSync(this.dataDir, { recursive: true, mode: 448 });
9220
9243
  }
9244
+ runAsUser(user, callback) {
9245
+ return this.userContext.run(user, callback);
9246
+ }
9247
+ }
9248
+ function resolveDefaultUser() {
9249
+ const info = userInfo();
9250
+ return {
9251
+ username: info.username,
9252
+ uid: info.uid,
9253
+ gid: info.gid,
9254
+ homeDir: process.env.HSW_HOME_DIR || homedir()
9255
+ };
9221
9256
  }
9222
9257
  function resolveSessionTtlMs() {
9223
9258
  const hours = Number(process.env.HSW_SESSION_TTL_HOURS || 24);
@@ -9236,6 +9271,7 @@ function resolvePublicDir() {
9236
9271
  import { randomBytes } from "crypto";
9237
9272
  import {
9238
9273
  chmodSync,
9274
+ chownSync,
9239
9275
  existsSync as existsSync2,
9240
9276
  mkdirSync as mkdirSync2,
9241
9277
  readdirSync,
@@ -9296,7 +9332,6 @@ class FileService {
9296
9332
  }
9297
9333
  }
9298
9334
  writeSecure(file, text) {
9299
- this.environment.ensureDataDir();
9300
9335
  this.write(file, text, 384);
9301
9336
  }
9302
9337
  writeUserFile(file, text) {
@@ -9314,7 +9349,22 @@ class FileService {
9314
9349
  `);
9315
9350
  }
9316
9351
  ensureDir(dir) {
9352
+ const missing = [];
9353
+ let cursor = dir;
9354
+ while (!existsSync2(cursor)) {
9355
+ missing.push(cursor);
9356
+ const parent = dirname2(cursor);
9357
+ if (parent === cursor)
9358
+ break;
9359
+ cursor = parent;
9360
+ }
9317
9361
  mkdirSync2(dir, { recursive: true, mode: 448 });
9362
+ for (const created of missing.toReversed()) {
9363
+ this.applyOwner(created, this.environment.currentUser.uid, this.environment.currentUser.gid);
9364
+ try {
9365
+ chmodSync(created, 448);
9366
+ } catch {}
9367
+ }
9318
9368
  }
9319
9369
  remove(file) {
9320
9370
  rmSync(file, { force: true, recursive: true });
@@ -9329,7 +9379,9 @@ class FileService {
9329
9379
  write(file, text, mode) {
9330
9380
  this.ensureDir(dirname2(file));
9331
9381
  const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
9382
+ const owner = this.ownerOf(file);
9332
9383
  writeFileSync(tmp, text, { encoding: "utf8", mode });
9384
+ this.applyOwner(tmp, owner.uid, owner.gid);
9333
9385
  renameSync(tmp, file);
9334
9386
  try {
9335
9387
  chmodSync(file, mode);
@@ -9342,6 +9394,27 @@ class FileService {
9342
9394
  return 384;
9343
9395
  }
9344
9396
  }
9397
+ ownerOf(file) {
9398
+ try {
9399
+ const stat2 = statSync(file);
9400
+ return { uid: stat2.uid, gid: stat2.gid };
9401
+ } catch {
9402
+ return { uid: this.environment.currentUser.uid, gid: this.environment.currentUser.gid };
9403
+ }
9404
+ }
9405
+ applyOwner(path, uid, gid) {
9406
+ if (process.platform === "win32")
9407
+ return;
9408
+ try {
9409
+ chownSync(path, uid, gid);
9410
+ } catch (error) {
9411
+ if (uid !== process.getuid?.() || gid !== process.getgid?.()) {
9412
+ throw new HttpError(403, `\u65E0\u6CD5\u628A ${path} \u7684\u6240\u6709\u6743\u8BBE\u7F6E\u4E3A ${this.environment.currentUser.username}\uFF0C\u8DE8\u7528\u6237\u7BA1\u7406\u9700\u8981\u4EE5 root \u8FD0\u884C`);
9413
+ }
9414
+ if (error.code !== "EPERM")
9415
+ throw error;
9416
+ }
9417
+ }
9345
9418
  }
9346
9419
  FileService = __decorateElement(_init, 0, "FileService", _dec, FileService);
9347
9420
  __runInitializers(_init, 1, FileService);
@@ -9456,7 +9529,7 @@ class AuthService {
9456
9529
  this.log = log;
9457
9530
  }
9458
9531
  ensurePassword() {
9459
- const file = this.environment.files.password;
9532
+ const file = this.environment.managerFiles.password;
9460
9533
  if (!this.files.exists(file)) {
9461
9534
  const password = this.crypto.randomPassword();
9462
9535
  this.files.writeSecure(file, `${password}
@@ -9472,7 +9545,8 @@ class AuthService {
9472
9545
  }
9473
9546
  const token = randomBytes3(32).toString("base64url");
9474
9547
  this.load().set(digest("session", token), {
9475
- expires: Date.now() + this.environment.sessionTtlMs
9548
+ expires: Date.now() + this.environment.sessionTtlMs,
9549
+ username: this.environment.defaultUser.username
9476
9550
  });
9477
9551
  this.persist();
9478
9552
  return token;
@@ -9497,13 +9571,29 @@ class AuthService {
9497
9571
  }
9498
9572
  return true;
9499
9573
  }
9574
+ userForToken(token) {
9575
+ if (!this.isAuthenticated(token) || !token) {
9576
+ return;
9577
+ }
9578
+ return this.load().get(digest("session", token))?.username;
9579
+ }
9580
+ selectUser(token, username) {
9581
+ if (!this.isAuthenticated(token) || !token) {
9582
+ return;
9583
+ }
9584
+ const session = this.load().get(digest("session", token));
9585
+ if (session) {
9586
+ session.username = username;
9587
+ this.persist();
9588
+ }
9589
+ }
9500
9590
  load() {
9501
9591
  const loaded = this.sessions;
9502
9592
  if (loaded) {
9503
9593
  return loaded;
9504
9594
  }
9505
9595
  this.fingerprint = digest("password", this.ensurePassword());
9506
- const store = this.files.readJson(this.environment.files.sessions, {
9596
+ const store = this.files.readJson(this.environment.managerFiles.sessions, {
9507
9597
  version: STORE_VERSION,
9508
9598
  password: this.fingerprint,
9509
9599
  sessions: {}
@@ -9513,7 +9603,10 @@ class AuthService {
9513
9603
  const now = Date.now();
9514
9604
  for (const [key, session] of Object.entries(store.sessions ?? {})) {
9515
9605
  if (typeof session?.expires === "number" && session.expires > now) {
9516
- sessions.set(key, { expires: session.expires });
9606
+ sessions.set(key, {
9607
+ expires: session.expires,
9608
+ username: typeof session.username === "string" ? session.username : this.environment.defaultUser.username
9609
+ });
9517
9610
  }
9518
9611
  }
9519
9612
  }
@@ -9528,7 +9621,7 @@ class AuthService {
9528
9621
  if (!sessions) {
9529
9622
  return;
9530
9623
  }
9531
- this.files.writeJson(this.environment.files.sessions, {
9624
+ this.files.writeJson(this.environment.managerFiles.sessions, {
9532
9625
  version: STORE_VERSION,
9533
9626
  password: this.fingerprint,
9534
9627
  sessions: Object.fromEntries(sessions)
@@ -9543,6 +9636,91 @@ function digest(kind, value) {
9543
9636
  return createHash("sha256").update(`${kind}:${value}`).digest("base64url");
9544
9637
  }
9545
9638
 
9639
+ // src/services/users.ts
9640
+ import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
9641
+ var IUserService = createDecorator("userService");
9642
+ var _dec = [
9643
+ inject(IEnvironmentService)
9644
+ ];
9645
+ var _init = __decoratorStart(undefined);
9646
+
9647
+ class UserService {
9648
+ environment;
9649
+ constructor(environment) {
9650
+ this.environment = environment;
9651
+ }
9652
+ list() {
9653
+ const users = discoverUsers();
9654
+ const existing = users.find((user) => user.username === this.environment.defaultUser.username);
9655
+ if (existing) {
9656
+ Object.assign(existing, this.environment.defaultUser);
9657
+ } else {
9658
+ users.push(this.environment.defaultUser);
9659
+ }
9660
+ const allow = parseAllowList();
9661
+ return users.filter((user) => user.username === this.environment.defaultUser.username || !allow || allow.has(user.username)).toSorted((left, right) => {
9662
+ if (left.username === this.environment.defaultUser.username)
9663
+ return -1;
9664
+ if (right.username === this.environment.defaultUser.username)
9665
+ return 1;
9666
+ return left.uid - right.uid || left.username.localeCompare(right.username);
9667
+ });
9668
+ }
9669
+ require(username) {
9670
+ const normalized = String(username ?? "").trim();
9671
+ const user = this.list().find((candidate) => candidate.username === normalized);
9672
+ if (!user) {
9673
+ throw new HttpError(404, `\u672C\u5730\u7528\u6237 ${normalized || "(empty)"} \u4E0D\u5B58\u5728\u6216\u672A\u83B7\u51C6\u7BA1\u7406`);
9674
+ }
9675
+ return user;
9676
+ }
9677
+ }
9678
+ UserService = __decorateElement(_init, 0, "UserService", _dec, UserService);
9679
+ __runInitializers(_init, 1, UserService);
9680
+ __decoratorMetadata(_init, UserService);
9681
+ let _UserService = UserService;
9682
+ function discoverUsers() {
9683
+ if (process.platform === "win32") {
9684
+ return [];
9685
+ }
9686
+ let text = "";
9687
+ try {
9688
+ text = readFileSync2("/etc/passwd", "utf8");
9689
+ } catch {
9690
+ return [];
9691
+ }
9692
+ const uidMin = readUidMin();
9693
+ const users = [];
9694
+ for (const line of text.split(`
9695
+ `)) {
9696
+ if (!line || line.startsWith("#"))
9697
+ continue;
9698
+ const fields = line.split(":");
9699
+ if (fields.length < 7)
9700
+ continue;
9701
+ const [username, , uidText, gidText, , homeDir, shell] = fields;
9702
+ const uid = Number(uidText);
9703
+ const gid = Number(gidText);
9704
+ if (!username || !homeDir?.startsWith("/") || !Number.isInteger(uid) || !Number.isInteger(gid) || uid !== 0 && uid < uidMin || /(?:nologin|false)$/.test(shell ?? "") || !existsSync3(homeDir)) {
9705
+ continue;
9706
+ }
9707
+ users.push({ username, uid, gid, homeDir });
9708
+ }
9709
+ return users;
9710
+ }
9711
+ function readUidMin() {
9712
+ try {
9713
+ const match2 = /^\s*UID_MIN\s+(\d+)/m.exec(readFileSync2("/etc/login.defs", "utf8"));
9714
+ return match2 ? Number(match2[1]) : 1000;
9715
+ } catch {
9716
+ return 1000;
9717
+ }
9718
+ }
9719
+ function parseAllowList() {
9720
+ const value = process.env.HSW_USERS?.trim();
9721
+ return value ? new Set(value.split(",").map((item) => item.trim()).filter(Boolean)) : undefined;
9722
+ }
9723
+
9546
9724
  // src/http/middleware.ts
9547
9725
  function createServiceMiddleware(services) {
9548
9726
  return async (c, next) => {
@@ -9568,12 +9746,15 @@ function createOriginGuard() {
9568
9746
  function createAuthGuard(services) {
9569
9747
  const auth = services.get(IAuthService);
9570
9748
  const environment = services.get(IEnvironmentService);
9749
+ const users = services.get(IUserService);
9571
9750
  return async (c, next) => {
9572
9751
  const token = getCookie(c, environment.cookieName);
9573
9752
  if (!auth.isAuthenticated(token)) {
9574
9753
  throw new HttpError(401, "authentication required");
9575
9754
  }
9576
- await next();
9755
+ const username = auth.userForToken(token) ?? environment.defaultUser.username;
9756
+ const user = users.require(username);
9757
+ await environment.runAsUser(user, () => next());
9577
9758
  };
9578
9759
  }
9579
9760
 
@@ -9594,7 +9775,7 @@ function createAuthRoutes(services) {
9594
9775
  path: "/",
9595
9776
  maxAge: environment.sessionTtlMs / 1000
9596
9777
  });
9597
- return c.json({ authenticated: true });
9778
+ return c.json({ authenticated: true, currentUser: environment.defaultUser.username });
9598
9779
  });
9599
9780
  app.post("/logout", (c) => {
9600
9781
  auth.logout(getCookie(c, environment.cookieName));
@@ -9606,7 +9787,7 @@ function createAuthRoutes(services) {
9606
9787
  if (!auth.isAuthenticated(token)) {
9607
9788
  throw new HttpError(401, "authentication required");
9608
9789
  }
9609
- return c.json({ authenticated: true });
9790
+ return c.json({ authenticated: true, currentUser: auth.userForToken(token) });
9610
9791
  });
9611
9792
  return app;
9612
9793
  }
@@ -13584,6 +13765,244 @@ function createUpdateRoutes(_services) {
13584
13765
  return api;
13585
13766
  }
13586
13767
 
13768
+ // src/services/user-sync.ts
13769
+ var IUserSyncService = createDecorator("userSyncService");
13770
+ var _dec = [
13771
+ inject(IEnvironmentService, IUserService, IFileService, ICryptoService)
13772
+ ];
13773
+ var _init = __decoratorStart(undefined);
13774
+
13775
+ class UserSyncService {
13776
+ environment;
13777
+ users;
13778
+ files;
13779
+ crypto;
13780
+ constructor(environment, users, files, crypto2) {
13781
+ this.environment = environment;
13782
+ this.users = users;
13783
+ this.files = files;
13784
+ this.crypto = crypto2;
13785
+ }
13786
+ preview(sourceUsername) {
13787
+ const target = this.environment.currentUser;
13788
+ const source = this.requireSource(sourceUsername, target);
13789
+ const portable = this.readPortable(source);
13790
+ const targetProfiles = this.readProfiles();
13791
+ const conflicts = [];
13792
+ let profileCount = 0;
13793
+ const referencedProviders = new Set;
13794
+ for (const [harness, profiles] of Object.entries(portable.profiles)) {
13795
+ for (const [name, profile] of Object.entries(profiles)) {
13796
+ profileCount++;
13797
+ if (targetProfiles[harness]?.[name]) {
13798
+ conflicts.push({ harness, name });
13799
+ }
13800
+ if (profile.provider_id)
13801
+ referencedProviders.add(profile.provider_id);
13802
+ }
13803
+ }
13804
+ return {
13805
+ sourceUser: source.username,
13806
+ targetUser: target.username,
13807
+ profileCount,
13808
+ providerCount: referencedProviders.size,
13809
+ conflicts
13810
+ };
13811
+ }
13812
+ sync(sourceUsername, conflictPolicy) {
13813
+ if (conflictPolicy !== "skip" && conflictPolicy !== "overwrite") {
13814
+ throw new HttpError(400, "invalid conflict policy");
13815
+ }
13816
+ const target = this.environment.currentUser;
13817
+ const source = this.requireSource(sourceUsername, target);
13818
+ const portable = this.readPortable(source);
13819
+ const profilesPath = this.environment.files.profiles;
13820
+ const vaultPath = this.environment.files.vault;
13821
+ const profileSnapshot = this.files.readOptional(profilesPath);
13822
+ const vaultSnapshot = this.files.readOptional(vaultPath);
13823
+ const targetProfiles = structuredClone(this.readProfiles());
13824
+ const targetVault = structuredClone(this.readVault());
13825
+ const active = this.files.readJson(this.environment.files.active, {});
13826
+ const warnings = [];
13827
+ let imported = 0;
13828
+ let overwritten = 0;
13829
+ let skipped = 0;
13830
+ const selected = [];
13831
+ for (const [harness, profiles] of Object.entries(portable.profiles)) {
13832
+ for (const [name, profile] of Object.entries(profiles)) {
13833
+ const exists = targetProfiles[harness]?.[name] !== undefined;
13834
+ if (exists && conflictPolicy === "skip") {
13835
+ skipped++;
13836
+ continue;
13837
+ }
13838
+ selected.push({ harness, name, profile });
13839
+ if (exists) {
13840
+ overwritten++;
13841
+ if (active[harness]?.name === name) {
13842
+ warnings.push(`${harness}/${name} \u5F53\u524D\u5904\u4E8E\u6FC0\u6D3B\u72B6\u6001\uFF1B\u5DF2\u66F4\u65B0\u914D\u7F6E\u5E93\u4F46\u672A\u6539\u5199\u539F\u751F\u6587\u4EF6\uFF0C\u8BF7\u624B\u52A8\u91CD\u65B0\u6FC0\u6D3B`);
13843
+ }
13844
+ } else
13845
+ imported++;
13846
+ }
13847
+ }
13848
+ const providerMap = new Map;
13849
+ for (const { profile } of selected) {
13850
+ const sourceId = profile.provider_id;
13851
+ if (!sourceId || providerMap.has(sourceId))
13852
+ continue;
13853
+ const provider = portable.providers[sourceId];
13854
+ if (!provider) {
13855
+ continue;
13856
+ }
13857
+ const targetId = this.availableProviderId(sourceId, source.username, targetVault);
13858
+ providerMap.set(sourceId, targetId);
13859
+ const { apiKey, ...storedProvider } = provider;
13860
+ targetVault.entries[targetId] = {
13861
+ ...storedProvider,
13862
+ id: targetId,
13863
+ api_key: this.crypto.encrypt(apiKey),
13864
+ created_at: new Date().toISOString(),
13865
+ updated_at: new Date().toISOString(),
13866
+ synced_from: { username: source.username, provider_id: sourceId }
13867
+ };
13868
+ }
13869
+ for (const { harness, name, profile } of selected) {
13870
+ targetProfiles[harness] ||= {};
13871
+ const mappedProvider = profile.provider_id ? providerMap.get(profile.provider_id) : undefined;
13872
+ const { apiKey, ...storedProfile } = profile;
13873
+ targetProfiles[harness][name] = {
13874
+ ...storedProfile,
13875
+ api_key: this.crypto.encrypt(apiKey),
13876
+ provider_id: mappedProvider,
13877
+ provider_endpoint: mappedProvider ? profile.provider_endpoint : undefined,
13878
+ updated_at: new Date().toISOString()
13879
+ };
13880
+ }
13881
+ try {
13882
+ this.files.writeJson(vaultPath, targetVault);
13883
+ this.files.writeJson(profilesPath, targetProfiles);
13884
+ } catch (error2) {
13885
+ this.restore(vaultPath, vaultSnapshot);
13886
+ this.restore(profilesPath, profileSnapshot);
13887
+ throw error2;
13888
+ }
13889
+ return {
13890
+ ok: true,
13891
+ sourceUser: source.username,
13892
+ targetUser: target.username,
13893
+ imported,
13894
+ overwritten,
13895
+ skipped,
13896
+ providersCopied: providerMap.size,
13897
+ warnings
13898
+ };
13899
+ }
13900
+ requireSource(sourceUsername, target) {
13901
+ const source = this.users.require(sourceUsername);
13902
+ if (source.username === target.username) {
13903
+ throw new HttpError(400, "\u6765\u6E90\u7528\u6237\u4E0D\u80FD\u4E0E\u5F53\u524D\u76EE\u6807\u7528\u6237\u76F8\u540C");
13904
+ }
13905
+ return source;
13906
+ }
13907
+ readPortable(source) {
13908
+ return this.environment.runAsUser(source, () => {
13909
+ const profiles = this.readProfiles();
13910
+ const vault = this.readVault();
13911
+ const portableProviders = {};
13912
+ for (const [id, entry] of Object.entries(vault.entries)) {
13913
+ portableProviders[id] = { ...entry, apiKey: this.crypto.decrypt(entry.api_key) };
13914
+ }
13915
+ const portableProfiles = {};
13916
+ for (const [harness, entries] of Object.entries(profiles)) {
13917
+ portableProfiles[harness] = {};
13918
+ for (const [name, profile] of Object.entries(entries)) {
13919
+ const providerKey = profile.provider_id ? portableProviders[profile.provider_id]?.apiKey : undefined;
13920
+ portableProfiles[harness][name] = {
13921
+ ...profile,
13922
+ apiKey: providerKey ?? this.crypto.decrypt(profile.api_key)
13923
+ };
13924
+ }
13925
+ }
13926
+ return { profiles: portableProfiles, providers: portableProviders };
13927
+ });
13928
+ }
13929
+ readProfiles() {
13930
+ return this.files.readJsonStrict(this.environment.files.profiles, {});
13931
+ }
13932
+ readVault() {
13933
+ return this.files.readJsonStrict(this.environment.files.vault, {
13934
+ version: 1,
13935
+ entries: {}
13936
+ });
13937
+ }
13938
+ availableProviderId(sourceId, sourceUsername, target) {
13939
+ const previous = Object.values(target.entries).find((entry) => entry.synced_from?.username === sourceUsername && entry.synced_from.provider_id === sourceId);
13940
+ if (previous)
13941
+ return previous.id;
13942
+ if (!target.entries[sourceId])
13943
+ return sourceId;
13944
+ const suffix = sourceUsername.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").slice(0, 24);
13945
+ const base = `${sourceId}-${suffix || "copy"}`.slice(0, 60);
13946
+ let candidate = base;
13947
+ let index = 2;
13948
+ while (target.entries[candidate]) {
13949
+ candidate = `${base}-${index}`.slice(0, 64);
13950
+ index++;
13951
+ }
13952
+ return candidate;
13953
+ }
13954
+ restore(path, snapshot) {
13955
+ try {
13956
+ if (snapshot === undefined)
13957
+ this.files.remove(path);
13958
+ else
13959
+ this.files.writeSecure(path, snapshot);
13960
+ } catch {}
13961
+ }
13962
+ }
13963
+ UserSyncService = __decorateElement(_init, 0, "UserSyncService", _dec, UserSyncService);
13964
+ __runInitializers(_init, 1, UserSyncService);
13965
+ __decoratorMetadata(_init, UserSyncService);
13966
+ let _UserSyncService = UserSyncService;
13967
+
13968
+ // src/http/routes/users.ts
13969
+ function createUserRoutes(services) {
13970
+ const app = new Hono2;
13971
+ const auth = services.get(IAuthService);
13972
+ const environment = services.get(IEnvironmentService);
13973
+ const users = services.get(IUserService);
13974
+ const sync = services.get(IUserSyncService);
13975
+ app.get("/", (c) => {
13976
+ const current = environment.currentUser.username;
13977
+ return c.json({
13978
+ currentUser: current,
13979
+ items: users.list().map((user) => ({ ...user, current: user.username === current }))
13980
+ });
13981
+ });
13982
+ app.post("/sync/preview", async (c) => {
13983
+ const body = await readBody4(c.req.json.bind(c.req));
13984
+ return c.json(sync.preview(String(body.sourceUser ?? "")));
13985
+ });
13986
+ app.post("/sync", async (c) => {
13987
+ const body = await readBody4(c.req.json.bind(c.req));
13988
+ return c.json(sync.sync(String(body.sourceUser ?? ""), body.conflictPolicy ?? "skip"));
13989
+ });
13990
+ app.post("/:username/select", (c) => {
13991
+ const user = users.require(decodeURIComponent(c.req.param("username")));
13992
+ const token = getCookie(c, environment.cookieName);
13993
+ if (!token)
13994
+ throw new HttpError(401, "authentication required");
13995
+ auth.selectUser(token, user.username);
13996
+ return c.json({ currentUser: user.username });
13997
+ });
13998
+ return app;
13999
+ }
14000
+ async function readBody4(read) {
14001
+ return read().catch(() => {
14002
+ throw new HttpError(400, "invalid json");
14003
+ });
14004
+ }
14005
+
13587
14006
  // src/app.ts
13588
14007
  function createApp(services) {
13589
14008
  const app = new Hono2;
@@ -13595,6 +14014,9 @@ function createApp(services) {
13595
14014
  api.use("*", createOriginGuard());
13596
14015
  api.get("/version", async (c) => c.json({ name: "harness-switch", version: await serverVersion() }));
13597
14016
  api.route("/auth", createAuthRoutes(services));
14017
+ api.use("/users/*", createAuthGuard(services));
14018
+ api.use("/users", createAuthGuard(services));
14019
+ api.route("/users", createUserRoutes(services));
13598
14020
  api.use("/harnesses/*", createAuthGuard(services));
13599
14021
  api.use("/harnesses", createAuthGuard(services));
13600
14022
  api.route("/harnesses", createHarnessRoutes(services));
@@ -13617,18 +14039,18 @@ function createApp(services) {
13617
14039
  api.route("/drift", createDriftRoutes(services));
13618
14040
  app.route("/api", api);
13619
14041
  const publicDir = environment.publicDir;
13620
- if (existsSync3(publicDir)) {
14042
+ if (existsSync4(publicDir)) {
13621
14043
  app.use("/assets/*", serveStatic2({ root: publicDir }));
13622
14044
  app.get("*", async (c, next) => {
13623
14045
  if (c.req.path.startsWith("/api") || c.req.path === "/healthz") {
13624
14046
  return next();
13625
14047
  }
13626
14048
  const assetPath = join11(publicDir, c.req.path.replace(/^\//, ""));
13627
- if (c.req.path !== "/" && existsSync3(assetPath)) {
14049
+ if (c.req.path !== "/" && existsSync4(assetPath)) {
13628
14050
  return serveStatic2({ root: publicDir })(c, next);
13629
14051
  }
13630
14052
  const index = join11(publicDir, "index.html");
13631
- if (existsSync3(index)) {
14053
+ if (existsSync4(index)) {
13632
14054
  c.header("Cache-Control", "no-store");
13633
14055
  return c.html(await Bun.file(index).text());
13634
14056
  }
@@ -13651,6 +14073,8 @@ function createServices() {
13651
14073
  const collection = new ServiceCollection;
13652
14074
  collection.set(ILogService, new SyncDescriptor(LogService));
13653
14075
  collection.set(IEnvironmentService, new SyncDescriptor(EnvironmentService));
14076
+ collection.set(IUserService, new SyncDescriptor(UserService));
14077
+ collection.set(IUserSyncService, new SyncDescriptor(UserSyncService));
13654
14078
  collection.set(IFileService, new SyncDescriptor(FileService));
13655
14079
  collection.set(ICryptoService, new SyncDescriptor(CryptoService));
13656
14080
  collection.set(IAuthService, new SyncDescriptor(AuthService));
@@ -13671,14 +14095,22 @@ function createServices() {
13671
14095
  function parseArgs(argv) {
13672
14096
  const flags = {};
13673
14097
  const positional = [];
13674
- for (const arg of argv) {
14098
+ const valueFlags = new Set(["user", "from", "to", "harness"]);
14099
+ for (let index = 0;index < argv.length; index++) {
14100
+ const arg = argv[index];
13675
14101
  if (arg.startsWith("--")) {
13676
14102
  const body = arg.slice(2);
13677
14103
  const separator = body.indexOf("=");
13678
14104
  if (separator !== -1) {
13679
14105
  flags[body.slice(0, separator)] = body.slice(separator + 1);
13680
14106
  } else {
13681
- flags[body] = true;
14107
+ const next = argv[index + 1];
14108
+ if (valueFlags.has(body) && next && !next.startsWith("--")) {
14109
+ flags[body] = next;
14110
+ index++;
14111
+ } else {
14112
+ flags[body] = true;
14113
+ }
13682
14114
  }
13683
14115
  } else {
13684
14116
  positional.push(arg);
@@ -13713,12 +14145,12 @@ import { stdin, stdout } from "process";
13713
14145
  import { createInterface } from "readline/promises";
13714
14146
 
13715
14147
  // src/cli/client.ts
13716
- import { readFileSync as readFileSync3 } from "fs";
14148
+ import { readFileSync as readFileSync4 } from "fs";
13717
14149
  import { join as join13 } from "path";
13718
14150
 
13719
14151
  // src/daemon.ts
13720
14152
  import { spawn as spawn2 } from "child_process";
13721
- import { mkdirSync as mkdirSync4, openSync as openSync2, readFileSync as readFileSync2, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
14153
+ import { mkdirSync as mkdirSync4, openSync as openSync2, readFileSync as readFileSync3, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
13722
14154
  import { homedir as homedir3 } from "os";
13723
14155
  import { join as join12, resolve } from "path";
13724
14156
  var DEFAULT_HOST = "127.0.0.1";
@@ -13736,7 +14168,7 @@ function daemonLogFile() {
13736
14168
  }
13737
14169
  function readPid() {
13738
14170
  try {
13739
- const raw2 = readFileSync2(daemonPidFile(), "utf8").trim();
14171
+ const raw2 = readFileSync3(daemonPidFile(), "utf8").trim();
13740
14172
  const pid = Number(raw2);
13741
14173
  return Number.isInteger(pid) && pid > 0 ? pid : null;
13742
14174
  } catch {
@@ -13904,7 +14336,7 @@ function resolveBaseUrl() {
13904
14336
  function readWebPassword() {
13905
14337
  const file = join13(daemonDataDir(), "web_password");
13906
14338
  try {
13907
- return readFileSync3(file, "utf8").trim();
14339
+ return readFileSync4(file, "utf8").trim();
13908
14340
  } catch {
13909
14341
  throw new CliError(`\u672A\u627E\u5230 ${file}\u3002\u8BF7\u5148\u8FD0\u884C\u4E00\u6B21\u670D\u52A1\uFF08harness-switch daemon \u6216 server\uFF09\u751F\u6210\u5BC6\u7801\uFF0C\u518D\u4F7F\u7528 CLI\u3002`);
13910
14342
  }
@@ -13992,12 +14424,16 @@ function cliUsage() {
13992
14424
  " doctor [--probe] [--harness H] run diagnostics (add --probe for /models checks)",
13993
14425
  " plan <harness> <profile> show the exact content activation would write",
13994
14426
  " activate <harness> <profile> activate a profile (add --yes to skip the prompt)",
14427
+ " users list manageable local Unix users",
14428
+ " sync --from USER --to USER copy profiles and credentials between users",
13995
14429
  "",
13996
14430
  "options:",
13997
14431
  " --json machine-readable JSON output",
13998
14432
  " --yes skip confirmation for activate",
13999
14433
  " --probe run the /models connectivity probe in doctor",
14000
14434
  " --harness H limit doctor to one harness",
14435
+ " --user USER run list/providers/doctor/plan/activate for this Unix user",
14436
+ " --overwrite overwrite same-name profiles during sync (default: skip)",
14001
14437
  "",
14002
14438
  "environment:",
14003
14439
  " HSW_URL base URL of the local service (default http://127.0.0.1:8787)",
@@ -14014,6 +14450,10 @@ async function runCli(command, positional, flags) {
14014
14450
  try {
14015
14451
  client = new CliClient(resolveBaseUrl(), readWebPassword());
14016
14452
  await client.login();
14453
+ const selectedUser = flagValue(flags, "user");
14454
+ if (selectedUser) {
14455
+ await selectUser(client, selectedUser);
14456
+ }
14017
14457
  } catch (error2) {
14018
14458
  return fail(error2, json);
14019
14459
  }
@@ -14029,6 +14469,10 @@ async function runCli(command, positional, flags) {
14029
14469
  return await cmdPlan(client, positional, json);
14030
14470
  case "activate":
14031
14471
  return await cmdActivate(client, positional, flags, json);
14472
+ case "users":
14473
+ return await cmdUsers(client, json);
14474
+ case "sync":
14475
+ return await cmdSync(client, flags, json);
14032
14476
  default:
14033
14477
  console.error(cliUsage());
14034
14478
  throw new CliError(`unknown command: ${command}`);
@@ -14037,6 +14481,40 @@ async function runCli(command, positional, flags) {
14037
14481
  return fail(error2, json);
14038
14482
  }
14039
14483
  }
14484
+ async function selectUser(client, username) {
14485
+ await client.post(`/api/users/${encodeURIComponent(username)}/select`);
14486
+ }
14487
+ async function cmdUsers(client, json) {
14488
+ const payload = await client.get("/api/users");
14489
+ if (json === "json") {
14490
+ printJson(payload);
14491
+ } else {
14492
+ for (const user of payload.items) {
14493
+ console.log(`${user.current ? "*" : " "} ${user.username.padEnd(20)} ${user.homeDir}`);
14494
+ }
14495
+ }
14496
+ return 0;
14497
+ }
14498
+ async function cmdSync(client, flags, json) {
14499
+ const source = flagValue(flags, "from");
14500
+ const target = flagValue(flags, "to") || flagValue(flags, "user");
14501
+ if (!source || !target) {
14502
+ throw new CliError("sync \u9700\u8981 --from <\u6765\u6E90\u7528\u6237> \u548C --to <\u76EE\u6807\u7528\u6237>");
14503
+ }
14504
+ await selectUser(client, target);
14505
+ const conflictPolicy = hasFlag(flags, "overwrite") ? "overwrite" : "skip";
14506
+ const payload = await client.post("/api/users/sync", {
14507
+ sourceUser: source,
14508
+ conflictPolicy
14509
+ });
14510
+ if (json === "json") {
14511
+ printJson(payload);
14512
+ } else {
14513
+ console.log(`\u5DF2\u4ECE ${source} \u540C\u6B65\u5230 ${target}`);
14514
+ console.log(`\u65B0\u589E=${payload.imported} \u8986\u76D6=${payload.overwritten} \u8DF3\u8FC7=${payload.skipped} \u51ED\u636E=${payload.providersCopied}`);
14515
+ }
14516
+ return 0;
14517
+ }
14040
14518
  async function cmdList(client, json) {
14041
14519
  const payload = await client.get("/api/harnesses");
14042
14520
  if (json === "json") {
@@ -14149,7 +14627,7 @@ if (command === "server") {
14149
14627
  await stopDaemon();
14150
14628
  } else if (command === "status") {
14151
14629
  printStatus();
14152
- } else if (command === "list" || command === "providers" || command === "doctor" || command === "plan" || command === "activate") {
14630
+ } else if (command === "list" || command === "providers" || command === "doctor" || command === "plan" || command === "activate" || command === "users" || command === "sync") {
14153
14631
  const { flags, positional } = parseArgs(rest);
14154
14632
  process.exitCode = await runCli(command, positional, flags);
14155
14633
  } else if (command === undefined || command === "daemon") {