@modelprofile.com/authswitch 8.1.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.
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/authority-contract.d.ts +73 -0
- package/dist_ts/authority-contract.js +55 -2
- package/dist_ts/authority-import-contract.d.ts +8 -4
- package/dist_ts/authority-import-contract.js +12 -13
- package/dist_ts/authority-paths.d.ts +37 -0
- package/dist_ts/authority-paths.js +46 -0
- package/dist_ts/authority-runtime-contract.d.ts +11 -1
- package/dist_ts/classes.authoritybroker.d.ts +9 -0
- package/dist_ts/classes.authoritybroker.js +72 -11
- package/dist_ts/classes.authorityclient.d.ts +17 -11
- package/dist_ts/classes.authorityclient.js +47 -22
- package/dist_ts/classes.authoritydaemon.d.ts +22 -3
- package/dist_ts/classes.authoritydaemon.js +106 -59
- package/dist_ts/classes.authoritydatabase.d.ts +9 -1
- package/dist_ts/classes.authoritydatabase.js +39 -13
- package/dist_ts/classes.authorityimport.d.ts +33 -6
- package/dist_ts/classes.authorityimport.js +102 -25
- package/dist_ts/classes.authoritymodels.d.ts +4 -1
- package/dist_ts/classes.authoritymodels.js +15 -3
- package/dist_ts/classes.authoritypreuse.js +8 -3
- package/dist_ts/classes.authorityservice.d.ts +20 -11
- package/dist_ts/classes.authorityservice.js +37 -23
- package/dist_ts/classes.claudeauthority.js +19 -11
- package/dist_ts/classes.claudenative.d.ts +63 -3
- package/dist_ts/classes.claudenative.js +68 -8
- package/dist_ts/classes.cli.d.ts +10 -2
- package/dist_ts/classes.cli.js +12 -4
- package/dist_ts/classes.codexmanaged.d.ts +8 -0
- package/dist_ts/classes.codexmanaged.js +19 -12
- package/dist_ts/classes.legacyfence.d.ts +53 -0
- package/dist_ts/classes.legacyfence.js +189 -0
- package/dist_ts/classes.operations.d.ts +15 -3
- package/dist_ts/classes.operations.js +22 -4
- package/dist_ts/classes.service.d.ts +21 -2
- package/dist_ts/classes.service.js +35 -8
- package/dist_ts/classes.tui.d.ts +2 -1
- package/dist_ts/classes.tui.js +3 -2
- package/dist_ts/ts_migration/0003_claude_handoff_proof.d.ts +13 -0
- package/dist_ts/ts_migration/0003_claude_handoff_proof.js +20 -0
- package/dist_ts/ts_migration/index.js +3 -1
- package/dist_ts/ts_migration/legacysources/authswitchstores.js +5 -2
- package/dist_ts/ts_migration/legacysources/nativestores.js +15 -8
- package/dist_ts/ts_migration/legacysources/shared.d.ts +3 -2
- package/dist_ts/ts_migration/legacysources/shared.js +3 -5
- package/package.json +11 -7
- package/readme.md +188 -13
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/authority-contract.ts +125 -0
- package/ts/authority-import-contract.ts +12 -11
- package/ts/authority-paths.ts +69 -0
- package/ts/authority-runtime-contract.ts +11 -1
- package/ts/classes.authoritybroker.ts +70 -11
- package/ts/classes.authorityclient.ts +59 -21
- package/ts/classes.authoritydaemon.ts +116 -60
- package/ts/classes.authoritydatabase.ts +39 -12
- package/ts/classes.authorityimport.ts +131 -26
- package/ts/classes.authoritymodels.ts +11 -2
- package/ts/classes.authoritypreuse.ts +7 -1
- package/ts/classes.authorityservice.ts +42 -30
- package/ts/classes.claudeauthority.ts +22 -10
- package/ts/classes.claudenative.ts +104 -10
- package/ts/classes.cli.ts +14 -3
- package/ts/classes.codexmanaged.ts +18 -7
- package/ts/classes.legacyfence.ts +219 -0
- package/ts/classes.operations.ts +22 -3
- package/ts/classes.service.ts +45 -8
- package/ts/classes.tui.ts +3 -1
- package/ts/ts_migration/0003_claude_handoff_proof.ts +19 -0
- package/ts/ts_migration/index.ts +2 -0
- package/ts/ts_migration/legacysources/authswitchstores.ts +4 -1
- package/ts/ts_migration/legacysources/nativestores.ts +15 -7
- package/ts/ts_migration/legacysources/shared.ts +4 -6
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as plugins from './plugins.js';
|
|
2
|
+
import type { TAuthSwitchClaudeProofFailure } from './authority-contract.js';
|
|
2
3
|
import { ClaudeCodeLockOutcomeUnknownError, ClaudeCodeLocks,
|
|
3
4
|
type IClaudeCodeLockLease } from './classes.claudecodelocks.js';
|
|
4
5
|
import { claudeRequest } from './claudehttp.js';
|
|
@@ -34,9 +35,10 @@ const CREDENTIAL_OVERRIDES = [
|
|
|
34
35
|
export class ClaudeNativeEffectiveAuthUnsupportedError extends Error {
|
|
35
36
|
public readonly code = 'unsupported_effective_auth';
|
|
36
37
|
|
|
37
|
-
constructor(public readonly reason:
|
|
38
|
-
|
|
39
|
-
|
|
38
|
+
constructor(public readonly reason: TAuthSwitchClaudeProofFailure) {
|
|
39
|
+
super(reason === 'unsupported_release'
|
|
40
|
+
? `Native Claude handoff requires Claude Code ${CLAUDE_NATIVE_HANDOFF_VERSION} for every active session.`
|
|
41
|
+
: `Cannot prove that Claude Code ${CLAUDE_NATIVE_HANDOFF_VERSION} uses its native claude.ai login (${reason}).`);
|
|
40
42
|
}
|
|
41
43
|
}
|
|
42
44
|
|
|
@@ -142,7 +144,15 @@ export interface IClaudeNativeAdapterOptions {
|
|
|
142
144
|
executable?: string;
|
|
143
145
|
platform?: NodeJS.Platform;
|
|
144
146
|
env?: NodeJS.ProcessEnv;
|
|
145
|
-
|
|
147
|
+
/**
|
|
148
|
+
* The settings sources this proof reads, stated by the caller because only it knows which they are.
|
|
149
|
+
*
|
|
150
|
+
* There is no default: this adapter runs inside the daemon, whose working directory is the service
|
|
151
|
+
* unit's and never a Claude session's project, so a list derived from `process.cwd()` would prove a
|
|
152
|
+
* directory nobody selected. `claudeNativeUserSettingsFiles` is the daemon's list; the settings a
|
|
153
|
+
* running session selected are proven from that session's own working directory instead.
|
|
154
|
+
*/
|
|
155
|
+
settingsFiles: readonly string[];
|
|
146
156
|
/** Internal test seam; production uses Claude's Linux managed-settings directory. */
|
|
147
157
|
managedSettingsDirectory?: string;
|
|
148
158
|
fetch?: typeof fetch;
|
|
@@ -166,6 +176,87 @@ const preparedWrites = new WeakMap<IClaudeNativePreparedWrite, {
|
|
|
166
176
|
const sameIdentity = (left: IClaudeNativeIdentity, right: IClaudeNativeIdentity): boolean =>
|
|
167
177
|
left.accountUuid === right.accountUuid && left.organizationUuid === right.organizationUuid;
|
|
168
178
|
|
|
179
|
+
/** Claude Code's own paths on this host, and the authority's id for that one native home. */
|
|
180
|
+
export interface IClaudeNativeHome {
|
|
181
|
+
configDir: string;
|
|
182
|
+
configFile: string;
|
|
183
|
+
credentialFile: string;
|
|
184
|
+
homeId: string;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* A home this host cannot have: the location it was pointed at, and why it is not usable.
|
|
189
|
+
*
|
|
190
|
+
* The inventory reports such a source with its defect rather than skipping it or reading a guessed
|
|
191
|
+
* location, so `declaredCredentialFile` names what the environment asked for, unresolved.
|
|
192
|
+
*/
|
|
193
|
+
export interface IClaudeNativeHomeDefect {
|
|
194
|
+
declaredCredentialFile: string;
|
|
195
|
+
problem: string;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export type TClaudeNativeHomeResolution =
|
|
199
|
+
| { kind: 'resolved'; home: IClaudeNativeHome }
|
|
200
|
+
| { kind: 'unusable'; defect: IClaudeNativeHomeDefect };
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* The authority's id for one native Claude home: the hash of the credential file Claude Code owns.
|
|
204
|
+
*
|
|
205
|
+
* The import ledger publishes the same value as a source's `sourcePathHash`, and
|
|
206
|
+
* `registerClaudeHomeFromReceipt` adopts a home only when the two are equal, so both sides must derive it
|
|
207
|
+
* here and nowhere else.
|
|
208
|
+
*/
|
|
209
|
+
export const claudeNativeHomeId = (credentialFile: string): string => hash(credentialFile);
|
|
210
|
+
|
|
211
|
+
/** An absolute, normalized directory without a trailing separator, or null for anything else. */
|
|
212
|
+
const canonicalDirectory = (value: string): string | null => {
|
|
213
|
+
if (!plugins.path.isAbsolute(value)) return null;
|
|
214
|
+
const normalized = plugins.path.normalize(value);
|
|
215
|
+
return normalized.length > 1 && normalized.endsWith(plugins.path.sep)
|
|
216
|
+
? normalized.slice(0, -1) : normalized;
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Where Claude Code keeps this user's login, resolved once for the daemon and the import inventory alike.
|
|
221
|
+
*
|
|
222
|
+
* `CLAUDE_CONFIG_DIR` selects the home; Claude Code keeps its account metadata beside the home directory
|
|
223
|
+
* unless that variable moves it. A relative directory is never resolved against the current working
|
|
224
|
+
* directory: a daemon and a CLI run from different places, so guessing would make them disagree about
|
|
225
|
+
* which file is the login.
|
|
226
|
+
*/
|
|
227
|
+
export const resolveClaudeNativeHome = (env: NodeJS.ProcessEnv,
|
|
228
|
+
homeDirectory: string): TClaudeNativeHomeResolution => {
|
|
229
|
+
const declared = env.CLAUDE_CONFIG_DIR ? canonicalDirectory(env.CLAUDE_CONFIG_DIR) : null;
|
|
230
|
+
if (env.CLAUDE_CONFIG_DIR && declared === null) {
|
|
231
|
+
return { kind: 'unusable', defect: {
|
|
232
|
+
declaredCredentialFile: plugins.path.join(env.CLAUDE_CONFIG_DIR, '.credentials.json'),
|
|
233
|
+
problem: 'CLAUDE_CONFIG_DIR is not an absolute path, so Claude Code\'s own login cannot be located' } };
|
|
234
|
+
}
|
|
235
|
+
const home = canonicalDirectory(homeDirectory);
|
|
236
|
+
if (home === null) {
|
|
237
|
+
return { kind: 'unusable', defect: {
|
|
238
|
+
declaredCredentialFile: plugins.path.join(homeDirectory, '.claude', '.credentials.json'),
|
|
239
|
+
problem: 'the home directory is not an absolute path, so Claude Code\'s own login cannot be located' } };
|
|
240
|
+
}
|
|
241
|
+
const configDir = declared ?? plugins.path.join(home, '.claude');
|
|
242
|
+
const credentialFile = plugins.path.join(configDir, '.credentials.json');
|
|
243
|
+
return { kind: 'resolved', home: { configDir,
|
|
244
|
+
configFile: plugins.path.join(declared ?? home, '.claude.json'),
|
|
245
|
+
credentialFile, homeId: claudeNativeHomeId(credentialFile) } };
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* The settings sources Claude Code reads at user scope for one resolved home.
|
|
250
|
+
*
|
|
251
|
+
* This is what a host-wide owner -- the daemon -- may prove: the user settings file beside the credential
|
|
252
|
+
* file the home owns. Claude Code's other two scopes are proven where they are selected: the managed
|
|
253
|
+
* settings directory is checked on its own, and a project's `.claude/settings.json` and
|
|
254
|
+
* `.claude/settings.local.json` belong to the working directory of a running session, which is read from
|
|
255
|
+
* that session rather than from this process.
|
|
256
|
+
*/
|
|
257
|
+
export const claudeNativeUserSettingsFiles = (configDir: string): readonly string[] =>
|
|
258
|
+
[plugins.path.join(configDir, 'settings.json')];
|
|
259
|
+
|
|
169
260
|
const pathEnvironment = ['HOME', 'XDG_CONFIG_HOME', 'ANTHROPIC_CONFIG_DIR', 'CLAUDE_CONFIG_DIR'] as const;
|
|
170
261
|
const contextKeys = new Set<string>([...CREDENTIAL_OVERRIDES, ...pathEnvironment]);
|
|
171
262
|
const readProcessContext = (file: string): string => {
|
|
@@ -486,8 +577,13 @@ export class ClaudeNativeAdapter {
|
|
|
486
577
|
|| plugins.path.normalize(options.configFile) !== options.configFile) {
|
|
487
578
|
throw new Error('Native Claude paths must be normalized absolute paths.');
|
|
488
579
|
}
|
|
580
|
+
// Claude Code keeps its account metadata inside a configured home and beside an unconfigured one.
|
|
581
|
+
// Which home that is follows from the environment this adapter was given, the same environment
|
|
582
|
+
// `assertSupported` re-checks before every operation, never from the running process's own account.
|
|
583
|
+
const configParent = selectedNativeConfigParent(options.env ?? process.env);
|
|
489
584
|
if (![plugins.path.join(options.configDir, '.claude.json'),
|
|
490
|
-
plugins.path.join(
|
|
585
|
+
...(configParent === null ? [] : [plugins.path.join(configParent, '.claude.json')]),
|
|
586
|
+
].includes(options.configFile)) {
|
|
491
587
|
throw new Error('Native Claude account metadata must use its vendor config file.');
|
|
492
588
|
}
|
|
493
589
|
this.credentialFile = plugins.path.join(options.configDir, '.credentials.json');
|
|
@@ -497,9 +593,7 @@ export class ClaudeNativeAdapter {
|
|
|
497
593
|
options.executable ?? 'claude');
|
|
498
594
|
this.fetcher = options.fetch ?? globalThis.fetch;
|
|
499
595
|
this.env = options.env ?? process.env;
|
|
500
|
-
this.settingsFiles = options.settingsFiles
|
|
501
|
-
plugins.path.join(process.cwd(), '.claude/settings.json'),
|
|
502
|
-
plugins.path.join(process.cwd(), '.claude/settings.local.json')];
|
|
596
|
+
this.settingsFiles = options.settingsFiles;
|
|
503
597
|
this.platform = options.platform ?? process.platform;
|
|
504
598
|
}
|
|
505
599
|
|
|
@@ -528,7 +622,7 @@ export class ClaudeNativeAdapter {
|
|
|
528
622
|
assertSettingsSelectNative(file);
|
|
529
623
|
}
|
|
530
624
|
if (this.versionProbe.installedVersion() !== CLAUDE_NATIVE_HANDOFF_VERSION) {
|
|
531
|
-
throw new
|
|
625
|
+
throw new ClaudeNativeEffectiveAuthUnsupportedError('unsupported_release');
|
|
532
626
|
}
|
|
533
627
|
let runningSessions = 0;
|
|
534
628
|
const nativeHomeIdentity = directoryIdentity(this.options.configDir);
|
|
@@ -543,7 +637,7 @@ export class ClaudeNativeAdapter {
|
|
|
543
637
|
throw new ClaudeNativeEffectiveAuthUnsupportedError('running_session');
|
|
544
638
|
}
|
|
545
639
|
if (running.version !== CLAUDE_NATIVE_HANDOFF_VERSION) {
|
|
546
|
-
throw new
|
|
640
|
+
throw new ClaudeNativeEffectiveAuthUnsupportedError('unsupported_release');
|
|
547
641
|
}
|
|
548
642
|
if (!running.env || !running.cwd || running.hasSettingsOverride === null
|
|
549
643
|
|| !running.mountNamespace || !running.processRoot) {
|
package/ts/classes.cli.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { CodexHarness } from './classes.codexharness.js';
|
|
|
4
4
|
import { OpenCodeHarness } from './classes.opencodeharness.js';
|
|
5
5
|
import { ClaudeCodeHarness } from './classes.claudecodeharness.js';
|
|
6
6
|
import { AuthSwitchTui } from './classes.tui.js';
|
|
7
|
-
import { AglAuthSwitchCoordinator, AuthSwitchOperations, authSwitchMutationReplacesLogin, type TAuthSwitchCoordinator, type TAuthSwitchMutation } from './classes.operations.js';
|
|
7
|
+
import { AglAuthSwitchCoordinator, AuthSwitchOperations, authSwitchHostLegacyFence, authSwitchMutationReplacesLogin, type TAuthSwitchCoordinator, type TAuthSwitchLegacyFence, type TAuthSwitchMutation } from './classes.operations.js';
|
|
8
8
|
import { readAccountList } from './classes.accountlist.js';
|
|
9
9
|
import { AccountListRenderer } from './classes.listrenderer.js';
|
|
10
10
|
import { accountLimits, activeAccounts, CondensedRenderer } from './classes.limits.js';
|
|
@@ -98,9 +98,20 @@ export class AuthSwitchCli {
|
|
|
98
98
|
private readonly operations: AuthSwitchOperations;
|
|
99
99
|
private get out(): plugins.smartconsole.SmartConsole { return this.console ??= new plugins.smartconsole.SmartConsole(); }
|
|
100
100
|
|
|
101
|
-
|
|
101
|
+
/**
|
|
102
|
+
* `legacyFenceArg` states which authority fences the mutations of injected harnesses.
|
|
103
|
+
*
|
|
104
|
+
* With no harnesses this command line is this host's, exactly as its default harnesses and its AGL
|
|
105
|
+
* coordinator are, and it is fenced by this host's authority. Injected harnesses write whatever stores
|
|
106
|
+
* their caller chose, so -- like the coordinator -- nothing of this host is assumed for them: they are
|
|
107
|
+
* fenced only by what the caller states, and by nothing when it states nothing.
|
|
108
|
+
*/
|
|
109
|
+
constructor(harnessesArg?: IAuthHarness[] | CodexSwitcher, coordinatorArg?: TAuthSwitchCoordinator,
|
|
110
|
+
legacyFenceArg?: TAuthSwitchLegacyFence) {
|
|
102
111
|
const coordinator = new AglAuthSwitchCoordinator();
|
|
103
|
-
this.operations = new AuthSwitchOperations(
|
|
112
|
+
this.operations = new AuthSwitchOperations(
|
|
113
|
+
coordinatorArg ?? (harnessesArg === undefined ? request => coordinator.coordinate(request) : undefined),
|
|
114
|
+
legacyFenceArg ?? (harnessesArg === undefined ? authSwitchHostLegacyFence() : 'none'));
|
|
104
115
|
harnessesArg ??= [new CodexHarness(), new OpenCodeHarness(), new ClaudeCodeHarness()];
|
|
105
116
|
// Preserve the published single-Codex constructor at the composition boundary.
|
|
106
117
|
const harnesses = Array.isArray(harnessesArg) ? harnessesArg : [new CodexHarness(harnessesArg)];
|
|
@@ -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 !==
|
|
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
|
-
|
|
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
|
-
|
|
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
|
+
};
|
package/ts/classes.operations.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
|
package/ts/classes.service.ts
CHANGED
|
@@ -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
|
-
|
|
71
|
-
|
|
72
|
-
|
|
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
|
-
|
|
115
|
-
|
|
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
|
-
|
|
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];
|