Skip to content

Commit

Permalink
fix cli profile
Browse files Browse the repository at this point in the history
  • Loading branch information
bnonni committed Nov 2, 2024
1 parent 6392c8e commit 8ab46bf
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 52 deletions.
37 changes: 19 additions & 18 deletions src/cli/commands/profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,21 +98,21 @@ export class ProfileCommand {
}

// Function to create a new profile
static async create({ password, dwnEndpoint, method }: ProfileCreateParams): Promise<void> {
static async create({ password, dwnEndpoints, method }: ProfileCreateParams): Promise<void> {
try {
if(await this.needSetup()) {
throw new Error(`DRPM config not setup. Re-install drpm to setup ${DRPM_HOME}.`);
}
method ??= 'dht';
if(!dwnEndpoint) {
if(!dwnEndpoints) {
throw new Error('DWN endpoint is required to create a new profile.');
}
const profile = await this.load();
// if(this.valid(profile)) {
// throw new Error(`Profile already setup and valid for ${method} context.`);
// }
password ??= createPassword();
const partialProfile = await this.createDht(password, dwnEndpoint);
const partialProfile = await this.createDht(password, dwnEndpoints);
await this.save({...profile, ...partialProfile});
Logger.log(`New DRPM ${method} profile created: ${stringify(partialProfile)}`);
} catch (error: any) {
Expand All @@ -135,43 +135,44 @@ export class ProfileCommand {
// Function to get profile data
static async get(options: ProfileOptions): Promise<void> {
const profile = await this.load();
const data = profile[profile.current ?? 'dht'];
const current = profile.current ?? 'dht';
const data = profile[current];
const optionKeys = Object.keys(options);
!optionKeys.length
? Logger.info(`Profile: ${stringify(data)}`)
? Logger.plain(`${current.toUpperCase()} Profile:\n${cleanProfile(data)}`)
: optionKeys.forEach((key) => {
if (options[key as keyof ProfileOptions]) {
Logger.info(`${cleanProfile({ [key]: data[key as keyof ProfileData] })}`);
if (data[key as keyof ProfileOptions]) {
Logger.plain(`${key}: ${data[key as keyof ProfileData]}`);
} else {
Logger.error(`ProfileError: ${key} not found in profile.`);
}
});
}

// Function to update profile data
static async set({ did, password, dwnEndpoint, web5DataPath, recoveryPhrase }: ProfileOptions): Promise<void> {
static async set({ did, password, dwnEndpoints, web5DataPath, recoveryPhrase }: ProfileOptions): Promise<void> {
const profile = await this.load();
const current = profile.current ?? 'dht';
const data = profile[current];
const updatedData = {
did : did ?? data.did,
password : password ?? data.password,
dwnEndpoints : !dwnEndpoint
dwnEndpoints : !dwnEndpoints
? data.dwnEndpoints
: !dwnEndpoint.startsWith('http')
? [`https://${dwnEndpoint}`]
: [dwnEndpoint],
: dwnEndpoints.split(','),
web5DataPath : web5DataPath ?? data.web5DataPath,
recoveryPhrase : recoveryPhrase ?? data.recoveryPhrase,
};
await this.save({ ...profile, [current]: { ...data, ...updatedData, } });
Logger.log(`Profile updated: ${cleanProfile(updatedData)}`);
}

static async switch({ method }: { method: string }): Promise<void> {
static async switch({ dht, web, btc }: { dht: string, web: string, btc: string }): Promise<void> {
const profile = await this.load();
if(!profile[method]) {
throw new Error(`Profile for ${method} does not exist.`);
}
await this.save({...profile, current: method});
Logger.log(`Switched to ${method} profile.`);
console.log('dht, web, btc', dht, web, btc);
profile.current = dht ? 'dht' : web ? 'web' : btc ? 'btc' : profile.current;
await this.save(profile);
const data = profile[profile.current];
Logger.log(`Switched to ${profile.current} profile: ${cleanProfile(data)}`);
}
}
63 changes: 32 additions & 31 deletions src/cli/drpm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,59 +65,60 @@ const profileCommand = program
profileCommand
.command('create')
.description('Create a new DPM profile')
.option('-p, --password <PASSWORD>', 'Secure password to protect your local DRPM DWN data')
.option('-m, --method <METHOD>', 'Did method to use for your profile; Accetps dht and web; (default: dht)')
.option('-u, --url <URL>', 'URL of for your did web; (e.g. did:web:example.com)')
.option('-e, --dwnEndpoint <ENDPOINT>', 'URL for your DWN endpoint; Only pass 1 endopoint, e.g. https://dwn.example.com or http://localhost:3000')
.option('-p, --password <PASSWORD>', 'Provide a custom password (protects local DWN data)')
.option('-m, --method <METHOD>', 'Provide a custom did method (default: dht)')
.option('-u, --url <URL>', 'Provide did web URL (e.g. example.com => did:web:example.com)')
.option('-e, --dwnEndpoints <ENDPOINTS>', 'Provide one or more DWN endpoints to use')
.addHelpText('after', `
Examples:
drpm profile create -e https://dwn.mydomain.org # Create new profile
drpm profile set -d did:example:abc123 # Set your did
drpm profile set -p "correct horse battery staple" # Set your password
drpm profile set -e https://dwn.mydomain.org # Set your dwn endpoint
drpm profile get -d # Get your did
drpm profile get -p # Get your password
drpm profile get -e # Get your dwn endpoint
`)
drpm profile create -e https://dwn.mydomain.org # Create new profile with 1 DWN endpoint
drpm profile create -e https://dwn.example.com,http://localhost:3000 # Create new profile with multiple DWN endpoints
`)
.action(async (args) => await ProfileCommand.create(args));

/* ---- PROFILE SET ---- */
profileCommand
.command('set')
.description('Set your DPM profile')
.option('-d, --did <DID>', 'Your Decentralized Identifier (DID)')
.option('-p, --password <PASSWORD>', 'Secure password to protect your local DRPM DWN data')
.option('-e, --dwnEndpoint <ENDPOINT>',
'Your Decentralized Web Node (DWN) endpoint; ' +
'e.g. https://dwn.example.com, dwn.example.com or http://localhost:3000')
.option('-w, --web5DataPath <WEB5DATAPATH>',
'Desired path location to store your web5 data (keys, dwn data, etc.); ' +
`Must be an absolute path. default: ${process.cwd()}/DATA`)
.option('-d, --did <DID>', 'Set the DID')
.option('-p, --password <PASSWORD>', 'Set the password (protects local DWN data)')
.option('-r, --recoveryPhrase <RECOVERYPHRASE>', 'Set the recovery phrase (for agent key recovery)')
.option('-e, --dwnEndpoints <ENDPOINTS>', 'Set the DWN endpoints')
.option('-w, --web5DataPath <WEB5DATAPATH>', `Set the web5 DATA folder path (default: ${process.cwd()}/DATA)`)
.addHelpText('after', `
Examples:
drpm profile set -d did:example:abc123 # Set the DID
drpm profile set -p "correct horse battery staple" # Set the password
drpm profile set -e https://dwn.mydomain.org # Set the DWN endpoint
`)
.action(async (args) => await ProfileCommand.set(args));

/* ---- PROFILE GET ---- */
profileCommand
.command('get')
.description('Get your DPM profile data. If no options passed, full profile will be printed.')
.option('-d, --did', 'Get your Decentralized Identifier (DID)')
.option('-p, --password', 'Get your password in plain text')
.option('-e, --dwnEndpoint', 'Get your Decentralized Web Node (DWN) endpoint')
.option('-w, --web5DataPath', `Get your web5 data storage path (default: ${DEFAULT_WEB5DATAPATH})`)
.option('-d, --did', 'Get the DID')
.option('-p, --password', 'Get the password in plain text')
.option('-r, --recoveryPhrase <RECOVERYPHRASE>', 'Get the recovery phrase (for agent key recovery)')
.option('-e, --dwnEndpoints', 'Get the DWN endpoints')
.option('-w, --web5DataPath', `Get the web5 data storage path (default: ${DEFAULT_WEB5DATAPATH})`)
.addHelpText('after', `
Examples:
drpm profile get # Get full profile
drpm profile get -d # Get your DID
drpm profile get -p # Get your password
drpm profile get -e # Get your DWN endpoint
drpm profile get -w # Get your web5 data path
drpm profile get # Print the full profile
drpm profile get -d # Print the profile DID
drpm profile get -p # Print the profile password
drpm profile get -e # Print the profile DWN endpoints
drpm profile get -w # Print the profile web5 data path
`)
.action(async (args) => await ProfileCommand.get(args));

/* ---- PROFILE SWITCH ---- */
profileCommand
.command('switch')
.description('Get your DPM profile data. If no options passed, full profile will be printed.')
.option('-m, --method', 'Profile to switch to (based on did method: dht, web, btc)')
.description('Switch between different DID profiles.')
.option('-d, --dht', 'Switch to did:dht method')
.option('-w, --web', 'Switch to did:web method')
.option('-b, --btc', 'Switch to did:btc method')
.action(async (args) => await ProfileCommand.switch(args));
/* ---- PROFILE ---- */

Expand Down
4 changes: 4 additions & 0 deletions src/utils/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ export class Logger implements Partial<Console> {
console.warn(chalk.red('security') + ':', message, ...args);
}

public static plain(message?: unknown, ...args: unknown[]): void {
console.log(message, ...args);
}

public static log(message?: unknown, ...args: unknown[]): void {
switch (NODE_ENV) {
case 'test':
Expand Down
2 changes: 1 addition & 1 deletion src/utils/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { ProfileData } from './types.js';

export const stringify = (data: any): string => JSON.stringify(data, null, 2);

export const hideSensitive = (data: any): {} => ({...data, password: '***************', recovertyPhrase: '***************'});
export const hideSensitive = (data: any): {} => ({...data, password: '***************', recoveryPhrase: '***************'});

export const cleanProfile = (profile: Partial<ProfileData>): {} => stringify(hideSensitive(profile));

Expand Down
4 changes: 2 additions & 2 deletions src/utils/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,15 +160,15 @@ export type Profile = {
export type ProfileOptions = {
did?: string;
password?: string;
dwnEndpoint?: string;
dwnEndpoints?: string;
web5DataPath?: string
recoveryPhrase?: string;
context?: string;
};
export type ProfileCreateParams = {
url?: string;
method: string;
dwnEndpoint: string;
dwnEndpoints: string;
password?: string;
};
export type RequestParams = Request['params'];

0 comments on commit 8ab46bf

Please sign in to comment.