@stateplane/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # @stateplane/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Stateplane command line. Stateplane is 21n's shared state service for all your agents: a generic owned-state
4
+ service with a versioned v1 logical contract, built in [21nCo/stateplane](https://github.com/21nCo/stateplane).
5
+
6
+ The `stateplane` command talks to a Stateplane HTTP v1 host and covers `config`, `auth`, `spaces`, `collections`,
7
+ `records`, `batches`, `events`, `sources`, `uploads`, `claims`, `links`, `retrieval` and `analysis`. It prints one
8
+ JSON value on success and one JSON error on stderr on failure, and never prints a token. Tokens are kept in the OS
9
+ keychain (Linux) or a private file.
10
+
11
+ ```sh
12
+ npx stateplane help # through the stateplane package, which runs this one
13
+ npm install --global @stateplane/cli
14
+ stateplane config endpoint --url https://stateplane.example.invalid/
15
+ ```
16
+
17
+ The package root also exports `runCli` and `StateplaneHttpClient` for scripts. It has no runtime dependencies.
18
+ Requires Node.js 22.13 or newer. Docs: [HTTP and CLI v1](https://github.com/21nCo/stateplane/blob/main/docs/http-cli.md).
19
+
20
+ ## Versions
21
+
22
+ 0.1.1 is the first release on npm: the release build of 0.1.0 failed in CI and was never published.
@@ -0,0 +1,19 @@
1
+ import Foundation
2
+ import Security
3
+
4
+ // Tokens cross this process boundary only on stdin/stdout, never in argv.
5
+ guard CommandLine.arguments.count == 3 else { exit(1) }
6
+ let operation = CommandLine.arguments[1]
7
+ let service = CommandLine.arguments[2]
8
+ let query: [String: Any] = [
9
+ kSecClass as String: kSecClassGenericPassword,
10
+ kSecAttrAccount as String: "default",
11
+ kSecAttrService as String: service
12
+ ]
13
+
14
+ // This helper only deletes legacy items. A Swift interpreter has no caller
15
+ // identity that can safely restrict credential reads to Stateplane.
16
+ if operation == "remove" {
17
+ let status = SecItemDelete(query as CFDictionary)
18
+ guard status == errSecSuccess || status == errSecItemNotFound else { exit(1) }
19
+ } else { exit(1) }
@@ -0,0 +1,69 @@
1
+ param(
2
+ [Parameter(Mandatory=$true)][string]$TargetPath,
3
+ [ValidateSet('harden','verify','diagnose')][string]$Action='verify'
4
+ )
5
+ $ErrorActionPreference='Stop'
6
+ $identity=[System.Security.Principal.WindowsIdentity]::GetCurrent().User
7
+ $allowed=@($identity.Value,'S-1-5-18','S-1-5-32-544')
8
+ function ReadAcl($path) {
9
+ # FileInfo/DirectoryInfo use the framework ACL API directly. The packaged
10
+ # CLI must not depend on PowerShell module autoload in a fresh user profile.
11
+ if ([System.IO.Directory]::Exists($path)) {
12
+ return ([System.IO.DirectoryInfo]::new($path)).GetAccessControl()
13
+ }
14
+ if ([System.IO.File]::Exists($path)) {
15
+ return ([System.IO.FileInfo]::new($path)).GetAccessControl()
16
+ }
17
+ exit 14
18
+ }
19
+ $acl=ReadAcl $TargetPath
20
+ function RulesBySid($security) {
21
+ # Get-Acl.Access can hold NTAccount names that no longer translate on a
22
+ # runner. Asking the ACL for SIDs also makes the allowlist comparison exact.
23
+ return @($security.GetAccessRules($true,$false,[System.Security.Principal.SecurityIdentifier]))
24
+ }
25
+ if ($Action -eq 'diagnose') {
26
+ $owner=$acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value
27
+ $rules=@(RulesBySid $acl | ForEach-Object {
28
+ $sid=$_.IdentityReference.Value
29
+ "$sid/$($_.AccessControlType)/$($_.IsInherited)"
30
+ }) -join ','
31
+ Write-Output "pid=$PID caller=$($identity.Value) owner=$owner protected=$($acl.AreAccessRulesProtected) rules=$rules"
32
+ exit 0
33
+ }
34
+ if ($Action -eq 'harden') {
35
+ # Set-Acl writes the owner as well as the DACL. A Windows runner may create
36
+ # a file owned by Administrators while the CLI runs as its member, in which
37
+ # case that owner write fails despite the caller being allowed to edit DACLs.
38
+ $icacls=Join-Path $env:SystemRoot 'System32\icacls.exe'
39
+ if (-not [System.IO.File]::Exists($icacls)) { exit 10 }
40
+ $suffix=if ([System.IO.Directory]::Exists($TargetPath)) { ':(OI)(CI)F' } else { ':F' }
41
+ # Grant our own SID before removing inherited rules. The system accounts
42
+ # retain access for backup and machine administration.
43
+ foreach ($sid in $allowed) {
44
+ & $icacls $TargetPath '/grant:r' "*$sid$suffix" | Out-Null
45
+ if ($LASTEXITCODE -ne 0) { exit 11 }
46
+ }
47
+ & $icacls $TargetPath '/inheritance:r' | Out-Null
48
+ if ($LASTEXITCODE -ne 0) { exit 12 }
49
+ $acl=ReadAcl $TargetPath
50
+ foreach ($rule in @(RulesBySid $acl)) {
51
+ $sid=$rule.IdentityReference.Value
52
+ if ($allowed -contains $sid) { continue }
53
+ & $icacls $TargetPath '/remove' "*$sid" | Out-Null
54
+ if ($LASTEXITCODE -ne 0) { exit 13 }
55
+ }
56
+ $acl=ReadAcl $TargetPath
57
+ }
58
+ if (-not $acl.AreAccessRulesProtected) { exit 1 }
59
+ $owner=$null
60
+ try { $owner=$acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value }
61
+ catch { exit 2 }
62
+ if ($allowed -notcontains $owner) { exit 2 }
63
+ $hasUser=$false
64
+ foreach ($rule in @(RulesBySid $acl)) {
65
+ $sid=$rule.IdentityReference.Value
66
+ if ($allowed -notcontains $sid -or $rule.AccessControlType -ne 'Allow') { exit 1 }
67
+ if ($sid -eq $identity.Value) { $hasUser=$true }
68
+ }
69
+ if (-not $hasUser) { exit 1 }
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import process from 'node:process';
3
+ import { runCli } from '../dist/index.js';
4
+ process.exitCode = await runCli(process.argv.slice(2));
@@ -0,0 +1,41 @@
1
+ type TokenStore = 'keychain' | 'file';
2
+ export interface CliConfig {
3
+ endpoint?: string;
4
+ space?: string;
5
+ tokenStore?: TokenStore;
6
+ tokenLocations?: TokenStore[];
7
+ }
8
+ export declare function configDir(): string;
9
+ export declare function withConfigMutation<T>(change: (current: CliConfig) => Promise<T>): Promise<T>;
10
+ export declare function readConfig(): Promise<CliConfig>;
11
+ export declare function saveConfig(value: CliConfig): Promise<void>;
12
+ interface CommandResult {
13
+ ok: boolean;
14
+ output: string;
15
+ missing?: boolean;
16
+ }
17
+ declare function command(program: string, args: string[], stdin?: string): Promise<CommandResult>;
18
+ export declare function loadSecretServiceToken(endpoint: string, run?: typeof command): Promise<string>;
19
+ export declare function loadOsSecretToken(endpoint: string, os?: NodeJS.Platform, run?: typeof command): Promise<string>;
20
+ export declare function storeSecretServiceToken(endpoint: string, token: string, run?: typeof command): Promise<void>;
21
+ /** secret-tool clear exits 1 when there was no item to remove. Confirm that
22
+ * absence with a lookup before treating it as successful cleanup. */
23
+ export declare function removeSecretServiceToken(endpoint: string, run?: typeof command): Promise<void>;
24
+ export declare function saveToken(endpoint: string, token: string, store: 'keychain' | 'file'): Promise<void>;
25
+ export declare function loadToken(config: CliConfig): Promise<string>;
26
+ export declare function removeToken(config: CliConfig): Promise<void>;
27
+ type TokenPersistence = {
28
+ saveConfig: typeof saveConfig;
29
+ saveToken: typeof saveToken;
30
+ removeToken: typeof removeToken;
31
+ };
32
+ /** Keep both possible locations discoverable until the old secret is gone.
33
+ * Each persisted step can be retried or cleaned up after process interruption. */
34
+ export declare function configureToken(config: CliConfig, token: string, store: 'keychain' | 'file', io?: TokenPersistence): Promise<void>;
35
+ /** Logout and endpoint changes also clean a transition interrupted at any step. */
36
+ export declare function removeTrackedTokens(config: CliConfig, io?: Pick<TokenPersistence, 'removeToken'>): Promise<void>;
37
+ export declare function logoutConfig(config: CliConfig, io?: {
38
+ removeTrackedTokens: typeof removeTrackedTokens;
39
+ saveConfig: typeof saveConfig;
40
+ }): Promise<void>;
41
+ export {};
package/dist/config.js ADDED
@@ -0,0 +1,330 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { mkdir, readFile, rename, rm, lstat, writeFile, open } from 'node:fs/promises';
3
+ import { homedir, platform } from 'node:os';
4
+ import { dirname, join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { StateplaneCliError } from './transport.js';
7
+ export function configDir() {
8
+ return process.env.STATEPLANE_CONFIG_DIR || join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'stateplane');
9
+ }
10
+ const windowsAclScript = join(dirname(fileURLToPath(import.meta.url)), '../bin/secure-acl.ps1');
11
+ /** fs.Stats.mode does not expose Windows ACLs. Keep only the current user,
12
+ * SYSTEM and Administrators on configuration and file-secret paths. */
13
+ async function windowsAcl(path, action) {
14
+ const powershell = join(process.env.SystemRoot ?? String.raw `C:\Windows`, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
15
+ const result = await command(powershell, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
16
+ '-File', windowsAclScript, '-TargetPath', path, '-Action', action]);
17
+ if (!result.ok)
18
+ throw new StateplaneCliError('INSECURE_CONFIGURATION');
19
+ }
20
+ async function secureDirectory() {
21
+ await mkdir(configDir(), { recursive: true, mode: 0o700 });
22
+ const stat = await lstat(configDir());
23
+ if (!stat.isDirectory())
24
+ throw new StateplaneCliError('INSECURE_CONFIGURATION');
25
+ if (platform() === 'win32')
26
+ await windowsAcl(configDir(), 'harden');
27
+ else if ((stat.mode & 0o077) !== 0)
28
+ throw new StateplaneCliError('INSECURE_CONFIGURATION');
29
+ }
30
+ const configPath = () => join(configDir(), 'config.json');
31
+ const tokenPath = () => join(configDir(), 'token');
32
+ /** Serialize config and secret-location changes across CLI processes. The
33
+ * durable journal remains the recovery source if a process exits mid-switch. */
34
+ let mutationTail = Promise.resolve();
35
+ let sqliteModule;
36
+ function sqlite() {
37
+ if (!sqliteModule) {
38
+ const emitWarning = process.emitWarning;
39
+ // Node 22 emits this warning while importing its built-in SQLite module.
40
+ // Keep all other diagnostics, including credential-store failures, intact.
41
+ process.emitWarning = function (warning, ...args) {
42
+ if (String(warning) === 'SQLite is an experimental feature and might change at any time')
43
+ return;
44
+ return Reflect.apply(emitWarning, process, [warning, ...args]);
45
+ };
46
+ sqliteModule = import('node:sqlite').finally(() => { process.emitWarning = emitWarning; });
47
+ }
48
+ return sqliteModule;
49
+ }
50
+ export async function withConfigMutation(change) {
51
+ // SQLite owns the cross-process lock. Its transaction is released by the OS
52
+ // on process death, so no contender ever unlinks another contender's lock.
53
+ // Queue this process too: DatabaseSync's busy wait would otherwise block a
54
+ // callback holding the lock in the same event loop.
55
+ const previous = mutationTail;
56
+ let release;
57
+ mutationTail = new Promise(resolve => { release = resolve; });
58
+ await previous;
59
+ let database;
60
+ try {
61
+ await secureDirectory();
62
+ const path = join(configDir(), 'config.lock.sqlite');
63
+ try {
64
+ const file = await open(path, 'wx', 0o600);
65
+ await file.close();
66
+ }
67
+ catch (error) {
68
+ if (error.code !== 'EEXIST')
69
+ throw error;
70
+ }
71
+ if (platform() === 'win32')
72
+ await windowsAcl(path, 'harden');
73
+ await privateFile(path);
74
+ const { DatabaseSync } = await sqlite();
75
+ database = new DatabaseSync(path);
76
+ // PRAGMA works on the earliest supported Node 22.13 runtime; the
77
+ // DatabaseSync constructor's timeout option arrived in Node 22.16.
78
+ database.exec('PRAGMA busy_timeout = 120000');
79
+ try {
80
+ database.exec('BEGIN IMMEDIATE');
81
+ }
82
+ catch (error) {
83
+ if (String(error).includes('database is locked'))
84
+ throw new StateplaneCliError('CONFIGURATION_BUSY', undefined, undefined, true);
85
+ throw error;
86
+ }
87
+ try {
88
+ const result = await change(await readConfig());
89
+ database.exec('COMMIT');
90
+ return result;
91
+ }
92
+ catch (error) {
93
+ database.exec('ROLLBACK');
94
+ throw error;
95
+ }
96
+ }
97
+ finally {
98
+ database?.close();
99
+ release();
100
+ }
101
+ }
102
+ async function privateFile(path) {
103
+ try {
104
+ const stat = await lstat(path);
105
+ if (!stat.isFile())
106
+ throw new StateplaneCliError('INSECURE_CONFIGURATION');
107
+ if (platform() === 'win32')
108
+ await windowsAcl(path, 'verify');
109
+ else if ((stat.mode & 0o077) !== 0)
110
+ throw new StateplaneCliError('INSECURE_CONFIGURATION');
111
+ return true;
112
+ }
113
+ catch (error) {
114
+ if (error.code === 'ENOENT')
115
+ return false;
116
+ throw error;
117
+ }
118
+ }
119
+ export async function readConfig() {
120
+ try {
121
+ await lstat(configDir());
122
+ await secureDirectory();
123
+ }
124
+ catch (error) {
125
+ if (error.code !== 'ENOENT')
126
+ throw error;
127
+ }
128
+ if (!await privateFile(configPath()))
129
+ return {};
130
+ try {
131
+ const value = JSON.parse(await readFile(configPath(), 'utf8'));
132
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
133
+ Object.keys(value).some(key => !['endpoint', 'space', 'tokenStore', 'tokenLocations'].includes(key)) ||
134
+ (value.endpoint !== undefined && typeof value.endpoint !== 'string') ||
135
+ (value.space !== undefined && typeof value.space !== 'string') ||
136
+ (value.tokenStore !== undefined && !['file', 'keychain'].includes(value.tokenStore)) ||
137
+ (value.tokenLocations !== undefined && (!value.endpoint || !Array.isArray(value.tokenLocations) ||
138
+ value.tokenLocations.length < 1 || value.tokenLocations.length > 2 ||
139
+ new Set(value.tokenLocations).size !== value.tokenLocations.length ||
140
+ value.tokenLocations.some(store => store !== 'file' && store !== 'keychain') ||
141
+ (value.tokenStore !== undefined && !value.tokenLocations.includes(value.tokenStore)))))
142
+ throw new Error('invalid');
143
+ return value;
144
+ }
145
+ catch {
146
+ throw new StateplaneCliError('INVALID_CONFIGURATION');
147
+ }
148
+ }
149
+ export async function saveConfig(value) {
150
+ await secureDirectory();
151
+ const temp = join(configDir(), `.config-${process.pid}-${crypto.randomUUID()}`);
152
+ try {
153
+ await writeFile(temp, JSON.stringify(value) + '\n', { mode: 0o600, flag: 'wx' });
154
+ if (platform() === 'win32')
155
+ await windowsAcl(temp, 'harden');
156
+ await rename(temp, configPath());
157
+ }
158
+ finally {
159
+ await rm(temp, { force: true });
160
+ }
161
+ }
162
+ function keyArgs(endpoint) { return ['service', 'stateplane', 'endpoint', endpoint]; }
163
+ const macKeychainScript = join(dirname(fileURLToPath(import.meta.url)), '../bin/keychain.swift');
164
+ function macKeychain(operation, endpoint, stdin, run = command) {
165
+ // xcrun selects a matching Swift toolchain and SDK. Direct /usr/bin/swift
166
+ // can bind to an older CLT compiler with a newer active Xcode SDK.
167
+ return run('/usr/bin/xcrun', ['--sdk', 'macosx', 'swift', macKeychainScript, operation, `stateplane:${endpoint}`], stdin);
168
+ }
169
+ function command(program, args, stdin) {
170
+ return new Promise(resolve => {
171
+ const child = spawn(program, args, { stdio: ['pipe', 'pipe', 'pipe'] });
172
+ const timer = setTimeout(() => child.kill(), 30_000);
173
+ let output = '';
174
+ let diagnostic = false;
175
+ child.stdout.setEncoding('utf8');
176
+ child.stdout.on('data', chunk => { if (output.length < 16_384)
177
+ output += chunk; });
178
+ child.stderr.on('data', () => { diagnostic = true; });
179
+ child.stdin.on('error', () => { });
180
+ child.on('error', () => { clearTimeout(timer); resolve({ ok: false, output: '' }); });
181
+ child.on('close', code => {
182
+ clearTimeout(timer);
183
+ resolve({ ok: code === 0, output,
184
+ missing: program === '/usr/bin/xcrun' ? code === 2 : program === 'secret-tool' && code === 1 && !diagnostic });
185
+ });
186
+ child.stdin.end(stdin);
187
+ });
188
+ }
189
+ export async function loadSecretServiceToken(endpoint, run = command) {
190
+ // An absent Secret Service item exits 1 without diagnostics. Backend
191
+ // failures produce diagnostics, which are observed but never printed.
192
+ const result = await run('secret-tool', ['lookup', ...keyArgs(endpoint)]);
193
+ if (!result.ok)
194
+ throw new StateplaneCliError(result.missing ? 'UNAUTHENTICATED' : 'KEYCHAIN_UNAVAILABLE');
195
+ const token = result.output.replace(/\n$/, '');
196
+ if (!token)
197
+ throw new StateplaneCliError('UNAUTHENTICATED');
198
+ return token;
199
+ }
200
+ export async function loadOsSecretToken(endpoint, os = platform(), run = command) {
201
+ if (os === 'linux')
202
+ return loadSecretServiceToken(endpoint, run);
203
+ // Interpreted Swift callers cannot provide a verifiable application identity.
204
+ // The legacy login Keychain allowed another same-account process to decrypt
205
+ // with interaction disabled. Retain only removal for existing stored items.
206
+ throw new StateplaneCliError('KEYCHAIN_UNAVAILABLE');
207
+ }
208
+ export async function storeSecretServiceToken(endpoint, token, run = command) {
209
+ const args = keyArgs(endpoint);
210
+ const stored = await run('secret-tool', ['store', '--label=Stateplane API key', ...args], token);
211
+ if (!stored.ok)
212
+ throw new StateplaneCliError('KEYCHAIN_UNAVAILABLE');
213
+ const checked = await run('secret-tool', ['lookup', ...args]);
214
+ if (!checked.ok || checked.output.replace(/\n$/, '') !== token) {
215
+ await run('secret-tool', ['clear', ...args]);
216
+ throw new StateplaneCliError('KEYCHAIN_UNAVAILABLE');
217
+ }
218
+ }
219
+ /** secret-tool clear exits 1 when there was no item to remove. Confirm that
220
+ * absence with a lookup before treating it as successful cleanup. */
221
+ export async function removeSecretServiceToken(endpoint, run = command) {
222
+ const args = keyArgs(endpoint);
223
+ const cleared = await run('secret-tool', ['clear', ...args]);
224
+ if (cleared.ok)
225
+ return;
226
+ if (!cleared.missing)
227
+ throw new StateplaneCliError('KEYCHAIN_UNAVAILABLE');
228
+ const remaining = await run('secret-tool', ['lookup', ...args]);
229
+ if (!remaining.missing)
230
+ throw new StateplaneCliError('KEYCHAIN_UNAVAILABLE');
231
+ }
232
+ export async function saveToken(endpoint, token, store) {
233
+ if (!token || /[\r\n\0]/.test(token))
234
+ throw new StateplaneCliError('INVALID_ARGUMENT');
235
+ if (store === 'file') {
236
+ await secureDirectory();
237
+ const temp = join(configDir(), `.token-${process.pid}-${crypto.randomUUID()}`);
238
+ try {
239
+ await writeFile(temp, token, { mode: 0o600, flag: 'wx' });
240
+ if (platform() === 'win32')
241
+ await windowsAcl(temp, 'harden');
242
+ await rename(temp, tokenPath());
243
+ }
244
+ finally {
245
+ await rm(temp, { force: true });
246
+ }
247
+ return;
248
+ }
249
+ if (platform() === 'linux')
250
+ return storeSecretServiceToken(endpoint, token);
251
+ throw new StateplaneCliError('KEYCHAIN_UNAVAILABLE');
252
+ }
253
+ export async function loadToken(config) {
254
+ if (process.env.STATEPLANE_TOKEN)
255
+ return process.env.STATEPLANE_TOKEN;
256
+ if (!config.endpoint)
257
+ throw new StateplaneCliError('INVALID_CONFIGURATION');
258
+ if (config.tokenStore === 'file') {
259
+ if (!await privateFile(tokenPath()))
260
+ throw new StateplaneCliError('UNAUTHENTICATED');
261
+ const token = await readFile(tokenPath(), 'utf8');
262
+ if (!token || /[\r\n\0]/.test(token))
263
+ throw new StateplaneCliError('INVALID_CONFIGURATION');
264
+ return token;
265
+ }
266
+ if (config.tokenStore === 'keychain') {
267
+ return loadOsSecretToken(config.endpoint);
268
+ }
269
+ throw new StateplaneCliError('UNAUTHENTICATED');
270
+ }
271
+ export async function removeToken(config) {
272
+ if (config.tokenStore === 'file')
273
+ await rm(tokenPath(), { force: true });
274
+ else if (config.tokenStore === 'keychain' && config.endpoint) {
275
+ let result;
276
+ if (platform() === 'darwin')
277
+ result = await macKeychain('remove', config.endpoint);
278
+ else if (platform() === 'linux')
279
+ return removeSecretServiceToken(config.endpoint);
280
+ else
281
+ result = { ok: false, output: '' };
282
+ if (!result.ok)
283
+ throw new StateplaneCliError('KEYCHAIN_UNAVAILABLE');
284
+ }
285
+ }
286
+ const persistence = { saveConfig, saveToken, removeToken };
287
+ /** Keep both possible locations discoverable until the old secret is gone.
288
+ * Each persisted step can be retried or cleaned up after process interruption. */
289
+ export async function configureToken(config, token, store, io = persistence) {
290
+ if (!config.endpoint)
291
+ throw new StateplaneCliError('INVALID_CONFIGURATION');
292
+ // Only Linux supports new OS-store tokens. Reject unsupported platforms before the durable
293
+ // journal records a cleanup obligation. Existing legacy locations below
294
+ // remain journaled and must still be removed during a switch or logout.
295
+ if (store === 'keychain' && platform() !== 'linux')
296
+ throw new StateplaneCliError('KEYCHAIN_UNAVAILABLE');
297
+ const locations = [...new Set([...(config.tokenLocations ?? []), ...(config.tokenStore ? [config.tokenStore] : []), store])];
298
+ await io.saveConfig({ ...config, tokenLocations: locations });
299
+ await io.saveToken(config.endpoint, token, store);
300
+ await io.saveConfig({ ...config, tokenStore: store, tokenLocations: locations });
301
+ for (const previous of locations)
302
+ if (previous !== store)
303
+ await io.removeToken({ ...config, tokenStore: previous }); // NOSONAR -- locations must settle serially before the journal clears
304
+ await io.saveConfig({ ...config, tokenStore: store, tokenLocations: undefined });
305
+ }
306
+ /** Logout and endpoint changes also clean a transition interrupted at any step. */
307
+ export async function removeTrackedTokens(config, io = persistence) {
308
+ const locations = new Set([...(config.tokenLocations ?? []), ...(config.tokenStore ? [config.tokenStore] : [])]);
309
+ let failure;
310
+ for (const store of locations) {
311
+ try {
312
+ await io.removeToken({ ...config, tokenStore: store });
313
+ } // NOSONAR -- preserve ordered cleanup and first failure
314
+ catch (error) {
315
+ failure ??= error;
316
+ }
317
+ }
318
+ // Leave the persisted location journal intact on any failure. A later
319
+ // logout or endpoint change can retry every location, including one whose
320
+ // removal already succeeded (both backends treat absence as success).
321
+ if (failure)
322
+ throw failure;
323
+ }
324
+ /** A completed logout clears the durable secret-location journal only after
325
+ * every tracked backend has confirmed removal. */
326
+ const logoutPersistence = { removeTrackedTokens, saveConfig };
327
+ export async function logoutConfig(config, io = logoutPersistence) {
328
+ await io.removeTrackedTokens(config);
329
+ await io.saveConfig({ ...config, tokenStore: undefined, tokenLocations: undefined });
330
+ }
@@ -0,0 +1,2 @@
1
+ export { StateplaneHttpClient, StateplaneCliError } from './transport.js';
2
+ export { runCli } from './run.js';