Skip to content

Commit dd9cc9f

Browse files
committed
cli: save credentials while preserving other fields
1 parent 85afea8 commit dd9cc9f

File tree

1 file changed

+23
-6
lines changed

1 file changed

+23
-6
lines changed

cli/src/utils/auth.ts

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -157,21 +157,31 @@ export interface AuthValidationResult {
157157
hasInvalidCredentials: boolean
158158
}
159159

160+
/** Read existing credentials file, returns empty object if missing/invalid */
161+
const readCredentialsFile = (): Record<string, unknown> => {
162+
const credentialsPath = getCredentialsPath()
163+
if (!fs.existsSync(credentialsPath)) return {}
164+
try {
165+
return JSON.parse(fs.readFileSync(credentialsPath, 'utf8'))
166+
} catch {
167+
return {}
168+
}
169+
}
170+
160171
/**
161-
* Save user credentials to file system
172+
* Save user credentials to file system.
162173
*/
163174
export const saveUserCredentials = (user: User): void => {
164175
const configDir = getConfigDir()
165176
const credentialsPath = getCredentialsPath()
166177

167178
try {
168-
// Ensure config directory exists
169179
if (!fs.existsSync(configDir)) {
170180
fs.mkdirSync(configDir, { recursive: true })
171181
}
172182

173-
// Save credentials
174-
fs.writeFileSync(credentialsPath, JSON.stringify({ default: user }))
183+
const updatedData = { ...readCredentialsFile(), default: user }
184+
fs.writeFileSync(credentialsPath, JSON.stringify(updatedData, null, 2))
175185
} catch (error) {
176186
logger.error(
177187
{
@@ -184,14 +194,21 @@ export const saveUserCredentials = (user: User): void => {
184194
}
185195

186196
/**
187-
* Clear user credentials from file system
197+
* Clear user credentials from file system.
198+
* Only removes the 'default' field, preserving other credentials.
188199
*/
189200
export const clearUserCredentials = (): void => {
190201
const credentialsPath = getCredentialsPath()
191202

192203
try {
193-
if (fs.existsSync(credentialsPath)) {
204+
if (!fs.existsSync(credentialsPath)) return
205+
206+
const { default: _, ...rest } = readCredentialsFile()
207+
208+
if (Object.keys(rest).length === 0) {
194209
fs.unlinkSync(credentialsPath)
210+
} else {
211+
fs.writeFileSync(credentialsPath, JSON.stringify(rest, null, 2))
195212
}
196213
} catch (error) {
197214
logger.error(

0 commit comments

Comments
 (0)