From dbc1d4a42ec54bdf57257c3f460beef15b87d908 Mon Sep 17 00:00:00 2001 From: Ankur Banerjee Date: Tue, 31 Oct 2023 09:38:09 +0000 Subject: [PATCH] build: Run NPM format and fix release config (#246) * Add prettier config * Update dependabot.yml * npm update * Release config * npm run format --- .github/dependabot.yml | 4 + .github/linters/.commitlint.rules.js | 21 -- .prettierignore | 11 + .prettierrc.json | 9 + .releaserc.json | 1 - package-lock.json | 72 ++-- package.json | 12 +- src/app.ts | 109 +++--- src/controllers/cheqd.ts | 124 +++---- src/controllers/did.ts | 498 ++++++++++++++------------- src/controllers/resource.ts | 246 +++++++------ src/controllers/store.ts | 63 ++-- src/helpers/helpers.ts | 98 +++--- src/helpers/response.ts | 386 +++++++++++---------- src/index.ts | 50 +-- src/service/cheqd.ts | 195 +++++------ src/types/constants.ts | 30 +- src/types/environment.d.ts | 24 +- src/types/types.ts | 108 +++--- 19 files changed, 1058 insertions(+), 1003 deletions(-) delete mode 100644 .github/linters/.commitlint.rules.js create mode 100644 .prettierignore create mode 100644 .prettierrc.json diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 1c3508a..1e1f9fe 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -18,6 +18,10 @@ updates: directory: "/" schedule: interval: "weekly" + ignore: + - dependency-name: "*" + update-types: + - version-update:semver-patch # Maintain dependencies for Docker - package-ecosystem: "docker" diff --git a/.github/linters/.commitlint.rules.js b/.github/linters/.commitlint.rules.js deleted file mode 100644 index 1217d7f..0000000 --- a/.github/linters/.commitlint.rules.js +++ /dev/null @@ -1,21 +0,0 @@ -module.exports = { - rules: { - 'type-case': [2, 'always', 'lower-case'], - 'type-empty': [2, 'never'], - 'type-enum': [ - 2, - 'always', - ['build', 'chore', 'ci', 'docs', 'feat', 'fix', 'perf', 'refactor', 'revert', 'style', 'test'], - ], - 'scope-case': [2, 'always', 'lower-case'], - 'scope-empty': [1, 'never'], - 'subject-case': [2, 'always', ['sentence-case']], - 'subject-empty': [1, 'never'], - 'subject-full-stop': [1, 'never', '.'], - 'header-max-length': [2, 'always', 100], - 'body-leading-blank': [1, 'always'], - 'body-max-line-length': [2, 'always', 1000], - 'footer-leading-blank': [1, 'always'], - 'footer-max-line-length': [2, 'always', 100], - }, -}; \ No newline at end of file diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..ae22b10 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,11 @@ +.DS_Store +node_modules +/dist + +# Ignore files for PNPM, NPM and YARN +pnpm-lock.yaml +package-lock.json +yarn.lock +*.md +*.yaml +*.yml diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..5c36adc --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,9 @@ +{ + "useTabs": true, + "tabWidth": 4, + "printWidth": 120, + "proseWrap": "always", + "semi": true, + "singleQuote": true, + "trailingComma": "es5" +} diff --git a/.releaserc.json b/.releaserc.json index 7268563..b36d3a7 100644 --- a/.releaserc.json +++ b/.releaserc.json @@ -14,7 +14,6 @@ [ "@semantic-release/commit-analyzer", { - "parserOpts": "./.github/linters/.commitlint.rules.js", "releaseRules": [ { "breaking": true, "release": "major" }, { "type": "feat", "release": "minor" }, diff --git a/package-lock.json b/package-lock.json index 2766930..a7f4e85 100644 --- a/package-lock.json +++ b/package-lock.json @@ -29,8 +29,8 @@ "@semantic-release/release-notes-generator": "^12.0.0", "@types/express": "^4.17.20", "@types/helmet": "^4.0.0", - "@types/node": "^20.8.9", - "@types/node-fetch": "^2.6.7", + "@types/node": "^20.8.10", + "@types/node-fetch": "^2.6.8", "@types/swagger-ui-express": "^4.1.5", "@types/uuid": "^9.0.6", "@typescript-eslint/eslint-plugin": "^5.62.0", @@ -41,8 +41,11 @@ "eslint-config-prettier": "^8.10.0", "eslint-config-typescript": "^3.0.0", "prettier": "^3.0.3", - "semantic-release": "^22.0.5", + "semantic-release": "^22.0.6", "typescript": "^5.2.2" + }, + "engines": { + "node": ">=18.0.0" } }, "node_modules/@aashutoshrathi/word-wrap": { @@ -1798,17 +1801,17 @@ "dev": true }, "node_modules/@types/node": { - "version": "20.8.9", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.8.9.tgz", - "integrity": "sha512-UzykFsT3FhHb1h7yD4CA4YhBHq545JC0YnEz41xkipN88eKQtL6rSgocL5tbAP6Ola9Izm/Aw4Ora8He4x0BHg==", + "version": "20.8.10", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.8.10.tgz", + "integrity": "sha512-TlgT8JntpcbmKUFzjhsyhGfP2fsiz1Mv56im6enJ905xG1DAYesxJaeSbGqQmAw8OWPdhyJGhGSQGKRNJ45u9w==", "dependencies": { "undici-types": "~5.26.4" } }, "node_modules/@types/node-fetch": { - "version": "2.6.7", - "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.7.tgz", - "integrity": "sha512-lX17GZVpJ/fuCjguZ5b3TjEbSENxmEk1B2z02yoXSK9WMEWRivhdSY73wWMn6bpcCDAOh6qAdktpKHIlkDk2lg==", + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.8.tgz", + "integrity": "sha512-nnH5lV9QCMPsbEVdTb5Y+F3GQxLSw1xQgIydrb2gSfEavRPs50FnMr+KUaa+LoPSqibm2N+ZZxH7lavZlAT4GA==", "dev": true, "dependencies": { "@types/node": "*", @@ -3660,28 +3663,15 @@ } }, "node_modules/figures": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/figures/-/figures-5.0.0.tgz", - "integrity": "sha512-ej8ksPF4x6e5wvK9yevct0UCXh8TTFlWGVLlgjZuoBH1HwjIfKE/IdL5mq89sFA7zELi1VhKpmtDnrs7zWyeyg==", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/figures/-/figures-6.0.1.tgz", + "integrity": "sha512-0oY/olScYD4IhQ8u//gCPA4F3mlTn2dacYmiDm/mbDQvpmLjV4uH+zhsQ5IyXRyvqkvtUkXkNdGvg5OFJTCsuQ==", "dev": true, "dependencies": { - "escape-string-regexp": "^5.0.0", - "is-unicode-supported": "^1.2.0" - }, - "engines": { - "node": ">=14" + "is-unicode-supported": "^2.0.0" }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/figures/node_modules/escape-string-regexp": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz", - "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==", - "dev": true, "engines": { - "node": ">=12" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -4481,12 +4471,12 @@ } }, "node_modules/is-unicode-supported": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-1.3.0.tgz", - "integrity": "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.0.0.tgz", + "integrity": "sha512-FRdAyx5lusK1iHG0TWpVtk9+1i+GjrzRffhDg4ovQ7mcidMQ6mj+MhKPmvh7Xwyv5gIS06ns49CA7Sqg7lC22Q==", "dev": true, "engines": { - "node": ">=12" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -4780,9 +4770,9 @@ } }, "node_modules/marked": { - "version": "9.1.3", - "resolved": "https://registry.npmjs.org/marked/-/marked-9.1.3.tgz", - "integrity": "sha512-XPU/J7GzU/n4voCSw1VYggtr3W5C2OeGkwEbe5PIQdA8thaie2Qw+fig6iNidKNDokTNcyR4OE9fMK14P6rqPg==", + "version": "9.1.4", + "resolved": "https://registry.npmjs.org/marked/-/marked-9.1.4.tgz", + "integrity": "sha512-Mq83CCaClhXqhf8sLQ57c1unNelHEuFadK36ga+GeXR4FeT/5ssaC5PaCRVqMA74VYorzYRqdAaxxteIanh3Kw==", "dev": true, "bin": { "marked": "bin/marked.js" @@ -8935,9 +8925,9 @@ } }, "node_modules/punycode": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz", - "integrity": "sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", "dev": true, "engines": { "node": ">=6" @@ -9344,9 +9334,9 @@ } }, "node_modules/semantic-release": { - "version": "22.0.5", - "resolved": "https://registry.npmjs.org/semantic-release/-/semantic-release-22.0.5.tgz", - "integrity": "sha512-ESCEQsZlBj1DWMA84RthaJzQHHnihoGk49s9nUxHfRNUNZelLE9JZrE94bHO2Y00EWb7iwrzr1OYhv5QNVmf8A==", + "version": "22.0.6", + "resolved": "https://registry.npmjs.org/semantic-release/-/semantic-release-22.0.6.tgz", + "integrity": "sha512-SxgpGR6b52gaKrb42nnaZWa2h5ig06XlloS3NjUN4W/lRBB8SId4JMaZaxN6Ncb+Ii2Uxd8WO6uvshTSSf8XRg==", "dev": true, "dependencies": { "@semantic-release/commit-analyzer": "^11.0.0", @@ -9359,7 +9349,7 @@ "debug": "^4.0.0", "env-ci": "^10.0.0", "execa": "^8.0.0", - "figures": "^5.0.0", + "figures": "^6.0.0", "find-versions": "^5.1.0", "get-stream": "^6.0.0", "git-log-parser": "^1.2.0", diff --git a/package.json b/package.json index db45806..1f54984 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,8 @@ "scripts": { "dev": "nodemon src/index.ts", "start": "node dist/index.js", - "build": "esbuild src/index.ts --platform=node --bundle --minify --outdir=dist --external:swagger-ui-express" + "build": "esbuild src/index.ts --platform=node --bundle --minify --outdir=dist --external:swagger-ui-express", + "format": "prettier --write 'src/**/*.{js,ts,cjs,mjs}' 'tests/**/*.{js,ts,cjs,mjs}'" }, "files": [ "dist", @@ -45,8 +46,8 @@ "@semantic-release/release-notes-generator": "^12.0.0", "@types/express": "^4.17.20", "@types/helmet": "^4.0.0", - "@types/node": "^20.8.9", - "@types/node-fetch": "^2.6.7", + "@types/node": "^20.8.10", + "@types/node-fetch": "^2.6.8", "@types/swagger-ui-express": "^4.1.5", "@types/uuid": "^9.0.6", "@typescript-eslint/eslint-plugin": "^5.62.0", @@ -57,11 +58,14 @@ "eslint-config-prettier": "^8.10.0", "eslint-config-typescript": "^3.0.0", "prettier": "^3.0.3", - "semantic-release": "^22.0.5", + "semantic-release": "^22.0.6", "typescript": "^5.2.2" }, "publishConfig": { "registry": "https://registry.npmjs.org/", "access": "public" + }, + "engines": { + "node": ">=18.0.0" } } diff --git a/src/app.ts b/src/app.ts index 7fb8259..13d200e 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,50 +1,69 @@ -import express from 'express' -import Helmet from 'helmet' -import * as swagger from 'swagger-ui-express' -import * as swaggerJson from '../swagger.json' +import express from 'express'; +import Helmet from 'helmet'; +import * as swagger from 'swagger-ui-express'; +import * as swaggerJson from '../swagger.json'; -import { DidController } from './controllers/did' -import { CheqdController } from './controllers/cheqd' -import { ResourceController } from './controllers/resource' -import { CheqdRegistrar } from './service/cheqd' +import { DidController } from './controllers/did'; +import { CheqdController } from './controllers/cheqd'; +import { ResourceController } from './controllers/resource'; +import { CheqdRegistrar } from './service/cheqd'; class App { - public express: express.Application - - constructor() { - this.express = express() - this.middleware() - this.routes() - CheqdRegistrar.instance - } - - private middleware() { - this.express.use(express.json({ limit: '50mb' })) - this.express.use(express.urlencoded({ extended: false })) - this.express.use(Helmet()) - this.express.use('/api-docs', swagger.serve, swagger.setup(swaggerJson)) - } - - private routes() { - const app = this.express - const URL_PREFIX = '/1.0' - - app.get('/', (req, res) => res.redirect('api-docs')) - - // did-registrar - app.post(`${URL_PREFIX}/create`, DidController.createValidator, DidController.commonValidator, new DidController().create) - app.post(`${URL_PREFIX}/update`, DidController.updateValidator, DidController.commonValidator, new DidController().update) - app.post(`${URL_PREFIX}/deactivate`, DidController.deactivateValidator, DidController.commonValidator, new DidController().deactivate) - app.post(`${URL_PREFIX}/:did/create-resource`, ResourceController.createValidator, DidController.commonValidator, new ResourceController().create) - - // cheqd-helpers - app.get(`${URL_PREFIX}/key-pair`, new CheqdController().generateKeys) - app.get(`${URL_PREFIX}/did-document`, CheqdController.didDocValidator, new CheqdController().generateDidDoc) - - // 404 for all other requests - app.all('*', (req, res) => res.status(400).send('Bad request')) - } - + public express: express.Application; + + constructor() { + this.express = express(); + this.middleware(); + this.routes(); + CheqdRegistrar.instance; + } + + private middleware() { + this.express.use(express.json({ limit: '50mb' })); + this.express.use(express.urlencoded({ extended: false })); + this.express.use(Helmet()); + this.express.use('/api-docs', swagger.serve, swagger.setup(swaggerJson)); + } + + private routes() { + const app = this.express; + const URL_PREFIX = '/1.0'; + + app.get('/', (req, res) => res.redirect('api-docs')); + + // did-registrar + app.post( + `${URL_PREFIX}/create`, + DidController.createValidator, + DidController.commonValidator, + new DidController().create + ); + app.post( + `${URL_PREFIX}/update`, + DidController.updateValidator, + DidController.commonValidator, + new DidController().update + ); + app.post( + `${URL_PREFIX}/deactivate`, + DidController.deactivateValidator, + DidController.commonValidator, + new DidController().deactivate + ); + app.post( + `${URL_PREFIX}/:did/create-resource`, + ResourceController.createValidator, + DidController.commonValidator, + new ResourceController().create + ); + + // cheqd-helpers + app.get(`${URL_PREFIX}/key-pair`, new CheqdController().generateKeys); + app.get(`${URL_PREFIX}/did-document`, CheqdController.didDocValidator, new CheqdController().generateDidDoc); + + // 404 for all other requests + app.all('*', (req, res) => res.status(400).send('Bad request')); + } } -export default new App().express \ No newline at end of file +export default new App().express; diff --git a/src/controllers/cheqd.ts b/src/controllers/cheqd.ts index 83daa0d..0028095 100644 --- a/src/controllers/cheqd.ts +++ b/src/controllers/cheqd.ts @@ -1,74 +1,82 @@ -import type { Request, Response } from 'express' +import type { Request, Response } from 'express'; -import { validationResult, query } from 'express-validator' +import { validationResult, query } from 'express-validator'; import { - createDidPayload, - createDidVerificationMethod, - createKeyPairHex, - createVerificationKeys, - CheqdNetwork, - MethodSpecificIdAlgo, - VerificationMethods -} from '@cheqd/sdk' + createDidPayload, + createDidVerificationMethod, + createKeyPairHex, + createVerificationKeys, + CheqdNetwork, + MethodSpecificIdAlgo, + VerificationMethods, +} from '@cheqd/sdk'; -import { NetworkType } from '../service/cheqd' +import { NetworkType } from '../service/cheqd'; export class CheqdController { + public static didDocValidator = [ + query('verificationMethod') + .isString() + .isIn([VerificationMethods.Ed255192020, VerificationMethods.Ed255192018, VerificationMethods.JWK]) + .withMessage('Invalid verificationMethod'), + query('methodSpecificIdAlgo') + .isString() + .isIn([MethodSpecificIdAlgo.Base58, MethodSpecificIdAlgo.Uuid]) + .withMessage('Invalid methodSpecificIdAlgo'), + query('network') + .optional() + .isString() + .isIn([NetworkType.Mainnet, NetworkType.Testnet]) + .withMessage('Invalid network'), + query('publicKeyHex') + .isString() + .withMessage('PublicKeyHex is required') + .isLength({ min: 64, max: 64 }) + .withMessage('PublicKeyHex should be of length 64'), + ]; - public static didDocValidator = [ - query('verificationMethod') - .isString() - .isIn([VerificationMethods.Ed255192020, VerificationMethods.Ed255192018, VerificationMethods.JWK]) - .withMessage('Invalid verificationMethod'), - query('methodSpecificIdAlgo').isString().isIn([MethodSpecificIdAlgo.Base58, MethodSpecificIdAlgo.Uuid]).withMessage('Invalid methodSpecificIdAlgo'), - query('network').optional().isString().isIn([NetworkType.Mainnet, NetworkType.Testnet]).withMessage('Invalid network'), - query('publicKeyHex').isString().withMessage('PublicKeyHex is required').isLength({min:64, max:64}).withMessage('PublicKeyHex should be of length 64') - ] - - public generateKeys(request: Request<{},{},{},{seed?: string}>, response: Response) { - const keyPair = createKeyPairHex(request.query?.seed) - - return response.json({ - privateKeyHex: keyPair.privateKey, - publicKeyHex: keyPair.publicKey - }) - } + public generateKeys(request: Request<{}, {}, {}, { seed?: string }>, response: Response) { + const keyPair = createKeyPairHex(request.query?.seed); - public generateDidDoc(request: Request<{},{},{},IDidDocRequest>, response: Response) { - // validate body - const result = validationResult(request); - if (!result.isEmpty()) { - return response.status(400).json({ - message: result.array()[0].msg - }) - } + return response.json({ + privateKeyHex: keyPair.privateKey, + publicKeyHex: keyPair.publicKey, + }); + } - const { verificationMethod, methodSpecificIdAlgo, network, publicKeyHex } = request.query - const verificationKeys = createVerificationKeys(publicKeyHex, methodSpecificIdAlgo, 'key-1', network) - const verificationMethods = createDidVerificationMethod([verificationMethod], [verificationKeys]) + public generateDidDoc(request: Request<{}, {}, {}, IDidDocRequest>, response: Response) { + // validate body + const result = validationResult(request); + if (!result.isEmpty()) { + return response.status(400).json({ + message: result.array()[0].msg, + }); + } - return response.json({ - didDoc: createDidPayload(verificationMethods, [verificationKeys]), - key: { - verificationMethodId: (verificationMethods[0]).id, - publicKeyHex - } - }) - } + const { verificationMethod, methodSpecificIdAlgo, network, publicKeyHex } = request.query; + const verificationKeys = createVerificationKeys(publicKeyHex, methodSpecificIdAlgo, 'key-1', network); + const verificationMethods = createDidVerificationMethod([verificationMethod], [verificationKeys]); + return response.json({ + didDoc: createDidPayload(verificationMethods, [verificationKeys]), + key: { + verificationMethodId: verificationMethods[0].id, + publicKeyHex, + }, + }); + } } - export interface IDidDocRequest { - verificationMethod: VerificationMethods - methodSpecificIdAlgo: MethodSpecificIdAlgo - network: CheqdNetwork - publicKeyHex: string + verificationMethod: VerificationMethods; + methodSpecificIdAlgo: MethodSpecificIdAlgo; + network: CheqdNetwork; + publicKeyHex: string; } export interface IVerificationMethodRequest { - verificationMethod: VerificationMethods - methodSpecificIdAlgo: MethodSpecificIdAlgo - network: CheqdNetwork - publicKey: string -} \ No newline at end of file + verificationMethod: VerificationMethods; + methodSpecificIdAlgo: MethodSpecificIdAlgo; + network: CheqdNetwork; + publicKey: string; +} diff --git a/src/controllers/did.ts b/src/controllers/did.ts index fce1481..9abe70e 100644 --- a/src/controllers/did.ts +++ b/src/controllers/did.ts @@ -1,263 +1,283 @@ -import type { Request, Response } from 'express' -import type { DIDDocument } from '@cheqd/sdk' -import type { SignInfo } from '@cheqd/ts-proto/cheqd/did/v2' +import type { Request, Response } from 'express'; +import type { DIDDocument } from '@cheqd/sdk'; +import type { SignInfo } from '@cheqd/ts-proto/cheqd/did/v2'; -import { validationResult, check } from 'express-validator' -import { v4 } from 'uuid' +import { validationResult, check } from 'express-validator'; +import { v4 } from 'uuid'; -import { convertToSignInfo, validateSpecCompliantPayload } from '../helpers/helpers' -import { Responses } from '../helpers/response' -import { CheqdRegistrar, CheqdResolver, NetworkType } from '../service/cheqd' -import { Messages } from '../types/constants' -import { DidDocumentOperation, IDIDCreateRequest, IDIDUpdateRequest, IState } from '../types/types' -import { LocalStore } from './store' +import { convertToSignInfo, validateSpecCompliantPayload } from '../helpers/helpers'; +import { Responses } from '../helpers/response'; +import { CheqdRegistrar, CheqdResolver, NetworkType } from '../service/cheqd'; +import { Messages } from '../types/constants'; +import { DidDocumentOperation, IDIDCreateRequest, IDIDUpdateRequest, IState } from '../types/types'; +import { LocalStore } from './store'; export class DidController { - public static createValidator = [ - check('didDocument').custom((value, {req})=>{ - if(!req.body.jobId && value) { - const {valid} = validateSpecCompliantPayload(value) - return valid - } else if (req.body.jobId) { - return true - } - return false - }).withMessage(Messages.InvalidDidDocument) - ] + public static createValidator = [ + check('didDocument') + .custom((value, { req }) => { + if (!req.body.jobId && value) { + const { valid } = validateSpecCompliantPayload(value); + return valid; + } else if (req.body.jobId) { + return true; + } + return false; + }) + .withMessage(Messages.InvalidDidDocument), + ]; - public static commonValidator = [ - check('options.versionId').optional().isString().withMessage(Messages.InvalidOptions), - check('secret.signingResponse').optional().isArray().withMessage(Messages.InvalidSecret), - check('secret.signingResponse.*.signature').isString().withMessage(Messages.InvalidSecret), - check('secret.signingResponse.*.verificationMethodId').isString().withMessage(Messages.InvalidSecret) - ] + public static commonValidator = [ + check('options.versionId').optional().isString().withMessage(Messages.InvalidOptions), + check('secret.signingResponse').optional().isArray().withMessage(Messages.InvalidSecret), + check('secret.signingResponse.*.signature').isString().withMessage(Messages.InvalidSecret), + check('secret.signingResponse.*.verificationMethodId').isString().withMessage(Messages.InvalidSecret), + ]; - public static updateValidator = [ - check('didDocument').optional().isArray().custom((value, {req})=>{ - const { valid } = validateSpecCompliantPayload(value[0]) - return valid - }).withMessage(Messages.InvalidDidDocument), - check('jobId').custom((value, {req})=>value || (req.body.did && req.body.didDocument)).withMessage(Messages.Invalid), - check('did').optional().isString().withMessage(Messages.InvalidDid).contains('did:cheqd:').withMessage(Messages.InvalidDid), - check('didDocumentOperation') - .optional() - .isArray() - .custom((value) => value[0] === DidDocumentOperation.Set && value.length == 1 ) - .withMessage('Only Set operation is supported') - ] + public static updateValidator = [ + check('didDocument') + .optional() + .isArray() + .custom((value, { req }) => { + const { valid } = validateSpecCompliantPayload(value[0]); + return valid; + }) + .withMessage(Messages.InvalidDidDocument), + check('jobId') + .custom((value, { req }) => value || (req.body.did && req.body.didDocument)) + .withMessage(Messages.Invalid), + check('did') + .optional() + .isString() + .withMessage(Messages.InvalidDid) + .contains('did:cheqd:') + .withMessage(Messages.InvalidDid), + check('didDocumentOperation') + .optional() + .isArray() + .custom((value) => value[0] === DidDocumentOperation.Set && value.length == 1) + .withMessage('Only Set operation is supported'), + ]; - public static deactivateValidator = [ - check('did').custom((value, {req})=>{ - if(!value && !req.body.jobId) return false - return true - }).withMessage(Messages.InvalidDid), - check('did').optional().isString().withMessage(Messages.InvalidDid).contains('did:cheqd:').withMessage(Messages.InvalidDid) - ] + public static deactivateValidator = [ + check('did') + .custom((value, { req }) => { + if (!value && !req.body.jobId) return false; + return true; + }) + .withMessage(Messages.InvalidDid), + check('did') + .optional() + .isString() + .withMessage(Messages.InvalidDid) + .contains('did:cheqd:') + .withMessage(Messages.InvalidDid), + ]; - public async create(request: Request, response: Response) { - // validate body - const result = validationResult(request); - if (!result.isEmpty()) { - return response.status(400).json(Responses.GetInvalidResponse( - request.body.didDocument, - request.body.secret, - result.array()[0].msg - )) - } - - let {jobId, secret={}, options={}, didDocument} = request.body as IDIDCreateRequest - let versionId: string - // Validate and get store data if any - if(jobId) { - const storeData = LocalStore.instance.getItem(jobId) - if(!storeData) { - return response.status(400).json(Responses.GetJobExpiredResponse(jobId)) - } else if (storeData.state == IState.Finished) { - return response.status(201).json(Responses.GetSuccessResponse(jobId, storeData.didDocument, secret)) - } + public async create(request: Request, response: Response) { + // validate body + const result = validationResult(request); + if (!result.isEmpty()) { + return response + .status(400) + .json( + Responses.GetInvalidResponse(request.body.didDocument, request.body.secret, result.array()[0].msg) + ); + } - didDocument = storeData.didDocument - versionId = storeData.versionId - } else { - jobId = v4() - versionId = options.versionId || v4() - } - - let signInputs: SignInfo[] - - if (secret.signingResponse) { - signInputs = convertToSignInfo(secret.signingResponse) - } else { - LocalStore.instance.setItem(jobId, {didDocument, state: IState.Action, versionId}) - return response.status(200).json(await Responses.GetDIDActionSignatureResponse(jobId, didDocument, versionId)) - } + let { jobId, secret = {}, options = {}, didDocument } = request.body as IDIDCreateRequest; + let versionId: string; + // Validate and get store data if any + if (jobId) { + const storeData = LocalStore.instance.getItem(jobId); + if (!storeData) { + return response.status(400).json(Responses.GetJobExpiredResponse(jobId)); + } else if (storeData.state == IState.Finished) { + return response.status(201).json(Responses.GetSuccessResponse(jobId, storeData.didDocument, secret)); + } - options.network = options?.network || ((didDocument.id!.split(':'))[2] as NetworkType) - - try { - await CheqdRegistrar.instance.connect(options) - const result = await CheqdRegistrar.instance.create(signInputs, didDocument, versionId) - if ( result.code == 0 ) { - LocalStore.instance.setItem(jobId, {didDocument, state: IState.Finished, versionId}) - return response.status(201).json({ - jobId, - didState: { - did: didDocument.id, - state: IState.Finished, - secret, - didDocument - } - }) - } else { - return response.status(400).json(Responses.GetInvalidResponse(didDocument, secret, JSON.stringify(result.rawLog))) - } - } catch (error) { - return response.status(500).json(Responses.GetInternalErrorResponse(didDocument, secret, error as string)) - } - } + didDocument = storeData.didDocument; + versionId = storeData.versionId; + } else { + jobId = v4(); + versionId = options.versionId || v4(); + } - public async update(request: Request, response: Response) { - // validate body - const result = validationResult(request); - if (!result.isEmpty()) { - return response.status(400).json(Responses.GetInvalidResponse( - request.body.didDocument, - request.body.secret, - result.array()[0].msg - )) - } + let signInputs: SignInfo[]; - let { jobId, secret={}, options={}, didDocument, did } = request.body as IDIDUpdateRequest + if (secret.signingResponse) { + signInputs = convertToSignInfo(secret.signingResponse); + } else { + LocalStore.instance.setItem(jobId, { didDocument, state: IState.Action, versionId }); + return response + .status(200) + .json(await Responses.GetDIDActionSignatureResponse(jobId, didDocument, versionId)); + } - let updatedDocument: DIDDocument | undefined - let versionId: string - try { - if (!jobId) { - // check if did is registered on the ledger - let resolvedDocument = await CheqdResolver(did) - - if(!resolvedDocument?.didDocument || resolvedDocument.didDocumentMetadata.deactivated) { - return response.status(400).send(Responses.GetInvalidResponse( - {id: did}, - secret, - Messages.DidNotFound - )) - } + options.network = options?.network || (didDocument.id!.split(':')[2] as NetworkType); - updatedDocument = didDocument[0] - jobId = v4() - versionId = options.versionId || v4() - } else { - const storeData = LocalStore.instance.getItem(jobId) - if(!storeData) { - return response.status(400).json(Responses.GetJobExpiredResponse(jobId)) - } else if (storeData.state == IState.Finished) { - return response.status(200).json(Responses.GetSuccessResponse(jobId, storeData.didDocument, secret)) - } + try { + await CheqdRegistrar.instance.connect(options); + const result = await CheqdRegistrar.instance.create(signInputs, didDocument, versionId); + if (result.code == 0) { + LocalStore.instance.setItem(jobId, { didDocument, state: IState.Finished, versionId }); + return response.status(201).json({ + jobId, + didState: { + did: didDocument.id, + state: IState.Finished, + secret, + didDocument, + }, + }); + } else { + return response + .status(400) + .json(Responses.GetInvalidResponse(didDocument, secret, JSON.stringify(result.rawLog))); + } + } catch (error) { + return response.status(500).json(Responses.GetInternalErrorResponse(didDocument, secret, error as string)); + } + } - updatedDocument = storeData.didDocument - versionId = storeData.versionId - did = updatedDocument.id! - } + public async update(request: Request, response: Response) { + // validate body + const result = validationResult(request); + if (!result.isEmpty()) { + return response + .status(400) + .json( + Responses.GetInvalidResponse(request.body.didDocument, request.body.secret, result.array()[0].msg) + ); + } - let signInputs: SignInfo[] - if (secret.signingResponse) { - signInputs = convertToSignInfo(secret.signingResponse) - } else { - LocalStore.instance.setItem(jobId, {didDocument: updatedDocument, state: IState.Action, versionId}) - return response.status(200).json(await Responses.GetDIDActionSignatureResponse(jobId, updatedDocument, versionId)) - } + let { jobId, secret = {}, options = {}, didDocument, did } = request.body as IDIDUpdateRequest; - options.network = options?.network || (did!.split(':'))[2] as NetworkType - await CheqdRegistrar.instance.connect(options) - const result = await CheqdRegistrar.instance.update(signInputs, updatedDocument, versionId) - if ( result.code == 0 ) { - return response.status(201).json(Responses.GetSuccessResponse(jobId, updatedDocument, secret)) - } else { - return response.status(400).json(Responses.GetInvalidResponse( - updatedDocument, - secret, - JSON.stringify(result.rawLog) - )) - } - } catch (error) { - return response.status(500).json(Responses.GetInternalErrorResponse(updatedDocument, secret, error as string)) - } - } + let updatedDocument: DIDDocument | undefined; + let versionId: string; + try { + if (!jobId) { + // check if did is registered on the ledger + let resolvedDocument = await CheqdResolver(did); - public async deactivate (request: Request, response: Response) { - // validate body - const result = validationResult(request); - if (!result.isEmpty()) { - return response.status(400).json(Responses.GetInvalidResponse( - undefined, - request.body.secret, - result.array()[0].msg - )) - } + if (!resolvedDocument?.didDocument || resolvedDocument.didDocumentMetadata.deactivated) { + return response + .status(400) + .send(Responses.GetInvalidResponse({ id: did }, secret, Messages.DidNotFound)); + } - let { jobId, secret={}, options={}, did } = request.body as IDIDUpdateRequest + updatedDocument = didDocument[0]; + jobId = v4(); + versionId = options.versionId || v4(); + } else { + const storeData = LocalStore.instance.getItem(jobId); + if (!storeData) { + return response.status(400).json(Responses.GetJobExpiredResponse(jobId)); + } else if (storeData.state == IState.Finished) { + return response + .status(200) + .json(Responses.GetSuccessResponse(jobId, storeData.didDocument, secret)); + } - let payload: DIDDocument - let versionId: string - try { - if(jobId) { - const storeData = LocalStore.instance.getItem(jobId) - if(!storeData) { - return response.status(400).json(Responses.GetJobExpiredResponse(jobId)) - } else if (storeData.state == IState.Finished) { - return response.status(201).json(Responses.GetSuccessResponse(jobId, storeData.didDocument, secret)) - } + updatedDocument = storeData.didDocument; + versionId = storeData.versionId; + did = updatedDocument.id!; + } - payload = storeData.didDocument - did = storeData.didDocument.id - versionId = storeData.versionId - } else { - jobId = v4() - versionId = options.versionId || v4() - // check if did is registered on the ledger - let resolvedDocument = await CheqdResolver(did) - - if(!resolvedDocument?.didDocument) { - return response.status(400).send(Responses.GetInvalidResponse( - {id: did}, - secret, - Messages.DidNotFound - )) - } + let signInputs: SignInfo[]; + if (secret.signingResponse) { + signInputs = convertToSignInfo(secret.signingResponse); + } else { + LocalStore.instance.setItem(jobId, { didDocument: updatedDocument, state: IState.Action, versionId }); + return response + .status(200) + .json(await Responses.GetDIDActionSignatureResponse(jobId, updatedDocument, versionId)); + } - payload = { - verificationMethod: resolvedDocument.didDocument.verificationMethod, - id: resolvedDocument.didDocument.id - } - } + options.network = options?.network || (did!.split(':')[2] as NetworkType); + await CheqdRegistrar.instance.connect(options); + const result = await CheqdRegistrar.instance.update(signInputs, updatedDocument, versionId); + if (result.code == 0) { + return response.status(201).json(Responses.GetSuccessResponse(jobId, updatedDocument, secret)); + } else { + return response + .status(400) + .json(Responses.GetInvalidResponse(updatedDocument, secret, JSON.stringify(result.rawLog))); + } + } catch (error) { + return response + .status(500) + .json(Responses.GetInternalErrorResponse(updatedDocument, secret, error as string)); + } + } - let signInputs: SignInfo[] - if (secret.signingResponse) { - signInputs = convertToSignInfo(secret.signingResponse) - } else { - LocalStore.instance.setItem(jobId, {didDocument: payload, state: IState.Action, versionId}) - return response.status(200).json(Responses.GetDeactivateDidSignatureResponse(jobId, payload, versionId)) - } + public async deactivate(request: Request, response: Response) { + // validate body + const result = validationResult(request); + if (!result.isEmpty()) { + return response + .status(400) + .json(Responses.GetInvalidResponse(undefined, request.body.secret, result.array()[0].msg)); + } - options.network = options?.network || ((did!.split(':'))[2] as NetworkType) - await CheqdRegistrar.instance.connect(options) - const result = await CheqdRegistrar.instance.deactivate(signInputs, payload, versionId) - if ( result.code == 0 ) { - return response.status(201).json(Responses.GetSuccessResponse( - jobId, - {id: did}, - secret - )) - } else { - return response.status(400).json(Responses.GetInvalidResponse( - {id: did}, - secret, - JSON.stringify(result.rawLog) - )) - } - } catch (error) { - return response.status(500).json(Responses.GetInternalErrorResponse({id: did}, secret, error as string)) - } - } -} \ No newline at end of file + let { jobId, secret = {}, options = {}, did } = request.body as IDIDUpdateRequest; + + let payload: DIDDocument; + let versionId: string; + try { + if (jobId) { + const storeData = LocalStore.instance.getItem(jobId); + if (!storeData) { + return response.status(400).json(Responses.GetJobExpiredResponse(jobId)); + } else if (storeData.state == IState.Finished) { + return response + .status(201) + .json(Responses.GetSuccessResponse(jobId, storeData.didDocument, secret)); + } + + payload = storeData.didDocument; + did = storeData.didDocument.id; + versionId = storeData.versionId; + } else { + jobId = v4(); + versionId = options.versionId || v4(); + // check if did is registered on the ledger + let resolvedDocument = await CheqdResolver(did); + + if (!resolvedDocument?.didDocument) { + return response + .status(400) + .send(Responses.GetInvalidResponse({ id: did }, secret, Messages.DidNotFound)); + } + + payload = { + verificationMethod: resolvedDocument.didDocument.verificationMethod, + id: resolvedDocument.didDocument.id, + }; + } + + let signInputs: SignInfo[]; + if (secret.signingResponse) { + signInputs = convertToSignInfo(secret.signingResponse); + } else { + LocalStore.instance.setItem(jobId, { didDocument: payload, state: IState.Action, versionId }); + return response + .status(200) + .json(Responses.GetDeactivateDidSignatureResponse(jobId, payload, versionId)); + } + + options.network = options?.network || (did!.split(':')[2] as NetworkType); + await CheqdRegistrar.instance.connect(options); + const result = await CheqdRegistrar.instance.deactivate(signInputs, payload, versionId); + if (result.code == 0) { + return response.status(201).json(Responses.GetSuccessResponse(jobId, { id: did }, secret)); + } else { + return response + .status(400) + .json(Responses.GetInvalidResponse({ id: did }, secret, JSON.stringify(result.rawLog))); + } + } catch (error) { + return response.status(500).json(Responses.GetInternalErrorResponse({ id: did }, secret, error as string)); + } + } +} diff --git a/src/controllers/resource.ts b/src/controllers/resource.ts index 7c025ee..68ce5d9 100644 --- a/src/controllers/resource.ts +++ b/src/controllers/resource.ts @@ -1,124 +1,142 @@ -import type { Request, Response } from 'express' -import type { MsgCreateResourcePayload } from '@cheqd/ts-proto/cheqd/resource/v2' -import type { SignInfo } from '@cheqd/ts-proto/cheqd/did/v2' +import type { Request, Response } from 'express'; +import type { MsgCreateResourcePayload } from '@cheqd/ts-proto/cheqd/resource/v2'; +import type { SignInfo } from '@cheqd/ts-proto/cheqd/did/v2'; -import { check, param, validationResult } from 'express-validator' -import { v4 } from 'uuid' -import { fromString } from 'uint8arrays' +import { check, param, validationResult } from 'express-validator'; +import { v4 } from 'uuid'; +import { fromString } from 'uint8arrays'; -import { CheqdRegistrar, CheqdResolver, NetworkType } from '../service/cheqd' -import { IResourceCreateRequest, IState } from '../types/types' -import { Messages } from '../types/constants' -import { convertToSignInfo } from '../helpers/helpers' -import { Responses } from '../helpers/response' -import { LocalStore } from './store' +import { CheqdRegistrar, CheqdResolver, NetworkType } from '../service/cheqd'; +import { IResourceCreateRequest, IState } from '../types/types'; +import { Messages } from '../types/constants'; +import { convertToSignInfo } from '../helpers/helpers'; +import { Responses } from '../helpers/response'; +import { LocalStore } from './store'; export class ResourceController { - public static createValidator = [ - param('did').exists().isString().contains('did:cheqd').withMessage(Messages.InvalidDid), - check('jobId').custom((value, {req})=>{ - if(!value && !(req.body.name && req.body.type && req.body.data)) return false - return true - }).withMessage('name, type and data are required'), - check('name').optional().isString().withMessage(Messages.Invalid), - check('type').optional().isString().withMessage(Messages.Invalid), - check('data').optional().isString().withMessage(Messages.Invalid), - check('alsoKnownAs').optional().isArray().withMessage(Messages.Invalid), - check('alsoKnownAs.*.uri').isString().withMessage(Messages.Invalid), - check('alsoKnownAs.*.description').isString().withMessage(Messages.Invalid) - ] + public static createValidator = [ + param('did').exists().isString().contains('did:cheqd').withMessage(Messages.InvalidDid), + check('jobId') + .custom((value, { req }) => { + if (!value && !(req.body.name && req.body.type && req.body.data)) return false; + return true; + }) + .withMessage('name, type and data are required'), + check('name').optional().isString().withMessage(Messages.Invalid), + check('type').optional().isString().withMessage(Messages.Invalid), + check('data').optional().isString().withMessage(Messages.Invalid), + check('alsoKnownAs').optional().isArray().withMessage(Messages.Invalid), + check('alsoKnownAs.*.uri').isString().withMessage(Messages.Invalid), + check('alsoKnownAs.*.description').isString().withMessage(Messages.Invalid), + ]; - public async create(request: Request, response: Response) { + public async create(request: Request, response: Response) { + const result = validationResult(request); + if (!result.isEmpty()) { + return response + .status(400) + .json(Responses.GetInvalidResourceResponse({}, request.body.secret, result.array()[0].msg)); + } - const result = validationResult(request); - if (!result.isEmpty()) { - return response.status(400).json(Responses.GetInvalidResourceResponse({}, request.body.secret, result.array()[0].msg)) - } + const { did } = request.params; + let { + jobId, + data, + name, + type, + alsoKnownAs, + version, + secret = {}, + options = {}, + } = request.body as IResourceCreateRequest; - const { did } = request.params - let { jobId, data, name, type, alsoKnownAs, version, secret={}, options={} } = request.body as IResourceCreateRequest - - let resourcePayload: Partial = {} - try { - // check if did is registered on the ledger - let resolvedDocument = await CheqdResolver(did) - if(!resolvedDocument?.didDocument || resolvedDocument.didDocumentMetadata.deactivated) { - return response.status(400).send(Responses.GetInvalidResponse( - {id: did}, - secret, - Messages.DidNotFound - )) - } else { - resolvedDocument = resolvedDocument.didDocument - } - - // Validate and get store data if any - if(jobId) { - const storeData = LocalStore.instance.getResource(jobId) - if(!storeData) { - return response.status(400).json(Responses.GetJobExpiredResponse(jobId)) - } else if (storeData.state == IState.Finished) { - return response.status(201).json({ - jobId, - resourceState: { - resourceId: storeData.resource.id, - state: IState.Finished, - secret, - resource: storeData.resource - } - }) - } + let resourcePayload: Partial = {}; + try { + // check if did is registered on the ledger + let resolvedDocument = await CheqdResolver(did); + if (!resolvedDocument?.didDocument || resolvedDocument.didDocumentMetadata.deactivated) { + return response + .status(400) + .send(Responses.GetInvalidResponse({ id: did }, secret, Messages.DidNotFound)); + } else { + resolvedDocument = resolvedDocument.didDocument; + } - resourcePayload = storeData.resource - resourcePayload.data = new Uint8Array(Object.values(resourcePayload.data!)) - } else if (!data) { - return response.status(400).json(Responses.GetInvalidResourceResponse({}, secret, Messages.InvalidResource)) - } else { - jobId = v4() + // Validate and get store data if any + if (jobId) { + const storeData = LocalStore.instance.getResource(jobId); + if (!storeData) { + return response.status(400).json(Responses.GetJobExpiredResponse(jobId)); + } else if (storeData.state == IState.Finished) { + return response.status(201).json({ + jobId, + resourceState: { + resourceId: storeData.resource.id, + state: IState.Finished, + secret, + resource: storeData.resource, + }, + }); + } - resourcePayload = { - collectionId: did.split(':').pop()!, - id: v4(), - name, - resourceType: type, - data: fromString(data, 'base64'), - version, - alsoKnownAs - } - } - - let signInputs: SignInfo[] - - if (secret.signingResponse) { - signInputs = convertToSignInfo(secret.signingResponse) - } else { - LocalStore.instance.setResource(jobId, {resource: resourcePayload, state: IState.Action}) - return response.status(200).json(Responses.GetResourceActionSignatureResponse( - jobId, - resolvedDocument.verificationMethod, - resourcePayload - )) - } + resourcePayload = storeData.resource; + resourcePayload.data = new Uint8Array(Object.values(resourcePayload.data!)); + } else if (!data) { + return response + .status(400) + .json(Responses.GetInvalidResourceResponse({}, secret, Messages.InvalidResource)); + } else { + jobId = v4(); - options.network = options.network || (did.split(':'))[2] as NetworkType - await CheqdRegistrar.instance.connect(options) - const result = await CheqdRegistrar.instance.createResource(signInputs, resourcePayload) - if ( result.code == 0 ) { - return response.status(201).json(Responses.GetResourceSuccessResponse(jobId, secret, resourcePayload)) - } else { - return response.status(400).json(Responses.GetInvalidResourceResponse(resourcePayload, secret, Messages.InvalidResource)) - } - } catch (error) { - return response.status(500).json({ - jobId, - resourceState: { - state: IState.Failed, - reason: Messages.Internal, - description: Messages.TryAgain + error, - secret, - resourcePayload - } - }) - } - } -} \ No newline at end of file + resourcePayload = { + collectionId: did.split(':').pop()!, + id: v4(), + name, + resourceType: type, + data: fromString(data, 'base64'), + version, + alsoKnownAs, + }; + } + + let signInputs: SignInfo[]; + + if (secret.signingResponse) { + signInputs = convertToSignInfo(secret.signingResponse); + } else { + LocalStore.instance.setResource(jobId, { resource: resourcePayload, state: IState.Action }); + return response + .status(200) + .json( + Responses.GetResourceActionSignatureResponse( + jobId, + resolvedDocument.verificationMethod, + resourcePayload + ) + ); + } + + options.network = options.network || (did.split(':')[2] as NetworkType); + await CheqdRegistrar.instance.connect(options); + const result = await CheqdRegistrar.instance.createResource(signInputs, resourcePayload); + if (result.code == 0) { + return response.status(201).json(Responses.GetResourceSuccessResponse(jobId, secret, resourcePayload)); + } else { + return response + .status(400) + .json(Responses.GetInvalidResourceResponse(resourcePayload, secret, Messages.InvalidResource)); + } + } catch (error) { + return response.status(500).json({ + jobId, + resourceState: { + state: IState.Failed, + reason: Messages.Internal, + description: Messages.TryAgain + error, + secret, + resourcePayload, + }, + }); + } + } +} diff --git a/src/controllers/store.ts b/src/controllers/store.ts index 1a1fd7b..2b3e83c 100644 --- a/src/controllers/store.ts +++ b/src/controllers/store.ts @@ -1,51 +1,48 @@ -import type { DIDDocument } from '@cheqd/sdk' -import type { MsgCreateResourcePayload } from '@cheqd/ts-proto/cheqd/resource/v2' +import type { DIDDocument } from '@cheqd/sdk'; +import type { MsgCreateResourcePayload } from '@cheqd/ts-proto/cheqd/resource/v2'; -import NodeCache from 'node-cache' -import * as dotenv from 'dotenv' +import NodeCache from 'node-cache'; +import * as dotenv from 'dotenv'; -import { IState } from '../types/types' +import { IState } from '../types/types'; -dotenv.config() +dotenv.config(); -let { - LOCAL_STORE_TTL -} = process.env +let { LOCAL_STORE_TTL } = process.env; export class LocalStore { - private cache: NodeCache + private cache: NodeCache; - public static instance = new LocalStore() + public static instance = new LocalStore(); - constructor() { - this.cache = new NodeCache() - } + constructor() { + this.cache = new NodeCache(); + } - setItem(key: string, data: IDidDocData) { - this.cache.set(key, data, LOCAL_STORE_TTL || 600) - } + setItem(key: string, data: IDidDocData) { + this.cache.set(key, data, LOCAL_STORE_TTL || 600); + } - getItem(key: string) { - return this.cache.get(key) as IDidDocData | undefined - } + getItem(key: string) { + return this.cache.get(key) as IDidDocData | undefined; + } - setResource(key: string, data: IResourceData) { - this.cache.set(key, data, LOCAL_STORE_TTL || 600) - } + setResource(key: string, data: IResourceData) { + this.cache.set(key, data, LOCAL_STORE_TTL || 600); + } - getResource(key: string) { - return this.cache.get(key) as IResourceData | undefined - } + getResource(key: string) { + return this.cache.get(key) as IResourceData | undefined; + } } - export interface IDidDocData { - didDocument: DIDDocument - state: IState - versionId: string + didDocument: DIDDocument; + state: IState; + versionId: string; } export interface IResourceData { - resource: Partial - state: IState -} \ No newline at end of file + resource: Partial; + state: IState; +} diff --git a/src/helpers/helpers.ts b/src/helpers/helpers.ts index 306c10e..4b661eb 100644 --- a/src/helpers/helpers.ts +++ b/src/helpers/helpers.ts @@ -1,54 +1,58 @@ -import type { DIDDocument, SpecValidationResult } from '@cheqd/sdk' -import type { SignInfo } from '@cheqd/ts-proto/cheqd/did/v2' +import type { DIDDocument, SpecValidationResult } from '@cheqd/sdk'; +import type { SignInfo } from '@cheqd/ts-proto/cheqd/did/v2'; -import { VerificationMethods } from '@cheqd/sdk' -import { base64ToBytes } from 'did-jwt' +import { VerificationMethods } from '@cheqd/sdk'; +import { base64ToBytes } from 'did-jwt'; -import { ISignInfo } from '../types/types' +import { ISignInfo } from '../types/types'; export function convertToSignInfo(payload: ISignInfo[]): SignInfo[] { - return payload.map((value)=>{ - return { - verificationMethodId: value.verificationMethodId, - signature: base64ToBytes(value.signature) - } - }) + return payload.map((value) => { + return { + verificationMethodId: value.verificationMethodId, + signature: base64ToBytes(value.signature), + }; + }); } -export function validateSpecCompliantPayload(didDocument: DIDDocument) : SpecValidationResult { - // id is required, validated on both compile and runtime - if (!didDocument.id) return { valid: false, error: 'id is required' } - - // verificationMethod is required - if (!didDocument.verificationMethod) return { valid: false, error: 'verificationMethod is required' } - - // verificationMethod must be an array - if (!Array.isArray(didDocument.verificationMethod)) return { valid: false, error: 'verificationMethod must be an array' } - - // verificationMethod must be not be empty - if (!didDocument.verificationMethod.length) return { valid: false, error: 'verificationMethod must be not be empty' } - - // verificationMethod types must be supported - const isValidVerificationMethod = didDocument.verificationMethod.every((vm) => { - switch (vm.type) { - case VerificationMethods.Ed255192020: - return vm.publicKeyMultibase != null - case VerificationMethods.JWK: - return vm.publicKeyJwk != null - case VerificationMethods.Ed255192018: - return vm.publicKeyBase58 != null - default: - return false - } - }) - - if(!isValidVerificationMethod) return { valid: false, error: 'verificationMethod publicKey is Invalid'} - - const isValidService = didDocument.service ? didDocument?.service?.every((s) => { - return Array.isArray(s?.serviceEndpoint) && s?.id && s?.type - }) : true - - if(!isValidService) return { valid: false, error: 'Service is Invalid'} - - return { valid: true } as SpecValidationResult +export function validateSpecCompliantPayload(didDocument: DIDDocument): SpecValidationResult { + // id is required, validated on both compile and runtime + if (!didDocument.id) return { valid: false, error: 'id is required' }; + + // verificationMethod is required + if (!didDocument.verificationMethod) return { valid: false, error: 'verificationMethod is required' }; + + // verificationMethod must be an array + if (!Array.isArray(didDocument.verificationMethod)) + return { valid: false, error: 'verificationMethod must be an array' }; + + // verificationMethod must be not be empty + if (!didDocument.verificationMethod.length) + return { valid: false, error: 'verificationMethod must be not be empty' }; + + // verificationMethod types must be supported + const isValidVerificationMethod = didDocument.verificationMethod.every((vm) => { + switch (vm.type) { + case VerificationMethods.Ed255192020: + return vm.publicKeyMultibase != null; + case VerificationMethods.JWK: + return vm.publicKeyJwk != null; + case VerificationMethods.Ed255192018: + return vm.publicKeyBase58 != null; + default: + return false; + } + }); + + if (!isValidVerificationMethod) return { valid: false, error: 'verificationMethod publicKey is Invalid' }; + + const isValidService = didDocument.service + ? didDocument?.service?.every((s) => { + return Array.isArray(s?.serviceEndpoint) && s?.id && s?.type; + }) + : true; + + if (!isValidService) return { valid: false, error: 'Service is Invalid' }; + + return { valid: true } as SpecValidationResult; } diff --git a/src/helpers/response.ts b/src/helpers/response.ts index d8af275..e64ace2 100644 --- a/src/helpers/response.ts +++ b/src/helpers/response.ts @@ -1,195 +1,203 @@ -import type { DIDDocument, VerificationMethod } from '@cheqd/sdk' +import type { DIDDocument, VerificationMethod } from '@cheqd/sdk'; -import { DIDModule } from '@cheqd/sdk' -import { MsgCreateDidDocPayload, MsgDeactivateDidDocPayload } from '@cheqd/ts-proto/cheqd/did/v2' -import { MsgCreateResourcePayload } from '@cheqd/ts-proto/cheqd/resource/v2' +import { DIDModule } from '@cheqd/sdk'; +import { MsgCreateDidDocPayload, MsgDeactivateDidDocPayload } from '@cheqd/ts-proto/cheqd/did/v2'; +import { MsgCreateResourcePayload } from '@cheqd/ts-proto/cheqd/resource/v2'; -import { toString } from 'uint8arrays' +import { toString } from 'uint8arrays'; -import { Messages } from '../types/constants' -import { IAction, IState } from '../types/types' +import { Messages } from '../types/constants'; +import { IAction, IState } from '../types/types'; export class Responses { - static GetSuccessResponse(jobId: string, didDocument: DIDDocument, secret: Record) { - return { - jobId, - didState: { - did: didDocument.id, - state: 'finished', - secret, - didDocument - } - } - } - - static async GetDIDActionSignatureResponse(jobId: string, didPayload: DIDDocument, versionId: string) { - const { protobufVerificationMethod, protobufService } = await DIDModule.validateSpecCompliantPayload(didPayload) - const signingRequest = didPayload.verificationMethod!.map((method)=> { - return { - kid: method.id, - type: method.type, - alg: 'EdDSA', - serializedPayload: toString( - ( - MsgCreateDidDocPayload.encode(MsgCreateDidDocPayload.fromPartial({ - context: didPayload?.['@context'], - id: didPayload.id, - controller: didPayload.controller, - verificationMethod: protobufVerificationMethod, - authentication: didPayload.authentication, - assertionMethod: didPayload.assertionMethod, - capabilityInvocation: didPayload.capabilityInvocation, - capabilityDelegation: didPayload.capabilityDelegation, - keyAgreement: didPayload.keyAgreement, - service: protobufService, - alsoKnownAs: didPayload.alsoKnownAs, - versionId: versionId - })).finish() - ), - 'base64pad' - ) - } - }) - - return { - jobId, - didState: { - did: didPayload.id, - state: IState.Action, - action: IAction.GetSignature, - description: Messages.GetSignature, - signingRequest, - secret: { - signingResponse: [Messages.SigingResponse] - } - } - } - } - - static GetDeactivateDidSignatureResponse(jobId: string, payload: DIDDocument, versionId: string) { - const signingRequest = payload.verificationMethod!.map((method)=> { - return { - kid: method.id, - type: method.type, - alg: 'EdDSA', - serializedPayload: toString( - ( - MsgDeactivateDidDocPayload.encode({ - id: payload.id, - versionId: versionId - }).finish() - ), - 'base64pad' - ) - } - }) - - return { - jobId, - didState: { - did: payload.id, - state: IState.Action, - action: IAction.GetSignature, - description: Messages.GetSignature, - signingRequest, - secret: { - signingResponse: [Messages.SigingResponse] - } - } - } - } - - static GetResourceActionSignatureResponse(jobId: string, verificationMethod: VerificationMethod[], resource: Partial) { - const signingRequest = verificationMethod.map((method)=> { - return { - kid: method.id, - type: method.type, - alg: 'EdDSA', - serializedPayload: toString( - ( - MsgCreateResourcePayload.encode(MsgCreateResourcePayload.fromPartial(resource)).finish() - ), - 'base64pad' - ) - } - }) - - return { - jobId, - resourceState: { - did: resource.collectionId, - state: IState.Action, - action: IAction.GetSignature, - description: Messages.GetSignature, - signingRequest, - secret: { - signingResponse: [Messages.SigingResponse] - } - } - } - } - - static GetInvalidResponse(didDocument: DIDDocument | undefined, secret: Record = {}, error: string) { - return { - jobId: null, - didState: { - did: didDocument?.id || '', - state: IState.Failed, - reason: Messages.Invalid, - description: Messages.Invalid + ': ' + error, - secret, - didDocument - } - } - } - - static GetInternalErrorResponse(didDocument: DIDDocument | undefined, secret: Record, error?: string) { - return { - jobId: null, - didState: { - state: IState.Failed, - reason: Messages.Internal, - description: Messages.TryAgain + ': ' + error, - secret, - didDocument - } - } - } - - static GetJobExpiredResponse(jobId: string) { - return { - jobId, - didState: { - state: IState.Failed, - reason: Messages.InvalidJob - } - } - } - - static GetResourceSuccessResponse(jobId: string, secret: Record, resourcePayload: Partial) { - return { - jobId, - resourceState: { - resourceId: resourcePayload.id || '', - state: IState.Finished, - secret, - resource: resourcePayload - } - } - } - - static GetInvalidResourceResponse(resourcePayload: Partial = {}, secret: Record = {}, error: string) { - return { - jobId: null, - resourceState: { - resourceId: resourcePayload.id, - state: IState.Failed, - reason: Messages.Invalid, - description: Messages.Invalid + ': ' + error, - secret, - resourcePayload - } - } - } - + static GetSuccessResponse(jobId: string, didDocument: DIDDocument, secret: Record) { + return { + jobId, + didState: { + did: didDocument.id, + state: 'finished', + secret, + didDocument, + }, + }; + } + + static async GetDIDActionSignatureResponse(jobId: string, didPayload: DIDDocument, versionId: string) { + const { protobufVerificationMethod, protobufService } = + await DIDModule.validateSpecCompliantPayload(didPayload); + const signingRequest = didPayload.verificationMethod!.map((method) => { + return { + kid: method.id, + type: method.type, + alg: 'EdDSA', + serializedPayload: toString( + MsgCreateDidDocPayload.encode( + MsgCreateDidDocPayload.fromPartial({ + context: didPayload?.['@context'], + id: didPayload.id, + controller: didPayload.controller, + verificationMethod: protobufVerificationMethod, + authentication: didPayload.authentication, + assertionMethod: didPayload.assertionMethod, + capabilityInvocation: didPayload.capabilityInvocation, + capabilityDelegation: didPayload.capabilityDelegation, + keyAgreement: didPayload.keyAgreement, + service: protobufService, + alsoKnownAs: didPayload.alsoKnownAs, + versionId: versionId, + }) + ).finish(), + 'base64pad' + ), + }; + }); + + return { + jobId, + didState: { + did: didPayload.id, + state: IState.Action, + action: IAction.GetSignature, + description: Messages.GetSignature, + signingRequest, + secret: { + signingResponse: [Messages.SigingResponse], + }, + }, + }; + } + + static GetDeactivateDidSignatureResponse(jobId: string, payload: DIDDocument, versionId: string) { + const signingRequest = payload.verificationMethod!.map((method) => { + return { + kid: method.id, + type: method.type, + alg: 'EdDSA', + serializedPayload: toString( + MsgDeactivateDidDocPayload.encode({ + id: payload.id, + versionId: versionId, + }).finish(), + 'base64pad' + ), + }; + }); + + return { + jobId, + didState: { + did: payload.id, + state: IState.Action, + action: IAction.GetSignature, + description: Messages.GetSignature, + signingRequest, + secret: { + signingResponse: [Messages.SigingResponse], + }, + }, + }; + } + + static GetResourceActionSignatureResponse( + jobId: string, + verificationMethod: VerificationMethod[], + resource: Partial + ) { + const signingRequest = verificationMethod.map((method) => { + return { + kid: method.id, + type: method.type, + alg: 'EdDSA', + serializedPayload: toString( + MsgCreateResourcePayload.encode(MsgCreateResourcePayload.fromPartial(resource)).finish(), + 'base64pad' + ), + }; + }); + + return { + jobId, + resourceState: { + did: resource.collectionId, + state: IState.Action, + action: IAction.GetSignature, + description: Messages.GetSignature, + signingRequest, + secret: { + signingResponse: [Messages.SigingResponse], + }, + }, + }; + } + + static GetInvalidResponse(didDocument: DIDDocument | undefined, secret: Record = {}, error: string) { + return { + jobId: null, + didState: { + did: didDocument?.id || '', + state: IState.Failed, + reason: Messages.Invalid, + description: Messages.Invalid + ': ' + error, + secret, + didDocument, + }, + }; + } + + static GetInternalErrorResponse(didDocument: DIDDocument | undefined, secret: Record, error?: string) { + return { + jobId: null, + didState: { + state: IState.Failed, + reason: Messages.Internal, + description: Messages.TryAgain + ': ' + error, + secret, + didDocument, + }, + }; + } + + static GetJobExpiredResponse(jobId: string) { + return { + jobId, + didState: { + state: IState.Failed, + reason: Messages.InvalidJob, + }, + }; + } + + static GetResourceSuccessResponse( + jobId: string, + secret: Record, + resourcePayload: Partial + ) { + return { + jobId, + resourceState: { + resourceId: resourcePayload.id || '', + state: IState.Finished, + secret, + resource: resourcePayload, + }, + }; + } + + static GetInvalidResourceResponse( + resourcePayload: Partial = {}, + secret: Record = {}, + error: string + ) { + return { + jobId: null, + resourceState: { + resourceId: resourcePayload.id, + state: IState.Failed, + reason: Messages.Invalid, + description: Messages.Invalid + ': ' + error, + secret, + resourcePayload, + }, + }; + } } diff --git a/src/index.ts b/src/index.ts index 4a510c9..5cea66f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,30 +1,30 @@ -import * as http from 'http' -import App from './app' +import * as http from 'http'; +import App from './app'; -require('dotenv').config() +require('dotenv').config(); -const port = process.env.PORT || 3000 -App.set('port', port) +const port = process.env.PORT || 3000; +App.set('port', port); -const server = http.createServer(App) -server.listen(port) -server.on('error', onError) +const server = http.createServer(App); +server.listen(port); +server.on('error', onError); function onError(error: NodeJS.ErrnoException): void { - if (error.syscall !== 'listen') { - throw error - } - const bind = (typeof port === 'string') ? 'Pipe ' + port : 'Port ' + port - switch (error.code) { - case 'EACCES': - console.error(`${bind} requires elevated privileges`) - process.exit(1) - break - case 'EADDRINUSE': - console.error(`${bind} is already in use`) - process.exit(1) - break - default: - throw error - } -} \ No newline at end of file + if (error.syscall !== 'listen') { + throw error; + } + const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; + switch (error.code) { + case 'EACCES': + console.error(`${bind} requires elevated privileges`); + process.exit(1); + break; + case 'EADDRINUSE': + console.error(`${bind} is already in use`); + process.exit(1); + break; + default: + throw error; + } +} diff --git a/src/service/cheqd.ts b/src/service/cheqd.ts index 61b3677..ce3666f 100644 --- a/src/service/cheqd.ts +++ b/src/service/cheqd.ts @@ -1,123 +1,108 @@ -import type { CheqdSDK, AbstractCheqdSDKModule, ICheqdSDKOptions, DIDDocument, DidStdFee } from '@cheqd/sdk' +import type { CheqdSDK, AbstractCheqdSDKModule, ICheqdSDKOptions, DIDDocument, DidStdFee } from '@cheqd/sdk'; -import { createCheqdSDK, DIDModule, ResourceModule } from '@cheqd/sdk' -import { MsgCreateResourcePayload } from '@cheqd/ts-proto/cheqd/resource/v2' -import { SignInfo } from '@cheqd/ts-proto/cheqd/did/v2' -import { DirectSecp256k1HdWallet } from '@cosmjs/proto-signing' -import * as dotenv from 'dotenv' -import fetch from 'node-fetch' +import { createCheqdSDK, DIDModule, ResourceModule } from '@cheqd/sdk'; +import { MsgCreateResourcePayload } from '@cheqd/ts-proto/cheqd/resource/v2'; +import { SignInfo } from '@cheqd/ts-proto/cheqd/did/v2'; +import { DirectSecp256k1HdWallet } from '@cosmjs/proto-signing'; +import * as dotenv from 'dotenv'; +import fetch from 'node-fetch'; -import { Messages } from '../types/constants' -import { IOptions } from '../types/types' +import { Messages } from '../types/constants'; +import { IOptions } from '../types/types'; -dotenv.config() +dotenv.config(); -let { - FEE_PAYER_TESTNET_MNEMONIC, - FEE_PAYER_MAINNET_MNEMONIC -} = process.env +let { FEE_PAYER_TESTNET_MNEMONIC, FEE_PAYER_MAINNET_MNEMONIC } = process.env; export enum DefaultRPCUrl { - Mainnet = 'https://rpc.cheqd.net', - Testnet = 'https://rpc.cheqd.network' + Mainnet = 'https://rpc.cheqd.net', + Testnet = 'https://rpc.cheqd.network', } export enum NetworkType { - Mainnet = "mainnet", - Testnet = "testnet" + Mainnet = 'mainnet', + Testnet = 'testnet', } export enum DefaultResolverUrl { - Cheqd = "https://resolver.cheqd.net" + Cheqd = 'https://resolver.cheqd.net', } export class CheqdRegistrar { - private sdk?: CheqdSDK - private fee?: DidStdFee - - public static instance = new CheqdRegistrar() - - public async connect(options: IOptions) { - if(options.network === NetworkType.Mainnet && !FEE_PAYER_MAINNET_MNEMONIC) { - throw new Error('No signer provided') - } else if(!FEE_PAYER_TESTNET_MNEMONIC) { - FEE_PAYER_TESTNET_MNEMONIC = Messages.TestnetFaucet - } - - const sdkOptions: ICheqdSDKOptions = { - modules: [DIDModule as unknown as AbstractCheqdSDKModule, ResourceModule as unknown as AbstractCheqdSDKModule], - rpcUrl: options.rpcUrl ? options.rpcUrl : (options.network === NetworkType.Testnet ? DefaultRPCUrl.Testnet : DefaultRPCUrl.Mainnet), - wallet: await DirectSecp256k1HdWallet.fromMnemonic(options.network === NetworkType.Mainnet ? FEE_PAYER_MAINNET_MNEMONIC : FEE_PAYER_TESTNET_MNEMONIC, {prefix: 'cheqd'}) - } - - this.sdk = await createCheqdSDK(sdkOptions) - this.fee = options.fee - - } - - public forceGetSdk(): CheqdSDK{ - if(!this.sdk) { - throw new Error('Cannot connect when your offline ...') - } - return this.sdk - } - - public async create(signInputs: SignInfo[], didPayload: DIDDocument, versionId: string | undefined) { - return await this.forceGetSdk() - .createDidDocTx( - signInputs, - didPayload, - '', - this?.fee, - undefined, - versionId, - { sdk: this.forceGetSdk() } - ) - } - - public async update(signInputs: SignInfo[], didPayload: DIDDocument, versionId: string | undefined) { - return await this.forceGetSdk() - .updateDidDocTx( - signInputs, - didPayload, - '', - this?.fee, - undefined, - versionId, - { sdk: this.forceGetSdk() } - ) - } - - public async deactivate(signInputs: SignInfo[], didPayload: DIDDocument, versionId: string | undefined) { - return await this.forceGetSdk() - .deactivateDidDocTx( - signInputs, - didPayload, - '', - this?.fee, - undefined, - versionId, - { sdk: this.forceGetSdk() } - ) - } - - public async createResource(signInputs: SignInfo[], resourcePayload: Partial) { - return await this.forceGetSdk().createLinkedResourceTx( - signInputs, - resourcePayload, - '', - this?.fee, - undefined, - { sdk: this.forceGetSdk() } - ) - } - + private sdk?: CheqdSDK; + private fee?: DidStdFee; + + public static instance = new CheqdRegistrar(); + + public async connect(options: IOptions) { + if (options.network === NetworkType.Mainnet && !FEE_PAYER_MAINNET_MNEMONIC) { + throw new Error('No signer provided'); + } else if (!FEE_PAYER_TESTNET_MNEMONIC) { + FEE_PAYER_TESTNET_MNEMONIC = Messages.TestnetFaucet; + } + + const sdkOptions: ICheqdSDKOptions = { + modules: [ + DIDModule as unknown as AbstractCheqdSDKModule, + ResourceModule as unknown as AbstractCheqdSDKModule, + ], + rpcUrl: options.rpcUrl + ? options.rpcUrl + : options.network === NetworkType.Testnet + ? DefaultRPCUrl.Testnet + : DefaultRPCUrl.Mainnet, + wallet: await DirectSecp256k1HdWallet.fromMnemonic( + options.network === NetworkType.Mainnet ? FEE_PAYER_MAINNET_MNEMONIC : FEE_PAYER_TESTNET_MNEMONIC, + { prefix: 'cheqd' } + ), + }; + + this.sdk = await createCheqdSDK(sdkOptions); + this.fee = options.fee; + } + + public forceGetSdk(): CheqdSDK { + if (!this.sdk) { + throw new Error('Cannot connect when your offline ...'); + } + return this.sdk; + } + + public async create(signInputs: SignInfo[], didPayload: DIDDocument, versionId: string | undefined) { + return await this.forceGetSdk().createDidDocTx(signInputs, didPayload, '', this?.fee, undefined, versionId, { + sdk: this.forceGetSdk(), + }); + } + + public async update(signInputs: SignInfo[], didPayload: DIDDocument, versionId: string | undefined) { + return await this.forceGetSdk().updateDidDocTx(signInputs, didPayload, '', this?.fee, undefined, versionId, { + sdk: this.forceGetSdk(), + }); + } + + public async deactivate(signInputs: SignInfo[], didPayload: DIDDocument, versionId: string | undefined) { + return await this.forceGetSdk().deactivateDidDocTx( + signInputs, + didPayload, + '', + this?.fee, + undefined, + versionId, + { sdk: this.forceGetSdk() } + ); + } + + public async createResource(signInputs: SignInfo[], resourcePayload: Partial) { + return await this.forceGetSdk().createLinkedResourceTx(signInputs, resourcePayload, '', this?.fee, undefined, { + sdk: this.forceGetSdk(), + }); + } } export async function CheqdResolver(id: string) { - const result = await fetch(`${DefaultResolverUrl.Cheqd}/1.0/identifiers/${id}`) - if (!result.ok) { - return null - } - return (await result.json() as any) -} \ No newline at end of file + const result = await fetch(`${DefaultResolverUrl.Cheqd}/1.0/identifiers/${id}`); + if (!result.ok) { + return null; + } + return (await result.json()) as any; +} diff --git a/src/types/constants.ts b/src/types/constants.ts index cb87d55..ff13921 100644 --- a/src/types/constants.ts +++ b/src/types/constants.ts @@ -1,16 +1,16 @@ export enum Messages { - Invalid = "Invalid payload", - Internal = "Internal server error", - TryAgain = "The operation failed due to an internal error. Please try again", - GetSignature = "Please sign the following payload with the keys in verificationMethod and Add the signingResponse in secret", - DidNotFound = "The DID does not exist or Deactivated", - InvalidDidDocument = "Provide a DID Document with atleast one valid verification method", - InvalidDid = "The DID is not valid", - InvalidJob = "The jobId is either expired or not found", - SecretValidation = "Provide either a valid KeyPair or Signature", - InvalidResource = "Resource Data is invalid", - TestnetFaucet = "sketch mountain erode window enact net enrich smoke claim kangaroo another visual write meat latin bacon pulp similar forum guilt father state erase bright", - SigingResponse = "e.g. { verificationMethodId: did:cheqd:testnet:qsqdcansoica#key-1, signature: aca1s12q14213casdvaadcfas }", - InvalidOptions = "The provided options are invalid", - InvalidSecret = "The provided secret is invalid" -} \ No newline at end of file + Invalid = 'Invalid payload', + Internal = 'Internal server error', + TryAgain = 'The operation failed due to an internal error. Please try again', + GetSignature = 'Please sign the following payload with the keys in verificationMethod and Add the signingResponse in secret', + DidNotFound = 'The DID does not exist or Deactivated', + InvalidDidDocument = 'Provide a DID Document with atleast one valid verification method', + InvalidDid = 'The DID is not valid', + InvalidJob = 'The jobId is either expired or not found', + SecretValidation = 'Provide either a valid KeyPair or Signature', + InvalidResource = 'Resource Data is invalid', + TestnetFaucet = 'sketch mountain erode window enact net enrich smoke claim kangaroo another visual write meat latin bacon pulp similar forum guilt father state erase bright', + SigingResponse = 'e.g. { verificationMethodId: did:cheqd:testnet:qsqdcansoica#key-1, signature: aca1s12q14213casdvaadcfas }', + InvalidOptions = 'The provided options are invalid', + InvalidSecret = 'The provided secret is invalid', +} diff --git a/src/types/environment.d.ts b/src/types/environment.d.ts index 05c2f3a..d1fb621 100644 --- a/src/types/environment.d.ts +++ b/src/types/environment.d.ts @@ -1,17 +1,17 @@ declare global { - namespace NodeJS { - interface ProcessEnv { - FEE_PAYER_TESTNET_MNEMONIC: string - FEE_PAYER_MAINNET_MNEMONIC: string - LOCAL_STORE_TTL: number - PORT: number - } - } + namespace NodeJS { + interface ProcessEnv { + FEE_PAYER_TESTNET_MNEMONIC: string; + FEE_PAYER_MAINNET_MNEMONIC: string; + LOCAL_STORE_TTL: number; + PORT: number; + } + } } -declare module "*.json" { - const value: any; - export default value; +declare module '*.json' { + const value: any; + export default value; } -export {} \ No newline at end of file +export {}; diff --git a/src/types/types.ts b/src/types/types.ts index e76fec0..06a23a0 100644 --- a/src/types/types.ts +++ b/src/types/types.ts @@ -1,89 +1,89 @@ -import type { DIDDocument, DidStdFee } from '@cheqd/sdk' -import type { AlternativeUri } from '@cheqd/ts-proto/cheqd/resource/v2' -import type { NetworkType } from '../service/cheqd' +import type { DIDDocument, DidStdFee } from '@cheqd/sdk'; +import type { AlternativeUri } from '@cheqd/ts-proto/cheqd/resource/v2'; +import type { NetworkType } from '../service/cheqd'; export interface IDIDCreateRequest { - jobId: string | null - options?: IOptions, - secret: ISecret - didDocument: DIDDocument + jobId: string | null; + options?: IOptions; + secret: ISecret; + didDocument: DIDDocument; } export interface IDIDUpdateRequest { - jobId: string | null - did: string - options: IOptions - secret: ISecret - didDocumentOperation: DidDocumentOperation[] - didDocument: DIDDocument[] + jobId: string | null; + did: string; + options: IOptions; + secret: ISecret; + didDocumentOperation: DidDocumentOperation[]; + didDocument: DIDDocument[]; } export interface IResourceCreateRequest { - jobId: string | null - secret: ISecret - options: IOptions - data: any, - name: string, - type: string, - mimeType: string, - alsoKnownAs?: AlternativeUri[], - version: string + jobId: string | null; + secret: ISecret; + options: IOptions; + data: any; + name: string; + type: string; + mimeType: string; + alsoKnownAs?: AlternativeUri[]; + version: string; } export enum DidDocumentOperation { - Set = 'setDidDocument', - Add = 'addToDidDocument', - Remove = 'removeFromDidDocument' + Set = 'setDidDocument', + Add = 'addToDidDocument', + Remove = 'removeFromDidDocument', } export interface IDIDDeactivateRequest { - jobId: string | null - did: string - options: Record, - secret: ISecret + jobId: string | null; + did: string; + options: Record; + secret: ISecret; } export interface IDidResponse { - jobId: null, - didState: IDidState, - didRegistratonMetatdata?: Record - didDocumentMetadata?: Record + jobId: null; + didState: IDidState; + didRegistratonMetatdata?: Record; + didDocumentMetadata?: Record; } export interface IDidState { - state: IState - action?: IAction - did: string - secret: ISecret - didDocument: DIDDocument + state: IState; + action?: IAction; + did: string; + secret: ISecret; + didDocument: DIDDocument; } export enum IState { - Init = "init", - Finished = "finished", - Action = "action", - Failed = "failed" + Init = 'init', + Finished = 'finished', + Action = 'action', + Failed = 'failed', } export enum IAction { - GetVerificationMethod = "getVerificationMethod", - GetSignature = "signPayload", - Redirect = "redirect", - Wait = "wait" + GetVerificationMethod = 'getVerificationMethod', + GetSignature = 'signPayload', + Redirect = 'redirect', + Wait = 'wait', } export interface ISignInfo { - verificationMethodId: string, - signature: string + verificationMethodId: string; + signature: string; } export interface ISecret { - signingResponse?: ISignInfo[] + signingResponse?: ISignInfo[]; } export interface IOptions { - network?: NetworkType, - rpcUrl?: string, - fee?: DidStdFee, - versionId?: string -} \ No newline at end of file + network?: NetworkType; + rpcUrl?: string; + fee?: DidStdFee; + versionId?: string; +}