@modelprofile.com/authswitch 8.2.0 → 9.0.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.
Files changed (50) hide show
  1. package/dist_ts/00_commitinfo_data.js +1 -1
  2. package/dist_ts/authority-contract.d.ts +18 -1
  3. package/dist_ts/authority-contract.js +3 -2
  4. package/dist_ts/authority-paths.d.ts +37 -0
  5. package/dist_ts/authority-paths.js +46 -0
  6. package/dist_ts/authority-runtime-contract.d.ts +11 -1
  7. package/dist_ts/classes.authoritybroker.d.ts +9 -0
  8. package/dist_ts/classes.authoritybroker.js +70 -10
  9. package/dist_ts/classes.authorityclient.js +20 -1
  10. package/dist_ts/classes.authoritydaemon.d.ts +14 -3
  11. package/dist_ts/classes.authoritydaemon.js +33 -2
  12. package/dist_ts/classes.authoritydatabase.js +11 -2
  13. package/dist_ts/classes.authorityimport.d.ts +16 -4
  14. package/dist_ts/classes.authorityimport.js +74 -23
  15. package/dist_ts/classes.authoritypreuse.js +8 -3
  16. package/dist_ts/classes.authorityservice.d.ts +10 -11
  17. package/dist_ts/classes.authorityservice.js +14 -23
  18. package/dist_ts/classes.cli.d.ts +10 -2
  19. package/dist_ts/classes.cli.js +12 -4
  20. package/dist_ts/classes.codexmanaged.d.ts +8 -0
  21. package/dist_ts/classes.codexmanaged.js +19 -12
  22. package/dist_ts/classes.legacyfence.d.ts +53 -0
  23. package/dist_ts/classes.legacyfence.js +189 -0
  24. package/dist_ts/classes.operations.d.ts +15 -3
  25. package/dist_ts/classes.operations.js +22 -4
  26. package/dist_ts/classes.service.d.ts +21 -2
  27. package/dist_ts/classes.service.js +35 -8
  28. package/dist_ts/classes.tui.d.ts +2 -1
  29. package/dist_ts/classes.tui.js +3 -2
  30. package/dist_ts/ts_migration/legacysources/authswitchstores.js +5 -2
  31. package/package.json +7 -7
  32. package/readme.md +129 -17
  33. package/ts/00_commitinfo_data.ts +1 -1
  34. package/ts/authority-contract.ts +20 -1
  35. package/ts/authority-paths.ts +69 -0
  36. package/ts/authority-runtime-contract.ts +11 -1
  37. package/ts/classes.authoritybroker.ts +68 -10
  38. package/ts/classes.authorityclient.ts +16 -0
  39. package/ts/classes.authoritydaemon.ts +45 -4
  40. package/ts/classes.authoritydatabase.ts +10 -1
  41. package/ts/classes.authorityimport.ts +101 -24
  42. package/ts/classes.authoritypreuse.ts +7 -1
  43. package/ts/classes.authorityservice.ts +15 -30
  44. package/ts/classes.cli.ts +14 -3
  45. package/ts/classes.codexmanaged.ts +18 -7
  46. package/ts/classes.legacyfence.ts +219 -0
  47. package/ts/classes.operations.ts +22 -3
  48. package/ts/classes.service.ts +45 -8
  49. package/ts/classes.tui.ts +3 -1
  50. package/ts/ts_migration/legacysources/authswitchstores.ts +4 -1
@@ -28,6 +28,15 @@ export interface IAuthSwitchCodexInteractiveCommand {
28
28
  env: NodeJS.ProcessEnv;
29
29
  }
30
30
 
31
+ /**
32
+ * The one Codex release whose app-server contract managed Codex was verified against: the
33
+ * external-token login and its refresh callback, thread/turn start and resume, `--listen` and
34
+ * how it publishes that socket, `--strict-config`, the ephemeral credential store and
35
+ * `--remote`. Both the CLI and the app-server it serves must report exactly this release;
36
+ * any other is refused unverified.
37
+ */
38
+ export const MANAGED_CODEX_VERSION = '0.157.0';
39
+
31
40
  const isRecord = (value: unknown): value is Record<string, unknown> =>
32
41
  value !== null && typeof value === 'object' && !Array.isArray(value);
33
42
  const isAlive = (child: plugins.childProcess.ChildProcess): boolean => child.exitCode === null && child.signalCode === null;
@@ -162,7 +171,9 @@ export class AuthSwitchManagedCodex {
162
171
  else resolve(stdout.trim());
163
172
  });
164
173
  });
165
- if (output !== 'codex-cli 0.155.1') throw new Error('Managed Codex requires verified codex-cli 0.155.1.');
174
+ if (output !== `codex-cli ${MANAGED_CODEX_VERSION}`) {
175
+ throw new Error(`Managed Codex requires verified codex-cli ${MANAGED_CODEX_VERSION}.`);
176
+ }
166
177
  }
167
178
 
168
179
  public start(): Promise<void> {
@@ -202,6 +213,9 @@ export class AuthSwitchManagedCodex {
202
213
  if (this.closed) throw new Error('Managed Codex startup was cancelled.');
203
214
  this.workspaceId = initial.accountId;
204
215
  this.grantedGeneration = initial.grantGeneration;
216
+ // Codex binds the socket elsewhere and publishes this path as an alias; deriving where
217
+ // proves the host can verify that alias before any run is recorded or process started.
218
+ await plugins.crossharness.codexUnixSocketTarget(this.socketPath);
205
219
  await this.options.onPreparedRun(this.socketPath);
206
220
  if (this.closed) throw new Error('Managed Codex startup was cancelled.');
207
221
  const child = plugins.childProcess.spawn(this.options.executable ?? 'codex', [
@@ -226,11 +240,7 @@ export class AuthSwitchManagedCodex {
226
240
  while (true) {
227
241
  if (this.closed) throw new Error('Managed Codex startup was cancelled.');
228
242
  if (!isAlive(child)) throw new Error('Managed Codex app-server exited before accepting connections.');
229
- try {
230
- if ((await plugins.fs.promises.lstat(this.socketPath)).isSocket()) break;
231
- } catch (error) {
232
- if (!isRecord(error) || error.code !== 'ENOENT') throw error;
233
- }
243
+ if (await plugins.crossharness.observeCodexUnixSocket(this.socketPath) === 'published') break;
234
244
  if (Date.now() >= deadline) throw new Error('Managed Codex app-server socket startup timed out.');
235
245
  await wait(25);
236
246
  }
@@ -248,7 +258,8 @@ export class AuthSwitchManagedCodex {
248
258
  });
249
259
  this.client = client;
250
260
  await client.connect();
251
- if (client.serverVersion !== '0.155.1') throw new Error('Managed Codex app-server version changed.');
261
+ // The executable can be replaced between the version probe and the spawn (Codex updates itself).
262
+ if (client.serverVersion !== MANAGED_CODEX_VERSION) throw new Error('Managed Codex app-server version changed.');
252
263
  const login: unknown = await client.request('account/login/start', {
253
264
  type: 'chatgptAuthTokens', accessToken: initial.accessToken, chatgptAccountId: initial.accountId,
254
265
  }, 5_000);
@@ -0,0 +1,219 @@
1
+ import * as plugins from './plugins.js';
2
+ import { AuthSwitchRefusal } from './authority-contract.js';
3
+ import { authSwitchAuthoritySocketPaths, authSwitchAuthorityUnitDirectory,
4
+ authSwitchAuthorityUnitName } from './authority-paths.js';
5
+ import { AuthSwitchClient } from './classes.authorityclient.js';
6
+ import { StashStore } from './classes.stashstore.js';
7
+ import { legacyHash, legacySourceId,
8
+ resolveLegacySourceLocations } from './ts_migration/legacysources/shared.js';
9
+ import type { TAuthSwitchMutation } from './mutation.js';
10
+ import type { IAuthHarness } from './interfaces.harness.js';
11
+
12
+ /**
13
+ * The gate between the legacy credential commands and an account the authority has taken over.
14
+ *
15
+ * An import is a transfer of ownership, not a copy: the moment the authority refreshes an adopted login,
16
+ * the legacy saved copy holds a refresh token the provider has already rotated away. Writing that copy back
17
+ * into a native store -- which is what the legacy `save` and `switch` do -- would hand a tool a credential
18
+ * that is dead, and the owner would learn it from the tool rather than from here. This is the one place
19
+ * that stops it, and it stops it for the hosted service too, because `runAuthSwitchMutation` is the
20
+ * chokepoint both the command line and `AuthSwitchService` pass through.
21
+ *
22
+ * An authority that answers decides from its migration ledger alone. The ledger names a source by the hash
23
+ * of its own path, which is exactly what the legacy side can compute for the record it is about to touch, so
24
+ * no account identity has to be mapped between the two worlds: the legacy account id names a file, the file
25
+ * names a row, and the row says whether the authority took it. One that does not answer is decided by
26
+ * whether its service unit is installed (`authorityUnitInstalled`).
27
+ */
28
+
29
+ /** Where a fence looks: this host's legacy stores and this host's authority, both stated by the caller. */
30
+ export interface IAuthSwitchLegacyFenceLocations {
31
+ env: NodeJS.ProcessEnv;
32
+ homeDirectory: string;
33
+ }
34
+
35
+ /**
36
+ * What a caller states, exactly as a daemon states where it reads the legacy stores.
37
+ *
38
+ * `'none'` is for a caller that is not this host's own credential tooling -- a fixture, or a harness test
39
+ * that owns no authority -- and it is stated rather than defaulted, because a fence that silently pointed
40
+ * at `process.env` from inside a test would read whichever host ran it.
41
+ */
42
+ export type TAuthSwitchLegacyFence = IAuthSwitchLegacyFenceLocations | 'none';
43
+
44
+ /**
45
+ * This host's own locations, for a caller whose harnesses are this host's own.
46
+ *
47
+ * `AuthSwitchCli` and `AuthSwitchService` use it when they compose their harnesses from this process's
48
+ * environment, and a host that composes them the same way -- AGL -- states it explicitly. A fence that named
49
+ * anything else would be fencing other stores than the ones those harnesses write. Everything below them --
50
+ * `AuthSwitchOperations`, `runAuthSwitchMutation` -- takes it as an argument, so no library path can pick
51
+ * up a host it was never given.
52
+ */
53
+ export const authSwitchHostLegacyFence = (): IAuthSwitchLegacyFenceLocations =>
54
+ ({ env: process.env, homeDirectory: plugins.os.homedir() });
55
+
56
+ const fenceRequired = 'An authswitch account mutation requires stated legacy fence locations: pass an env '
57
+ + 'and an absolute homeDirectory, or "none" for a caller that owns no authority.';
58
+
59
+ /** The same check for a caller with types and one without. */
60
+ export function assertStatedLegacyFence(value: unknown): asserts value is TAuthSwitchLegacyFence {
61
+ if (value === 'none') return;
62
+ if (value === null || typeof value !== 'object'
63
+ || typeof (value as { env?: unknown }).env !== 'object' || (value as { env?: unknown }).env === null
64
+ || typeof (value as { homeDirectory?: unknown }).homeDirectory !== 'string'
65
+ || !plugins.path.isAbsolute((value as { homeDirectory: string }).homeDirectory)) {
66
+ throw new Error(fenceRequired);
67
+ }
68
+ }
69
+
70
+ /**
71
+ * What the owner is told. Neither names a path, an id or a host; each names the command that helps.
72
+ *
73
+ * There is no authority command that activates a login in a native store, and that is the point: a login
74
+ * the authority holds is used by binding a runtime to it, which is what AGL does, so the instruction names
75
+ * the read that shows it rather than inventing a replacement for `switch`.
76
+ */
77
+ const authorityHoldsLogin = 'The account authority holds this login now: its legacy saved copy is stale, '
78
+ + 'so the legacy save and switch no longer apply to it. "authswitch account list" shows the account; a '
79
+ + 'runtime uses it by binding to it through the authority.';
80
+ const authorityUnavailable = 'This host has an account authority and it is not answering, so whether it '
81
+ + 'holds this login cannot be known. Start it with "authswitch authority service start" and run this '
82
+ + 'again.';
83
+
84
+ /** A settled row is one whose source was taken over. Both statuses mean the legacy copy is finished. */
85
+ const settled = new Set(['verified', 'complete']);
86
+
87
+ /** How long the gate may wait on the authority before a mutation is refused rather than delayed. */
88
+ const ASK_TIMEOUT_MS = 4_000;
89
+
90
+ /**
91
+ * The legacy store paths one mutation would read or write, as the migration readers name them.
92
+ *
93
+ * Codex keeps a stash directory per account, Claude and OpenCode a record file per account, and the reader
94
+ * of each derives its ledger row from that exact path (`ts_migration/legacysources/authswitchstores.ts`).
95
+ * Only the account the mutation names is looked up: a switch also re-saves the outgoing login, but writing
96
+ * a record rotates nothing, while activating one is the write this fence exists for.
97
+ */
98
+ const mutationSourcePaths = (root: string, harnessId: string, accountId: string): string[] => {
99
+ if (harnessId === 'codex') {
100
+ try { return [new StashStore('codex', root).entryDir(accountId)]; }
101
+ // An account id no stash name can be derived from names no stash, and therefore no ledger row.
102
+ catch { return []; }
103
+ }
104
+ if (harnessId === 'claude' || harnessId === 'opencode') {
105
+ return /^[a-f0-9]{64}$/.test(accountId)
106
+ ? [plugins.path.join(root, harnessId, `${accountId}.json`)] : [];
107
+ }
108
+ // A harness this package never wrote a legacy store for has no legacy copy to strand.
109
+ return [];
110
+ };
111
+
112
+ /** Which account a mutation touches. A save without one saves whatever login is active right now. */
113
+ const mutationAccountId = async (harness: IAuthHarness,
114
+ mutation: TAuthSwitchMutation): Promise<string | null> => {
115
+ if (mutation.accountId !== undefined) return mutation.accountId;
116
+ if (mutation.action !== 'save') return null;
117
+ const state = await harness.readState();
118
+ return state.accounts.find(account => account.isActive)?.id ?? null;
119
+ };
120
+
121
+ /** What the legacy source a mutation names looks like to an authority that answers. */
122
+ type TLedgerAnswer = 'settled' | 'not_settled' | 'no_answer';
123
+
124
+ /**
125
+ * One bounded, paged read of the ledger over the management socket: credential-free, and it reaches no
126
+ * legacy store. Anything but a complete answer -- no runtime directory, no socket, a socket that never
127
+ * answers within the bound, a daemon that serves no import status -- is `no_answer`, never "nothing held".
128
+ */
129
+ const askLedger = async (env: NodeJS.ProcessEnv, sourceIds: ReadonlySet<string>): Promise<TLedgerAnswer> => {
130
+ // Only the stated environment names a socket, and nothing else decides which one: the full path resolver
131
+ // defaults an absent directory to this process's own and reads this process's home and XDG_DATA_HOME for
132
+ // the store, so a value there would silence an authority that answers.
133
+ if (!env.XDG_RUNTIME_DIR) return 'no_answer';
134
+ let client: AuthSwitchClient;
135
+ try {
136
+ const paths = authSwitchAuthoritySocketPaths(env.XDG_RUNTIME_DIR);
137
+ client = new AuthSwitchClient(paths.authoritySocketPath, paths.runtimeSocketPath);
138
+ } catch { return 'no_answer'; }
139
+ const deadline = AbortSignal.timeout(ASK_TIMEOUT_MS);
140
+ let after: string | undefined;
141
+ try {
142
+ while (true) {
143
+ const page = await client.importStatus({ after, limit: 128 }, deadline);
144
+ if (page.entries.some(entry => sourceIds.has(entry.sourceId) && settled.has(entry.status))) return 'settled';
145
+ if (!page.nextCursor) return 'not_settled';
146
+ after = page.nextCursor;
147
+ }
148
+ } catch { return 'no_answer'; }
149
+ };
150
+
151
+ const unitUnreadable = 'The authswitch authority service unit could not be inspected, so whether an account '
152
+ + 'authority is installed here cannot be known; the legacy save and switch refuse until it can.';
153
+
154
+ /**
155
+ * Whether this user has the authority's service unit installed: the durable evidence that an authority
156
+ * exists here even while it is not running.
157
+ *
158
+ * The unit is what `authswitch authority service install` writes, in the directory
159
+ * `authSwitchAuthorityUnitDirectory` derives from the caller's stated locations, and it survives a reboot --
160
+ * the management socket does not: it lives on tmpfs and is absent after every boot until the service
161
+ * starts. It is read through smartdaemon's own `SystemdUnitFile.inspect()`, which checks the exact file the
162
+ * installer writes and reads nothing else; its content is a service definition, never a credential.
163
+ *
164
+ * The read needs no login session. `inspect()` reads only the unit directory, so the fence hands smartdaemon
165
+ * no runtime directory: the stated one belongs to the ledger ask above, and passing it here would let a value
166
+ * this read never uses refuse the command. The answer therefore depends on the stated unit directory alone,
167
+ * and a cron job or a plain ssh command -- no `XDG_RUNTIME_DIR` at all -- is decided exactly like a session.
168
+ *
169
+ * smartdaemon agrees: with an explicit unit directory it validates only that directory at construction, and
170
+ * `inspect()` never reads this process's `XDG_RUNTIME_DIR`, `XDG_CONFIG_HOME`, `XDG_DATA_HOME` or home, so
171
+ * none of them can change the answer.
172
+ *
173
+ * systemd is the only installer this package has, so on another platform no unit can be installed. Any
174
+ * failure to inspect it -- an unsafe or changed file, a directory another user can write -- is not an answer,
175
+ * and refuses. So does a stated unit directory that cannot be derived or that smartdaemon refuses to
176
+ * construct the read from (a relative or malformed stated `XDG_DATA_HOME`): the stated locations then name no
177
+ * directory to look in, an installer running with well-formed locations may have written the unit elsewhere,
178
+ * and reading that as "no authority here" would be a guess.
179
+ */
180
+ const authorityUnitInstalled = async (fence: IAuthSwitchLegacyFenceLocations): Promise<boolean> => {
181
+ if (process.platform !== 'linux') return false;
182
+ // One catch covers derivation, construction and inspection: each failure leaves the same question open.
183
+ try {
184
+ const unitFile = new plugins.smartdaemon.SystemdUnitFile({ unitName: authSwitchAuthorityUnitName,
185
+ scope: 'user', unitDirectory: authSwitchAuthorityUnitDirectory(fence.env, fence.homeDirectory) });
186
+ return await unitFile.inspect() !== null;
187
+ } catch { throw new Error(unitUnreadable); }
188
+ };
189
+
190
+ /**
191
+ * The gate itself: allow, or refuse with the reason.
192
+ *
193
+ * An authority that answers decides, whether or not its unit is installed: its ledger is the only record
194
+ * of what it took over. One that does not answer is unknown -- and unknown is never idle -- but only where
195
+ * an authority is installed at all; a host without the unit is known to hold nothing, and it is every host
196
+ * before the cutover. The evidence cannot tell which stores an installed authority imports from, so while it
197
+ * is stopped it refuses the legacy save and switch of every store, until it runs again.
198
+ */
199
+ export const assertAuthSwitchMutationAllowed = async (fence: TAuthSwitchLegacyFence,
200
+ harness: IAuthHarness, mutation: TAuthSwitchMutation): Promise<void> => {
201
+ assertStatedLegacyFence(fence);
202
+ if (fence === 'none') return;
203
+ // A remove deletes a saved copy and writes no credential, which is why the legacy `drop` command is
204
+ // deliberately unfenced as well: for an adopted account that copy already holds a rotated-away token.
205
+ if (mutation.action !== 'save' && mutation.action !== 'switch') return;
206
+
207
+ const root = resolveLegacySourceLocations(fence.env, fence.homeDirectory).authSwitchHome;
208
+ const accountId = await mutationAccountId(harness, mutation);
209
+ const paths = accountId === null ? [] : mutationSourcePaths(root, harness.id, accountId);
210
+ // A mutation that names no legacy record the importer reads can never have been imported, so there is
211
+ // nothing to ask about, and the answer must not depend on whether an authority is up.
212
+ if (paths.length === 0) return;
213
+
214
+ const answer = await askLedger(fence.env,
215
+ new Set(paths.map(path => legacySourceId('authswitch_stash', legacyHash(path)))));
216
+ if (answer === 'settled') throw new AuthSwitchRefusal('authority_holds_login', authorityHoldsLogin);
217
+ if (answer === 'not_settled') return;
218
+ if (await authorityUnitInstalled(fence)) throw new AuthSwitchRefusal('authority_unavailable', authorityUnavailable);
219
+ };
@@ -1,6 +1,8 @@
1
1
  import * as plugins from './plugins.js';
2
2
  import { authSwitchHome } from './classes.credentialstore.js';
3
3
  import { assertAuthSwitchMutation, type TAuthSwitchMutation } from './mutation.js';
4
+ import { assertAuthSwitchMutationAllowed, assertStatedLegacyFence,
5
+ type TAuthSwitchLegacyFence } from './classes.legacyfence.js';
4
6
  import type { IAuthHarness, IHarnessOutcome } from './interfaces.harness.js';
5
7
 
6
8
  /**
@@ -8,6 +10,8 @@ import type { IAuthHarness, IHarnessOutcome } from './interfaces.harness.js';
8
10
  * through `@modelprofile.com/authswitch/mutation`; they stay exported here for every Node caller.
9
11
  */
10
12
  export { assertAuthSwitchMutation, authSwitchMutationReplacesLogin, type TAuthSwitchMutation } from './mutation.js';
13
+ export { authSwitchHostLegacyFence, type TAuthSwitchLegacyFence,
14
+ type IAuthSwitchLegacyFenceLocations } from './classes.legacyfence.js';
11
15
 
12
16
  export interface IAuthSwitchCoordinationRequest {
13
17
  protocolVersion: 1;
@@ -41,9 +45,19 @@ export const authSwitchEnvironmentId = (env: NodeJS.ProcessEnv = process.env): s
41
45
  openCodeOverride: env.OPENCODE_AUTH_CONTENT !== undefined,
42
46
  })).digest('hex');
43
47
 
44
- export const runAuthSwitchMutation = async (harness: IAuthHarness, mutation: TAuthSwitchMutation): Promise<IHarnessOutcome> => {
48
+ /**
49
+ * The one mutation chokepoint, and therefore the one place the legacy fence can sit.
50
+ *
51
+ * `AuthSwitchOperations.run` delegates here and the AGL-hosted `AuthSwitchService` calls it directly, so a
52
+ * fence inside the class would leave the hosted path open. Where it looks is stated by the caller rather
53
+ * than defaulted, for the reason the authority states its own legacy locations: a fence that reached for
54
+ * `process.env` from inside a test would read whichever host ran it.
55
+ */
56
+ export const runAuthSwitchMutation = async (harness: IAuthHarness, mutation: TAuthSwitchMutation,
57
+ legacyFence: TAuthSwitchLegacyFence): Promise<IHarnessOutcome> => {
45
58
  assertAuthSwitchMutation(mutation);
46
59
  if (harness.id !== mutation.harnessId) throw new Error('Account operation targets a different harness.');
60
+ await assertAuthSwitchMutationAllowed(legacyFence, harness, mutation);
47
61
  switch (mutation.action) {
48
62
  case 'save': return harness.saveCurrent({ keepActive: mutation.keepActive, accountId: mutation.accountId });
49
63
  case 'switch': return harness.switchAccount(mutation.accountId);
@@ -53,10 +67,15 @@ export const runAuthSwitchMutation = async (harness: IAuthHarness, mutation: TAu
53
67
 
54
68
  /** One mutation path for command, guide and TUI. Supervisors own their complete restart transaction. */
55
69
  export class AuthSwitchOperations {
56
- constructor(private readonly coordinator?: TAuthSwitchCoordinator) {}
70
+ /** `legacyFence` is stated, never defaulted: see `runAuthSwitchMutation`. */
71
+ constructor(private readonly coordinator: TAuthSwitchCoordinator | undefined,
72
+ private readonly legacyFence: TAuthSwitchLegacyFence) { assertStatedLegacyFence(legacyFence); }
57
73
  public async run(harness: IAuthHarness, mutation: TAuthSwitchMutation, confirm?: TAuthSwitchConfirmation, prepareLocal?: TAuthSwitchLocalPreparation): Promise<IHarnessOutcome> {
58
74
  assertAuthSwitchMutation(mutation);
59
75
  if (harness.id !== mutation.harnessId) throw new Error('Account operation targets a different harness.');
76
+ // Asked before AGL is, so a coordinated mutation is refused here rather than carried out by a host that
77
+ // may not fence it; `runAuthSwitchMutation` asks again, because the answer can change while it waits.
78
+ await assertAuthSwitchMutationAllowed(this.legacyFence, harness, mutation);
60
79
  if (this.coordinator && mutation.action !== 'remove') {
61
80
  const request: IAuthSwitchCoordinationRequest = { protocolVersion: 1, contextId: authSwitchEnvironmentId(), mutation, waitForIdle: false };
62
81
  let result = await this.coordinator(request);
@@ -68,7 +87,7 @@ export class AuthSwitchOperations {
68
87
  if (result.status === 'busy') return { lines: [], problems: [result.message] };
69
88
  }
70
89
  if (prepareLocal) await prepareLocal();
71
- return runAuthSwitchMutation(harness, mutation);
90
+ return runAuthSwitchMutation(harness, mutation, this.legacyFence);
72
91
  }
73
92
  }
74
93
 
@@ -4,6 +4,9 @@ import { OpenCodeHarness } from './classes.opencodeharness.js';
4
4
  import { ClaudeCodeHarness } from './classes.claudecodeharness.js';
5
5
  import { readAccountList } from './classes.accountlist.js';
6
6
  import { assertAuthSwitchMutation, authSwitchEnvironmentId, runAuthSwitchMutation, type IAuthSwitchCoordinationRequest, type TAuthSwitchCoordinationResult, type TAuthSwitchCoordinator } from './classes.operations.js';
7
+ import { AuthSwitchRefusal } from './authority-contract.js';
8
+ import { assertAuthSwitchMutationAllowed, assertStatedLegacyFence, authSwitchHostLegacyFence,
9
+ type TAuthSwitchLegacyFence } from './classes.legacyfence.js';
7
10
  import type { IAuthHarness, IHarnessLoginHandle, IHarnessLoginOptions, IHarnessLoginProvider, IHarnessLoginResult, IHarnessOutcome } from './interfaces.harness.js';
8
11
  import type { IAccountList } from './interfaces.list.js';
9
12
  import type { TAuthLoginPrompt } from './classes.login.js';
@@ -67,15 +70,51 @@ export const assertAuthSwitchServiceRequest: (value: unknown) => asserts value i
67
70
  export class AuthSwitchService {
68
71
  private readonly operations = new Map<string, IOperation>();
69
72
  private closed = false;
70
- constructor(
71
- private readonly harnesses: IAuthHarness[] = [new CodexHarness(), new OpenCodeHarness(), new ClaudeCodeHarness()],
72
- private readonly coordinator?: TAuthSwitchCoordinator,
73
- ) {}
73
+ private readonly harnesses: IAuthHarness[];
74
+ private readonly legacyFence: TAuthSwitchLegacyFence;
75
+ /**
76
+ * With no harnesses, the service composes this host's own and fences them with this host's authority.
77
+ *
78
+ * A host that injects its harnesses -- AGL does -- also states the fence for them: only it knows which
79
+ * stores they write, and a default would fence whichever host this process happens to run on.
80
+ */
81
+ constructor();
82
+ constructor(harnesses: IAuthHarness[], coordinator: TAuthSwitchCoordinator | undefined,
83
+ legacyFence: TAuthSwitchLegacyFence);
84
+ constructor(harnessesArg?: IAuthHarness[], private readonly coordinator?: TAuthSwitchCoordinator,
85
+ legacyFenceArg?: TAuthSwitchLegacyFence) {
86
+ this.harnesses = harnessesArg ?? [new CodexHarness(), new OpenCodeHarness(), new ClaudeCodeHarness()];
87
+ const legacyFence: unknown = harnessesArg === undefined ? authSwitchHostLegacyFence() : legacyFenceArg;
88
+ assertStatedLegacyFence(legacyFence);
89
+ this.legacyFence = legacyFence;
90
+ }
74
91
  private harness(id: string): IAuthHarness {
75
92
  const harness = this.harnesses.find(item => item.id === id);
76
93
  if (!harness) throw new Error('Unknown harness.');
77
94
  return harness;
78
95
  }
96
+ /**
97
+ * One hosted mutation: fenced, then coordinated, then -- when no supervisor carries it out -- run here.
98
+ *
99
+ * The fence is asked before the coordinator, as `AuthSwitchOperations` asks it: a refused mutation must not
100
+ * first have its host stop the runtimes it would restart. The local run asks again, because the answer can
101
+ * change while coordination waits. A refusal is reported as the outcome's problem: it is an answer the owner
102
+ * acts on, exactly like the credential-location mismatch `request` reports, and it wrote nothing; letting it
103
+ * fall into the operation's generic failure would hide the one sentence that says what to do instead.
104
+ */
105
+ private async mutate(harness: IAuthHarness,
106
+ coordination: IAuthSwitchCoordinationRequest): Promise<TAuthSwitchCoordinationResult> {
107
+ try {
108
+ await assertAuthSwitchMutationAllowed(this.legacyFence, harness, coordination.mutation);
109
+ const coordinated = this.coordinator ? await this.coordinator(coordination) : { status: 'unavailable' } as const;
110
+ if (coordinated.status !== 'unavailable') return coordinated;
111
+ return { status: 'complete',
112
+ outcome: await runAuthSwitchMutation(harness, coordination.mutation, this.legacyFence) };
113
+ } catch (error) {
114
+ if (error instanceof AuthSwitchRefusal) return { status: 'complete', outcome: { lines: [], problems: [error.message] } };
115
+ throw error;
116
+ }
117
+ }
79
118
  private snapshot(operation: IOperation): IAuthSwitchServiceOperation { return structuredClone(operation.status); }
80
119
  public async request(request: TAuthSwitchServiceRequest): Promise<IAuthSwitchServiceOperation> {
81
120
  assertAuthSwitchServiceRequest(request);
@@ -111,10 +150,8 @@ export class AuthSwitchService {
111
150
  operation.status.result = { status: 'complete', outcome: { lines: [], problems: ['AGL and authswitch use different credential locations. Use matching credential environment settings before switching.'] } };
112
151
  break;
113
152
  }
114
- const harness = this.harness(request.coordination.mutation.harnessId);
115
- const coordinated = this.coordinator ? await this.coordinator(request.coordination) : { status: 'unavailable' } as const;
116
- operation.status.result = publicResult(coordinated.status === 'unavailable'
117
- ? { status: 'complete', outcome: await runAuthSwitchMutation(harness, request.coordination.mutation) } : coordinated);
153
+ operation.status.result = publicResult(
154
+ await this.mutate(this.harness(request.coordination.mutation.harnessId), request.coordination));
118
155
  break;
119
156
  }
120
157
  case 'login': {
package/ts/classes.tui.ts CHANGED
@@ -13,7 +13,9 @@ const preuseResultLine = (resultArg: TPreuseAccountResult): string => resultArg.
13
13
 
14
14
  /** Owns account-management actions; terminal rendering and interaction belong to smartconsole. */
15
15
  export class AuthSwitchTui {
16
- constructor(private readonly harnesses: readonly IAuthHarness[], private readonly out: plugins.smartconsole.SmartConsole, private readonly operations = new AuthSwitchOperations()) {}
16
+ /** The guide is reached through `AuthSwitchCli`, and mutates through that command line's own operations and fence. */
17
+ constructor(private readonly harnesses: readonly IAuthHarness[], private readonly out: plugins.smartconsole.SmartConsole,
18
+ private readonly operations: AuthSwitchOperations) {}
17
19
 
18
20
  public async run(preferredArg?: IAuthHarness): Promise<number> {
19
21
  let harness = preferredArg ?? this.harnesses[0];
@@ -175,7 +175,10 @@ export const readAuthSwitchStores = (locations: ILegacySourceLocations): ILegacy
175
175
  try { entries = plugins.fs.readdirSync(locations.authSwitchHome, { withFileTypes: true }); }
176
176
  catch (error) {
177
177
  if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { sources, problems };
178
- return { sources, problems: [`${locations.authSwitchHome} could not be listed`] };
178
+ // The store is named by what it is, never by where it is: this report goes to a CLI and to a backend,
179
+ // and the location of a credential store is not something either of them may be told. Everything
180
+ // below names an entry inside the store instead, which is what the owner needs to find it.
181
+ return { sources, problems: ['the authswitch store could not be listed'] };
179
182
  }
180
183
  for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
181
184
  const path = plugins.path.join(locations.authSwitchHome, entry.name);