Skip to content

Commit

Permalink
add veramo
Browse files Browse the repository at this point in the history
  • Loading branch information
shihjay2 committed Jan 2, 2025
1 parent b38f284 commit 90cdc28
Show file tree
Hide file tree
Showing 48 changed files with 29,049 additions and 24,787 deletions.
6 changes: 3 additions & 3 deletions components/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ const Layout = (props: any) => {
router.push("/");
};
return (
<Box sx={{ display: 'flex' }}>
(<Box sx={{ display: 'flex' }}>
{/* <CssBaseline /> */}
<AppBar position="fixed">
<Toolbar>
Expand Down Expand Up @@ -237,7 +237,7 @@ const Layout = (props: any) => {
</LayoutDialogTitle>
<DialogContent dividers>
<ul>
{content.map((text: string | number | boolean | React.ReactElement<any, string | React.JSXElementConstructor<any>> | React.ReactFragment | React.ReactPortal | null | undefined, index: any) => (
{content.map((text: string | number | boolean | React.ReactElement<any, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | React.ReactPortal | null | undefined, index: any) => (
<li key={index}>
<Typography gutterBottom>
{text}
Expand All @@ -251,7 +251,7 @@ const Layout = (props: any) => {
<DrawerHeader/>
{props.children}
</Main>
</Box>
</Box>)
);
}

Expand Down
22 changes: 22 additions & 0 deletions lib/cors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import cors, { CorsOptions, CorsOptionsDelegate } from 'cors'
import { NextApiRequest, NextApiResponse } from 'next'

// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function initMiddleware(middleware: typeof cors) {
return (req: NextApiRequest, res: NextApiResponse, options?: CorsOptions | CorsOptionsDelegate) =>
new Promise((resolve, reject) => {
middleware(options)(req, res, (result: Error | unknown) => {
if (result instanceof Error) {
return reject(result)
}

return resolve(result)
})
})
}

// You can read more about the available options here: https://github.com/expressjs/cors#configuration-options
const NextCors = initMiddleware(cors)

export default NextCors
5 changes: 2 additions & 3 deletions lib/createJWT.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as jose from 'jose';
import { randomBytes } from 'crypto';
import { nanoid } from 'nanoid';
import objectPath from 'object-path';

var user = process.env.COUCHDB_USER;
Expand Down Expand Up @@ -49,8 +49,7 @@ async function createJWT(doc: any) {
.setExpirationTime('6h')
.setSubject(doc.email)
.sign(rsaPrivateKey);
const token_endpoint_access_token = Buffer.from(randomBytes(16)).toString('base64url');
// const token_endpoint_access_token = randomBytes(16).toString('base64url');
const token_endpoint_access_token = nanoid(22);
const gnap = await nano.use("gnap");
objectPath.set(doc, 'token_endpoint_access_token', token_endpoint_access_token);
objectPath.set(doc, 'access_token.value', jwt);
Expand Down
88 changes: 88 additions & 0 deletions lib/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import {
ClaimTableEntry,
CredentialTableEntry,
DiffCallback,
PresentationTableEntry,
VeramoJsonCache,
VeramoJsonStore,
} from '@veramo/data-store-json'
import * as fs from 'fs'
import { IIdentifier, IMessage, ManagedKeyInfo } from '@veramo/core-types'
import { ManagedPrivateKey } from '@veramo/key-manager'

/**
* A utility class that shows how a File based JSON storage system could work.
* This is not recommended for large databases since every write operation rewrites the entire database.
*/
export class JsonFileStore implements VeramoJsonStore {
notifyUpdate: DiffCallback
dids: Record<string, IIdentifier>
keys: Record<string, ManagedKeyInfo>
privateKeys: Record<string, ManagedPrivateKey>
credentials: Record<string, CredentialTableEntry>
claims: Record<string, ClaimTableEntry>
presentations: Record<string, PresentationTableEntry>
messages: Record<string, IMessage>
private file: fs.PathLike

private constructor(file: fs.PathLike) {
this.file = file
this.notifyUpdate = async (oldState: VeramoJsonCache, newState: VeramoJsonCache) => {
await this.save(newState)
}
this.dids = {}
this.keys = {}
this.privateKeys = {}
this.credentials = {}
this.claims = {}
this.presentations = {}
this.messages = {}
}

public static async fromFile(file: fs.PathLike): Promise<JsonFileStore> {
const store = new JsonFileStore(file)
return await store.load()
}

private async load(): Promise<JsonFileStore> {

let cache: VeramoJsonCache
if (fs.existsSync(this.file)) {
try {
const rawCache = await fs.promises.readFile(this.file, { encoding: 'utf8' })
cache = JSON.parse(rawCache)
} catch (e: any) {
console.log(e)
cache = {}
}
} else {
cache = {}
}
; ({
dids: this.dids,
keys: this.keys,
credentials: this.credentials,
claims: this.claims,
presentations: this.presentations,
messages: this.messages,
privateKeys: this.privateKeys,
} = {
dids: {},
keys: {},
credentials: {},
claims: {},
presentations: {},
messages: {},
privateKeys: {},
...cache,
})
return this
}

private async save(newState: VeramoJsonCache): Promise<void> {
await fs.promises.writeFile(this.file, JSON.stringify(newState), {
encoding: 'utf8',
})
}

}
72 changes: 72 additions & 0 deletions lib/veramo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { createAgent } from '@veramo/core'
import { DIDManager } from '@veramo/did-manager'
import { KeyManager } from '@veramo/key-manager'
import { KeyManagementSystem, SecretBox } from '@veramo/kms-local'
import { CredentialPlugin } from '@veramo/credential-w3c'
import { EthrDIDProvider } from '@veramo/did-provider-ethr'
import { KeyDIDProvider } from '@veramo/did-provider-key'
import { DIDResolverPlugin } from '@veramo/did-resolver'
import { Resolver } from 'did-resolver'
import { getResolver as ethrDidResolver } from 'ethr-did-resolver'
import { getResolver as webDidResolver } from 'web-did-resolver'
import { DataStoreJson, KeyStoreJson, DIDStoreJson, PrivateKeyStoreJson } from '@veramo/data-store-json'
import fs from 'fs'
import { JsonFileStore } from './store'
import {
IDIDManager,
IKeyManager,
IResolver,
IDataStore,
ICredentialIssuer,
TAgent
} from '@veramo/core-types'
type ConfiguredAgent = TAgent<IDIDManager & IKeyManager & IResolver & IDataStore & ICredentialIssuer>

const INFURA_PROJECT_ID = process.env.INFURIA_API_KEY
// const INFURA_PROJECT_ID = '62cfe5babc774c1aaffa9eac6dbbf47f'
let KMS_SECRET_KEY = null
const kmsfile = '/data/kms';
const storefile = '/data/store.json';

if (fs.existsSync(kmsfile)) {
KMS_SECRET_KEY = fs.readFileSync(kmsfile, 'utf8')
} else {
KMS_SECRET_KEY = await SecretBox.createSecretKey()
fs.writeFileSync(kmsfile, KMS_SECRET_KEY)
}

const jsonFileStore = await JsonFileStore.fromFile(storefile)

export const agent: ConfiguredAgent = createAgent({
plugins: [
new KeyManager({
store: new KeyStoreJson(jsonFileStore),
kms: {
local: new KeyManagementSystem(new PrivateKeyStoreJson(jsonFileStore, new SecretBox(KMS_SECRET_KEY))),
}
}),
new DIDManager({
store: new DIDStoreJson(jsonFileStore),
defaultProvider: 'did:key',
providers: {
'did:ethr:sepolia': new EthrDIDProvider({
defaultKms: 'local',
network: 'sepolia',
rpcUrl: 'https://sepolia.infura.io/v3/' + INFURA_PROJECT_ID,
}),
'did:key': new KeyDIDProvider({
defaultKms: 'local'
})
},
}),
new DIDResolverPlugin({
resolver: new Resolver({
...ethrDidResolver({ infuraProjectId: INFURA_PROJECT_ID }),
...webDidResolver(),
})
}),
new DataStoreJson(jsonFileStore),
new CredentialPlugin()
],
})

2 changes: 1 addition & 1 deletion next-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/building-your-application/configuring/typescript for more information.
// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
Loading

0 comments on commit 90cdc28

Please sign in to comment.