diff --git a/packages/daf-cli/package.json b/packages/daf-cli/package.json index dc3533c0e..965a79105 100644 --- a/packages/daf-cli/package.json +++ b/packages/daf-cli/package.json @@ -8,7 +8,6 @@ "daf": "bin/daf.js" }, "scripts": { - "postinstall": "scripts/postinstall.js", "build": "tsc", "watch": "tsc -b --watch" }, diff --git a/packages/daf-cli/scripts/postinstall.js b/packages/daf-cli/scripts/postinstall.js deleted file mode 100755 index dbb324eeb..000000000 --- a/packages/daf-cli/scripts/postinstall.js +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env node - -const fs = require('fs') -const { SecretBox } = require('daf-libsodium') - -const defaultPath = process.env.HOME + '/.daf/' -const envFile = defaultPath + '.env' - -async function main() { - - if (!fs.existsSync(defaultPath)) { - fs.mkdirSync(defaultPath) - } - - if (!fs.existsSync(envFile)) { - console.log('Configuration file does not exist. Creating: ' + envFile) - let env = 'DAF_DATA_STORE=' + defaultPath + 'database-v3.sqlite3' - env += '\nDEBUG_DAF_DB=0' - env += '\nDAF_SECRET_KEY=' + await SecretBox.createSecretKey() - env += '\nDAF_INFURA_ID=5ffc47f65c4042ce847ef66a3fa70d4c' - env += '\n#DEBUG=daf:*' - - fs.writeFileSync(envFile, env) - } - -} - -main().catch(console.error) \ No newline at end of file diff --git a/packages/daf-cli/src/cli.ts b/packages/daf-cli/src/cli.ts index 16d200f3f..844db1c56 100644 --- a/packages/daf-cli/src/cli.ts +++ b/packages/daf-cli/src/cli.ts @@ -1,6 +1,3 @@ -import { config } from 'dotenv' -config({ path: process.env.HOME + '/.daf/.env'}) - import program from 'commander' import './identity-manager' import './did-resolver' diff --git a/packages/daf-cli/src/credential.ts b/packages/daf-cli/src/credential.ts index 2116d62e5..af343b2a4 100644 --- a/packages/daf-cli/src/credential.ts +++ b/packages/daf-cli/src/credential.ts @@ -12,7 +12,7 @@ program .option('-s, --send', 'Send') .option('-q, --qrcode', 'Show qrcode') .action(async cmd => { - const identities = await agent.identityManager.getIdentities() + const identities = await (await agent).identityManager.getIdentities() if (identities.length === 0) { console.error('No dids') process.exit() @@ -59,7 +59,7 @@ program }, } - const credential: Daf.Credential = await agent.handleAction(signAction) + const credential: Daf.Credential = await (await agent).handleAction(signAction) if (cmd.send) { const sendAction: DIDComm.ActionSendDIDComm = { @@ -72,7 +72,7 @@ program }, } try { - const message: Daf.Message = await agent.handleAction(sendAction) + const message: Daf.Message = await (await agent).handleAction(sendAction) console.log('Sent:', message) } catch (e) { console.error(e) @@ -92,7 +92,7 @@ program .option('-s, --send', 'Send') .option('-q, --qrcode', 'Show qrcode') .action(async cmd => { - const myIdentities = await agent.identityManager.getIdentities() + const myIdentities = await (await agent).identityManager.getIdentities() if (myIdentities.length === 0) { console.error('No dids') process.exit() @@ -107,7 +107,7 @@ program }, ] for (const id of ids) { - const name = await id.getLatestClaimValue(agent.dbConnection, { type: 'name'}) + const name = await id.getLatestClaimValue((await agent).dbConnection, { type: 'name'}) identities.push({ value: id.did, name: `${id.did} - ${name}`, @@ -204,7 +204,7 @@ program }, } - const presentation: Daf.Presentation = await agent.handleAction(signAction) + const presentation: Daf.Presentation = await (await agent).handleAction(signAction) if (cmd.send) { const sendAction: DIDComm.ActionSendDIDComm = { @@ -217,7 +217,7 @@ program }, } try { - const message: Daf.Message = await agent.handleAction(sendAction) + const message: Daf.Message = await (await agent).handleAction(sendAction) console.log('Sent:', message) } catch (e) { console.error(e) diff --git a/packages/daf-cli/src/data-explorer.ts b/packages/daf-cli/src/data-explorer.ts index f90fc0490..42bafb856 100644 --- a/packages/daf-cli/src/data-explorer.ts +++ b/packages/daf-cli/src/data-explorer.ts @@ -12,7 +12,7 @@ program .option('-m, --messages', 'List messages') .action(async cmd => { if (cmd.identities) { - const dbConnection = await agent.dbConnection + const dbConnection = await (await agent).dbConnection const ids = await dbConnection.getRepository(Daf.Identity).find() if (ids.length === 0) { console.error('No dids') @@ -21,7 +21,7 @@ program const identities = [] for (const id of ids) { - const name = await id.getLatestClaimValue(agent.dbConnection, {type: 'name'}) + const name = await id.getLatestClaimValue((await agent).dbConnection, {type: 'name'}) identities.push({ value: id.did, name: `${id.did} - ${name || id.shortDid()}`, @@ -57,7 +57,7 @@ program } if (cmd.messages) { - const dbConnection = await agent.dbConnection + const dbConnection = await (await agent).dbConnection showMessageList(await dbConnection.getRepository(Daf.Message).find()) } }) @@ -85,7 +85,7 @@ const showMessageList = async (messages: Daf.Message[]) => { } const showMessage = async (id: string) => { - const dbConnection = await agent.dbConnection + const dbConnection = await (await agent).dbConnection const message = await dbConnection.getRepository(Daf.Message) .findOne(id, {relations: ['credentials', 'credentials.claims']}) console.log(message) @@ -112,7 +112,7 @@ const showMessage = async (id: string) => { const showCredentials = async (did: string) => { const table = [] - const dbConnection = await agent.dbConnection + const dbConnection = await (await agent).dbConnection const credentials = await dbConnection.getRepository(Daf.Credential) .find({ where: { subject: did } }) diff --git a/packages/daf-cli/src/did-resolver.ts b/packages/daf-cli/src/did-resolver.ts index 66b436723..275484739 100644 --- a/packages/daf-cli/src/did-resolver.ts +++ b/packages/daf-cli/src/did-resolver.ts @@ -6,7 +6,7 @@ program .description('Resolve DID Document') .action(async (did) => { try { - const ddo = await agent.didResolver.resolve(did) + const ddo = await (await agent).didResolver.resolve(did) console.log(ddo) } catch (e) { console.error(e) diff --git a/packages/daf-cli/src/graphql.ts b/packages/daf-cli/src/graphql.ts index eb35a977c..f574a9b0f 100644 --- a/packages/daf-cli/src/graphql.ts +++ b/packages/daf-cli/src/graphql.ts @@ -33,7 +33,7 @@ program W3cGql.resolvers, SdrGql.resolvers, ), - context: () => ({ agent }), + context: async () => ({ agent: (await agent) }), introspection: true, }) // await core.setupServices() diff --git a/packages/daf-cli/src/identity-manager.ts b/packages/daf-cli/src/identity-manager.ts index 27bf48773..0de8a3d64 100644 --- a/packages/daf-cli/src/identity-manager.ts +++ b/packages/daf-cli/src/identity-manager.ts @@ -18,7 +18,7 @@ program .option('--decrypt', 'Decrypt data') .action(async cmd => { if (cmd.types) { - const providers = await agent.identityManager.getIdentityProviders() + const providers = (await agent).identityManager.getIdentityProviders() const list = providers.map(provider => ({ type: provider.type, description: provider.description, @@ -32,7 +32,7 @@ program } if (cmd.list) { - const list = await agent.identityManager.getIdentities() + const list = await (await agent).identityManager.getIdentities() if (list.length > 0) { const dids = list.map(item => ({ type: item.identityProviderType, did: item.did })) @@ -44,7 +44,7 @@ program if (cmd.create) { try { - const providers = await agent.identityManager.getIdentityProviders() + const providers = await (await agent).identityManager.getIdentityProviders() let type if (providers.length > 1) { const answers = await inquirer.prompt([ @@ -61,7 +61,7 @@ program type = answers.type } - const identity = await agent.identityManager.createIdentity(type) + const identity = await (await agent).identityManager.createIdentity(type) printTable([{ type: identity.identityProviderType, did: identity.did }]) } catch (e) { console.error(e) @@ -70,7 +70,7 @@ program if (cmd.delete) { try { - const identities = await agent.identityManager.getIdentities() + const identities = await (await agent).identityManager.getIdentities() const answers = await inquirer.prompt([ { type: 'list', @@ -80,9 +80,9 @@ program }, ]) - const identity = await agent.identityManager.getIdentity(answers.did) + const identity = await (await agent).identityManager.getIdentity(answers.did) - const result = await agent.identityManager.deleteIdentity(identity.identityProviderType, identity.did) + const result = await (await agent).identityManager.deleteIdentity(identity.identityProviderType, identity.did) console.log('Success:', result) } catch (e) { console.error(e) @@ -91,7 +91,7 @@ program if (cmd.service) { try { - const identities = await agent.identityManager.getIdentities() + const identities = await (await agent).identityManager.getIdentities() const answers = await inquirer.prompt([ { type: 'list', @@ -112,7 +112,7 @@ program }, ]) - const identity = await agent.identityManager.getIdentity(answers.did) + const identity = await (await agent).identityManager.getIdentity(answers.did) const result = await identity.identityController.addService({ type: answers.type, serviceEndpoint: answers.endpoint, @@ -126,7 +126,7 @@ program if (cmd.publicKey) { try { - const identities = await agent.identityManager.getIdentities() + const identities = await (await agent).identityManager.getIdentities() const answers = await inquirer.prompt([ { type: 'list', @@ -142,7 +142,7 @@ program }, ]) - const identity = await agent.identityManager.getIdentity(answers.did) + const identity = await (await agent).identityManager.getIdentity(answers.did) const result = await identity.identityController.addPublicKey(answers.type) console.log('Success:', result) } catch (e) { @@ -152,7 +152,7 @@ program if (cmd.encrypt) { try { - const identities = await agent.identityManager.getIdentities() + const identities = await (await agent).identityManager.getIdentities() const answers = await inquirer.prompt([ { type: 'list', @@ -172,9 +172,9 @@ program }, ]) - const identity = await agent.identityManager.getIdentity(answers.did) + const identity = await (await agent).identityManager.getIdentity(answers.did) const key = await identity.keyByType('Ed25519') - const didDoc = await agent.didResolver.resolve(answers.to) + const didDoc = await (await agent).didResolver.resolve(answers.to) const publicKey = didDoc?.publicKey.find(item => item.type == 'Ed25519VerificationKey2018') if (!publicKey?.publicKeyHex) throw Error('Recipient does not have encryption publicKey') @@ -194,7 +194,7 @@ program if (cmd.decrypt) { try { - const identities = await agent.identityManager.getIdentities() + const identities = await (await agent).identityManager.getIdentities() const answers = await inquirer.prompt([ { type: 'list', @@ -209,7 +209,7 @@ program }, ]) - const identity = await agent.identityManager.getIdentity(answers.did) + const identity = await (await agent).identityManager.getIdentity(answers.did) const key = await identity.keyByType('Ed25519') const result = await key.decrypt(answers.message) console.log('Success:', result) @@ -220,7 +220,7 @@ program if (cmd.export) { try { - const identities = await agent.identityManager.getIdentities() + const identities = await (await agent).identityManager.getIdentities() const answers = await inquirer.prompt([ { type: 'list', @@ -230,8 +230,8 @@ program }, ]) - const identity = await agent.identityManager.getIdentity(answers.did) - const secret = await agent.identityManager.exportIdentity(identity.identityProviderType, identity.did) + const identity = await (await agent).identityManager.getIdentity(answers.did) + const secret = await (await agent).identityManager.exportIdentity(identity.identityProviderType, identity.did) console.log(secret) } catch (e) { console.error(e) @@ -240,7 +240,7 @@ program if (cmd.import) { try { - const providers = await agent.identityManager.getIdentityProviders() + const providers = await (await agent).identityManager.getIdentityProviders() const answers = await inquirer.prompt([ { @@ -256,7 +256,7 @@ program }, ]) - const identity = await agent.identityManager.importIdentity(answers.provider, answers.secret) + const identity = await (await agent).identityManager.importIdentity(answers.provider, answers.secret) console.log(identity) } catch (e) { console.error(e) diff --git a/packages/daf-cli/src/msg.ts b/packages/daf-cli/src/msg.ts index ddf78a8a9..10ea46969 100644 --- a/packages/daf-cli/src/msg.ts +++ b/packages/daf-cli/src/msg.ts @@ -7,7 +7,7 @@ program .description('Handle raw message (JWT)') .action(async raw => { try { - const message = await agent.handleMessage({ raw, metaData: [{ type: 'cli' }] }) + const message = await (await agent).handleMessage({ raw, metaData: [{ type: 'cli' }] }) console.log(message) } catch (e) { console.error(e.message) diff --git a/packages/daf-cli/src/sdr.ts b/packages/daf-cli/src/sdr.ts index 3b0ec736d..aba1b0a52 100644 --- a/packages/daf-cli/src/sdr.ts +++ b/packages/daf-cli/src/sdr.ts @@ -12,7 +12,7 @@ program .option('-s, --send', 'Send') .option('-q, --qrcode', 'Show qrcode') .action(async cmd => { - const identities = await agent.identityManager.getIdentities() + const identities = await (await agent).identityManager.getIdentities() if (identities.length === 0) { console.error('No dids') process.exit() @@ -196,10 +196,10 @@ program }, } - const jwt = await agent.handleAction(signAction) + const jwt = await (await agent).handleAction(signAction) if (!cmd.send) { - await agent.handleMessage({ raw: jwt, metaData: [{ type: 'cli' }] }) + await (await agent).handleMessage({ raw: jwt, metaData: [{ type: 'cli' }] }) } else if (answers.sub !== '') { const sendAction: DIDComm.ActionSendDIDComm = { type: DIDComm.ActionTypes.sendMessageDIDCommAlpha1, @@ -211,7 +211,7 @@ program }, } try { - const result = await agent.handleAction(sendAction) + const result = await (await agent).handleAction(sendAction) console.log('Sent:', result) } catch (e) { console.error(e) diff --git a/packages/daf-cli/src/services.ts b/packages/daf-cli/src/services.ts index fc9a76035..d80767f23 100644 --- a/packages/daf-cli/src/services.ts +++ b/packages/daf-cli/src/services.ts @@ -12,17 +12,17 @@ program }) export const listen = async (pollSeconds?: number) => { - agent.on(EventTypes.savedMessage, async (msg: Message) => { + (await agent).on(EventTypes.savedMessage, async (msg: Message) => { console.log('New message type:', msg.type) }) - await agent.setupServices() - await agent.listen() - await agent.getMessagesSince([]) + await (await agent).setupServices() + await (await agent).listen() + await (await agent).getMessagesSince([]) if (pollSeconds) { setInterval(async () => { - await agent.getMessagesSince([]) + await (await agent).getMessagesSince([]) }, pollSeconds * 1000) } } diff --git a/packages/daf-cli/src/setup.ts b/packages/daf-cli/src/setup.ts index b268d7221..e20d8962a 100644 --- a/packages/daf-cli/src/setup.ts +++ b/packages/daf-cli/src/setup.ts @@ -14,60 +14,95 @@ import { UrlMessageHandler } from 'daf-url' import { createConnection } from 'typeorm' import ws from 'ws' +import { config } from 'dotenv' +const fs = require('fs') -const infuraProjectId = process.env.DAF_INFURA_ID -// DID Document Resolver -let didResolver: Daf.Resolver = new DafResolver({ - infuraProjectId, -}) +const defaultPath = process.env.HOME + '/.daf/' +const envFile = defaultPath + '.env' + +const writeDefaultConfig = async () => { + + if (!fs.existsSync(defaultPath)) { + fs.mkdirSync(defaultPath) + } + + if (!fs.existsSync(envFile)) { + console.log('Configuration file does not exist. Creating: ' + envFile) + let env = 'DAF_DATA_STORE=' + defaultPath + 'database-v3.sqlite3' + env += '\nDAF_DEBUG_DB=false' + env += '\nDAF_SECRET_KEY=' + await SecretBox.createSecretKey() + env += '\nDAF_INFURA_ID=5ffc47f65c4042ce847ef66a3fa70d4c' + env += '\n#DEBUG=daf:*' + + fs.writeFileSync(envFile, env) + } -if (process.env.DAF_UNIVERSAL_RESOLVER_URL) { - didResolver = new DafUniversalResolver({ - url: process.env.DAF_UNIVERSAL_RESOLVER_URL, - }) } -if (process.env.DAF_TG_URI) TrustGraphServiceController.defaultUri = process.env.DAF_TG_URI -if (process.env.DAF_TG_WSURI) TrustGraphServiceController.defaultWsUri = process.env.DAF_TG_WSURI -TrustGraphServiceController.webSocketImpl = ws +const setupAgent = async (): Promise => { + + await writeDefaultConfig() -const dbConnection = createConnection({ - type: 'sqlite', - database: process.env.DAF_DATA_STORE, - synchronize: true, - logging: process.env.DAF_DEBUG_DB === 'true' ? true : false, - entities: [...Daf.Entities], -}) + config({ path: envFile }) -const identityProviders = [ - new EthrDid.IdentityProvider({ - identityStore: new Daf.IdentityStore('rinkeby-ethr', dbConnection), - kms: new KeyManagementSystem(new Daf.KeyStore(dbConnection, new SecretBox(process.env.DAF_SECRET_KEY))), - network: 'rinkeby', - rpcUrl: 'https://rinkeby.infura.io/v3/' + infuraProjectId, - }), -] -const serviceControllers = [TrustGraphServiceController] + const infuraProjectId = process.env.DAF_INFURA_ID -const messageHandler = new UrlMessageHandler() -messageHandler - .setNext(new DIDCommMessageHandler()) - .setNext(new JwtMessageHandler()) - .setNext(new W3cMessageHandler()) - .setNext(new SdrMessageHandler()) + // DID Document Resolver + let didResolver: Daf.Resolver = new DafResolver({ + infuraProjectId, + }) + + if (process.env.DAF_UNIVERSAL_RESOLVER_URL) { + didResolver = new DafUniversalResolver({ + url: process.env.DAF_UNIVERSAL_RESOLVER_URL, + }) + } + + if (process.env.DAF_TG_URI) TrustGraphServiceController.defaultUri = process.env.DAF_TG_URI + if (process.env.DAF_TG_WSURI) TrustGraphServiceController.defaultWsUri = process.env.DAF_TG_WSURI + TrustGraphServiceController.webSocketImpl = ws -const actionHandler = new DIDCommActionHandler() -actionHandler - .setNext(new TrustGraphActionHandler()) - .setNext(new W3cActionHandler()) - .setNext(new SdrActionHandler()) + const dbConnection = createConnection({ + type: 'sqlite', + database: process.env.DAF_DATA_STORE, + synchronize: true, + logging: process.env.DAF_DEBUG_DB === 'true' ? true : false, + entities: [...Daf.Entities], + }) + + const identityProviders = [ + new EthrDid.IdentityProvider({ + identityStore: new Daf.IdentityStore('rinkeby-ethr', dbConnection), + kms: new KeyManagementSystem(new Daf.KeyStore(dbConnection, new SecretBox(process.env.DAF_SECRET_KEY))), + network: 'rinkeby', + rpcUrl: 'https://rinkeby.infura.io/v3/' + infuraProjectId, + }), + ] + const serviceControllers = [TrustGraphServiceController] + + const messageHandler = new UrlMessageHandler() + messageHandler + .setNext(new DIDCommMessageHandler()) + .setNext(new JwtMessageHandler()) + .setNext(new W3cMessageHandler()) + .setNext(new SdrMessageHandler()) + + const actionHandler = new DIDCommActionHandler() + actionHandler + .setNext(new TrustGraphActionHandler()) + .setNext(new W3cActionHandler()) + .setNext(new SdrActionHandler()) + + const agent = new Daf.Agent({ + dbConnection, + identityProviders, + serviceControllers, + didResolver, + messageHandler, + actionHandler, + }) + return agent +} -export const agent = new Daf.Agent({ - dbConnection, - identityProviders, - serviceControllers, - didResolver, - messageHandler, - actionHandler, -}) +export const agent = setupAgent() \ No newline at end of file