Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement credential deletion on 401 responses #338

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion src/commands/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { existsSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs';
import { join } from 'node:path';
import { createHash } from 'node:crypto';
import { TokenSet } from 'openid-client';
Expand Down Expand Up @@ -227,4 +227,24 @@ export const ensureAuth = async (
});
};

/**
* Deletes the credentials file at the specified path
* @param configDir Directory where credentials file is stored
*/
export const deleteCredentials = (configDir: string): void => {
const credentialsPath = join(configDir, CREDENTIALS_FILE);
try {
if (existsSync(credentialsPath)) {
unlinkSync(credentialsPath);
log.info('Deleted credentials from %s', credentialsPath);
} else {
log.debug('Credentials file %s does not exist', credentialsPath);
}
} catch (err) {
const typedErr = err instanceof Error ? err : new Error('Unknown error');
log.error('Failed to delete credentials: %s', typedErr.message);
throw new Error('CREDENTIALS_DELETE_FAILED');
}
};

const md5hash = (s: string) => createHash('md5').update(s).digest('hex');
12 changes: 10 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ axiosDebug({
});
import { Api } from '@neondatabase/api-client';

import { ensureAuth } from './commands/auth.js';
import { ensureAuth, deleteCredentials } from './commands/auth.js';
import { defaultDir, ensureConfigDir } from './config.js';
import { log } from './log.js';
import { defaultClientID } from './auth.js';
Expand Down Expand Up @@ -171,8 +171,16 @@ builder = builder
log.error('Request timed out');
sendError(err, 'REQUEST_TIMEOUT');
} else if (err.response?.status === 401) {
sendError(err, 'AUTH_FAILED');
log.error('Authentication failed, please run `neonctl auth`');
sendError(err, 'AUTH_FAILED');
try {
deleteCredentials(defaultDir);
} catch (deleteErr) {
log.debug(
'Failed to delete credentials: %s',
deleteErr instanceof Error ? deleteErr.message : 'unknown error',
);
}
} else {
if (err.response?.data?.message) {
log.error(err.response?.data?.message);
Expand Down