-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathmemory-key-store.ts
70 lines (60 loc) · 2 KB
/
memory-key-store.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { IKey } from '@veramo/core'
import { AbstractKeyStore } from './abstract-key-store'
import {
AbstractPrivateKeyStore,
ImportablePrivateKey,
ManagedPrivateKey,
} from './abstract-private-key-store'
import { v4 as uuidv4 } from 'uuid'
export class MemoryKeyStore extends AbstractKeyStore {
private keys: Record<string, IKey> = {}
async get({ kid }: { kid: string }): Promise<IKey> {
const key = this.keys[kid]
if (!key) throw Error('Key not found')
return key
}
async delete({ kid }: { kid: string }) {
delete this.keys[kid]
return true
}
async import(args: IKey) {
this.keys[args.kid] = { ...args }
return true
}
async list(args: {}): Promise<Exclude<IKey, 'privateKeyHex'>[]> {
const safeKeys = Object.values(this.keys).map((key) => {
const { privateKeyHex, ...safeKey } = key
return safeKey
})
return safeKeys
}
}
/**
* An implementation of {@link AbstractPrivateKeyStore} that holds everything in memory.
*
* This is usable by {@link @veramo/kms-local} to hold the private key data.
*/
export class MemoryPrivateKeyStore extends AbstractPrivateKeyStore {
private privateKeys: Record<string, ManagedPrivateKey> = {}
async get({ alias }: { alias: string }): Promise<ManagedPrivateKey> {
const key = this.privateKeys[alias]
if (!key) throw Error(`not_found: PrivateKey not found for alias=${alias}`)
return key
}
async delete({ alias }: { alias: string }) {
delete this.privateKeys[alias]
return true
}
async import(args: ImportablePrivateKey) {
const alias = args.alias || uuidv4()
const existingEntry = this.privateKeys[alias]
if (existingEntry && existingEntry.privateKeyHex !== args.privateKeyHex) {
throw new Error('key_already_exists: key exists with different data, please use a different alias')
}
this.privateKeys[alias] = { ...args, alias }
return this.privateKeys[alias]
}
async list(): Promise<Array<ManagedPrivateKey>> {
return [...Object.values(this.privateKeys)]
}
}