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: account recovery #270

Closed
wants to merge 1 commit into from
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
39 changes: 2 additions & 37 deletions src/command-handlers/logout.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,11 @@
import { Database } from 'better-sqlite3';
import { deactivateDevices } from '../endpoints/index.js';
import { connectAndPrepare, connect, reset } from '../modules/database/index.js';
import { LocalConfiguration, DeviceConfiguration } from '../types.js';
import { askConfirmReset } from '../utils/index.js';
import { logger } from '../logger.js';
import { logout } from '../modules/auth/logout.js';

export const runLogout = async (options: { ignoreRevocation: boolean }) => {
if (options.ignoreRevocation) {
logger.info("The device credentials won't be revoked on Dashlane's servers.");
}

const resetConfirmation = await askConfirmReset();
if (!resetConfirmation) {
return;
}

let db: Database;
let localConfiguration: LocalConfiguration | undefined;
let deviceConfiguration: DeviceConfiguration | null | undefined;
try {
({ db, localConfiguration, deviceConfiguration } = await connectAndPrepare({
autoSync: false,
failIfNoDB: true,
}));
} catch (error) {
let errorMessage = 'unknown error';
if (error instanceof Error) {
errorMessage = error.message;
}
logger.debug(`Unable to read device configuration during logout: ${errorMessage}`);

db = connect();
db.serialize();
}
if (localConfiguration && deviceConfiguration && !options.ignoreRevocation) {
await deactivateDevices({
deviceIds: [deviceConfiguration.accessKey],
login: deviceConfiguration.login,
localConfiguration,
}).catch((error) => logger.error('Unable to deactivate the device', error));
}
reset({ db, localConfiguration });
logger.success('The local Dashlane local storage has been reset and you have been logged out.');
db.close();
await logout({ ignoreRevocation: options.ignoreRevocation });
};
37 changes: 37 additions & 0 deletions src/command-handlers/recovery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { logger } from '../logger';
import { logout } from '../modules/auth';
import { connectAndPrepare } from '../modules/database/connectAndPrepare';
import { askConfirmRecovery, askConfirmShowMp } from '../utils';
import { sync } from './sync';

export const runAccountRecovery = async () => {
const doRecovery = await askConfirmRecovery();
if (!doRecovery) {
return;
}
const shouldShowMp = await askConfirmShowMp();

await logout({ ignoreRevocation: false });
const { db, localConfiguration, deviceConfiguration } = await connectAndPrepare({
autoSync: false,
recoveryOptions: {
promptForArk: true,
displayMasterpassword: shouldShowMp,
},
});

try {
await sync({ db, localConfiguration, deviceConfiguration });
logger.success('Account recovered! you can use the CLI to export its data.');
} catch (error) {
logger.error(
'Sync failed. It probably means that the masterpassword locked behind the recovery key\n' +
'is not matching. Try running the command again and show the masterpassword. Maybe you will\n' +
'remember the one you initially set up'
);

throw error;
} finally {
db.close();
}
};
6 changes: 6 additions & 0 deletions src/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
runBackup,
runSecret,
} from '../command-handlers/index.js';
import { runAccountRecovery } from '../command-handlers/recovery.js';

export const rootCommands = (params: { program: Command }) => {
const { program } = params;
Expand Down Expand Up @@ -113,6 +114,11 @@ export const rootCommands = (params: { program: Command }) => {
.description('Backup your local vault (will use the current directory by default)')
.action(runBackup);

program
.command('recover-account')
.description('interactively login to an account with a recovery key')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
.description('interactively login to an account with a recovery key')
.description('Interactively login to an account with a recovery key')

.action(runAccountRecovery);

program
.command('lock')
.description('Lock the vault, next commands will request the master password to unlock it)')
Expand Down
19 changes: 19 additions & 0 deletions src/endpoints/getEncryptedVaultKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { requestAppApi } from '../requestApi.js';

interface GetEncryptedVaultKeyParams {
login: string;
authTicket: string;
}

export interface GetEncryptedVaultKeyResult {
encryptedVaultKey: string;
}

export const getEncryptedVaultKey = ({ authTicket, login }: GetEncryptedVaultKeyParams) =>
requestAppApi<GetEncryptedVaultKeyResult>({
path: 'accountrecovery/GetEncryptedVaultKey',
payload: {
authTicket,
login,
},
});
74 changes: 74 additions & 0 deletions src/modules/auth/getAuthenticationTickets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import {
performDashlaneAuthenticatorVerification,
performDuoPushVerification,
performEmailTokenVerification,
performTotpVerification,
} from '../../endpoints';
import { getAuthenticationMethodsForDevice } from '../../endpoints/getAuthenticationMethodsForDevice';
import { logger } from '../../logger';
import { askOtp, askToken, askVerificationMethod } from '../../utils/dialogs';
import { doConfidentialSSOVerification } from './confidential-sso';
import { doSSOVerification } from './sso';

export const getAuthenticationTickets = async (login: string) => {
logger.debug('Registering the device...');

// Log in via a compatible verification method
const { verifications, accountType } = await getAuthenticationMethodsForDevice({ login });

if (accountType === 'invisibleMasterPassword') {
throw new Error('Master password-less is currently not supported');
}

const nonEmptyVerifications = verifications.filter((method) => method.type);

const selectedVerificationMethod =
nonEmptyVerifications.length > 1
? await askVerificationMethod(nonEmptyVerifications)
: nonEmptyVerifications[0];

let authTicket: string;
let ssoSpKey: string | null = null;
if (!selectedVerificationMethod || Object.keys(selectedVerificationMethod).length === 0) {
throw new Error('No verification method selected');
}

if (selectedVerificationMethod.type === 'duo_push') {
logger.info('Please accept the Duo push notification on your phone.');
({ authTicket } = await performDuoPushVerification({ login }));
} else if (selectedVerificationMethod.type === 'dashlane_authenticator') {
logger.info('Please accept the Dashlane Authenticator push notification on your phone.');
({ authTicket } = await performDashlaneAuthenticatorVerification({ login }));
} else if (selectedVerificationMethod.type === 'totp') {
const otp = await askOtp();
({ authTicket } = await performTotpVerification({
login,
otp,
}));
} else if (selectedVerificationMethod.type === 'email_token') {
const urlEncodedLogin = encodeURIComponent(login);
logger.info(
`Please open the following URL in your browser: https://www.dashlane.com/cli-device-registration?login=${urlEncodedLogin}`
);
const token = await askToken();
({ authTicket } = await performEmailTokenVerification({
login,
token,
}));
} else if (selectedVerificationMethod.type === 'sso') {
if (selectedVerificationMethod.ssoInfo.isNitroProvider) {
({ authTicket, ssoSpKey } = await doConfidentialSSOVerification({
requestedLogin: login,
}));
} else {
({ authTicket, ssoSpKey } = await doSSOVerification({
requestedLogin: login,
serviceProviderURL: selectedVerificationMethod.ssoInfo.serviceProviderUrl,
}));
}
} else {
throw new Error('Auth verification method not supported: ' + selectedVerificationMethod.type);
}

return { ssoSpKey, authTicket };
};
3 changes: 3 additions & 0 deletions src/modules/auth/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
export * from './perform2FAVerification.js';
export * from './registerDevice.js';
export * from './userPresenceVerification.js';
export * from './getAuthenticationTickets.js';
export * from './recovery/getMasterpasswordFromArkPrompt.js';
export * from './logout.js';
40 changes: 40 additions & 0 deletions src/modules/auth/logout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Database } from 'better-sqlite3';
import { deactivateDevices } from '../../endpoints';
import { logger } from '../../logger';
import { LocalConfiguration, DeviceConfiguration } from '../../types';
import { connectAndPrepare, connect, reset } from '../database';

export const logout = async (options: { ignoreRevocation: boolean }) => {
if (options.ignoreRevocation) {
logger.info("The device credentials won't be revoked on Dashlane's servers.");
}

let db: Database;
let localConfiguration: LocalConfiguration | undefined;
let deviceConfiguration: DeviceConfiguration | null | undefined;
try {
({ db, localConfiguration, deviceConfiguration } = await connectAndPrepare({
autoSync: false,
failIfNoDB: true,
}));
} catch (error) {
let errorMessage = 'unknown error';
if (error instanceof Error) {
errorMessage = error.message;
}
logger.debug(`Unable to read device configuration during logout: ${errorMessage}`);

db = connect();
db.serialize();
}
if (localConfiguration && deviceConfiguration && !options.ignoreRevocation) {
await deactivateDevices({
deviceIds: [deviceConfiguration.accessKey],
login: deviceConfiguration.login,
localConfiguration,
}).catch((error) => logger.error('Unable to deactivate the device', error));
}
reset({ db, localConfiguration });
logger.success('The local Dashlane local storage has been reset and you have been logged out.');
db.close();
};
34 changes: 34 additions & 0 deletions src/modules/auth/recovery/getMasterpasswordFromArkPrompt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { getEncryptedVaultKey } from '../../../endpoints/getEncryptedVaultKey';
import { logger } from '../../../logger';
import { askAccountRecoveryKey } from '../../../utils/dialogs';
import { decryptAesCbcHmac256, getDerivateUsingParametersFromEncryptedData } from '../../crypto/decrypt';
import { deserializeEncryptedData } from '../../crypto/encryptedDataDeserialization';

function cleanArk(input: string): string {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use arrow function please, here and below

return input.toUpperCase().replaceAll(/[^A-Z0-9]/g, '');
}
export async function getMasterpasswordFromArkPrompt(authTicket: string, login: string): Promise<string> {
const { encryptedVaultKey: encryptedVaultKeyBase64 } = await getEncryptedVaultKey({
authTicket,
login,
});

const ark = cleanArk(await askAccountRecoveryKey());

const buffer = Buffer.from(encryptedVaultKeyBase64, 'base64');
const decodedBase64 = buffer.toString('ascii');
const { encryptedData } = deserializeEncryptedData(decodedBase64, buffer);
const derivatedKey = await getDerivateUsingParametersFromEncryptedData(ark, encryptedData);

try {
const decryptedVaultKey = decryptAesCbcHmac256({
cipherData: encryptedData.cipherData,
originalKey: derivatedKey,
inflatedKey: encryptedData.cipherConfig.cipherMode === 'cbchmac64',
});
return decryptedVaultKey.toString('utf-8');
} catch (e) {
logger.error('Failed to decrypt MP. Maybe the ARK entered is incorrect');
throw e;
Comment on lines +30 to +32
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
} catch (e) {
logger.error('Failed to decrypt MP. Maybe the ARK entered is incorrect');
throw e;
} catch (error) {
logger.error('Failed to decrypt Master Password. Maybe the ARK (Account Recovery Key) entered is incorrect');
throw error;

}
}
79 changes: 5 additions & 74 deletions src/modules/auth/registerDevice.ts
Original file line number Diff line number Diff line change
@@ -1,84 +1,15 @@
import { doSSOVerification } from './sso/index.js';
import { doConfidentialSSOVerification } from './confidential-sso/index.js';
import {
completeDeviceRegistration,
performDashlaneAuthenticatorVerification,
performDuoPushVerification,
performEmailTokenVerification,
performTotpVerification,
} from '../../endpoints/index.js';
import { askOtp, askToken, askVerificationMethod } from '../../utils/index.js';
import { getAuthenticationMethodsForDevice } from '../../endpoints/getAuthenticationMethodsForDevice.js';
import { logger } from '../../logger.js';
import { completeDeviceRegistration } from '../../endpoints/index.js';
import { getAuthenticationTickets } from './getAuthenticationTickets.js';

interface RegisterDevice {
login: string;
deviceName: string;
}

export const registerDevice = async (params: RegisterDevice) => {
const { login, deviceName } = params;
logger.debug('Registering the device...');

// Log in via a compatible verification method
const { verifications, accountType } = await getAuthenticationMethodsForDevice({ login });

if (accountType === 'invisibleMasterPassword') {
throw new Error('Master password-less is currently not supported');
}

const nonEmptyVerifications = verifications.filter((method) => method.type);

const selectedVerificationMethod =
nonEmptyVerifications.length > 1
? await askVerificationMethod(nonEmptyVerifications)
: nonEmptyVerifications[0];

let authTicket: string;
let ssoSpKey: string | null = null;
if (!selectedVerificationMethod || Object.keys(selectedVerificationMethod).length === 0) {
throw new Error('No verification method selected');
}

if (selectedVerificationMethod.type === 'duo_push') {
logger.info('Please accept the Duo push notification on your phone.');
({ authTicket } = await performDuoPushVerification({ login }));
} else if (selectedVerificationMethod.type === 'dashlane_authenticator') {
logger.info('Please accept the Dashlane Authenticator push notification on your phone.');
({ authTicket } = await performDashlaneAuthenticatorVerification({ login }));
} else if (selectedVerificationMethod.type === 'totp') {
const otp = await askOtp();
({ authTicket } = await performTotpVerification({
login,
otp,
}));
} else if (selectedVerificationMethod.type === 'email_token') {
const urlEncodedLogin = encodeURIComponent(login);
logger.info(
`Please open the following URL in your browser: https://www.dashlane.com/cli-device-registration?login=${urlEncodedLogin}`
);
const token = await askToken();
({ authTicket } = await performEmailTokenVerification({
login,
token,
}));
} else if (selectedVerificationMethod.type === 'sso') {
if (selectedVerificationMethod.ssoInfo.isNitroProvider) {
({ authTicket, ssoSpKey } = await doConfidentialSSOVerification({
requestedLogin: login,
}));
} else {
({ authTicket, ssoSpKey } = await doSSOVerification({
requestedLogin: login,
serviceProviderURL: selectedVerificationMethod.ssoInfo.serviceProviderUrl,
}));
}
} else {
throw new Error('Auth verification method not supported: ' + selectedVerificationMethod.type);
}
export const registerDevice = async ({ deviceName, login }: RegisterDevice) => {
const { authTicket, ssoSpKey } = await getAuthenticationTickets(login);

// Complete the device registration and save the result
const completeDeviceRegistrationResponse = await completeDeviceRegistration({ login, deviceName, authTicket });

return { ...completeDeviceRegistrationResponse, ssoSpKey };
return { ...completeDeviceRegistrationResponse, ssoSpKey, authTicket };
};
Loading