/
idx.ts
208 lines (157 loc) · 7.73 KB
/
idx.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import { DID } from 'dids';
import { toUint8Array } from 'hex-lite';
import KeyDidResolver from 'key-did-resolver';
import { Ed25519Provider } from 'key-did-provider-ed25519';
import { DIDDataStore } from '@glazed/did-datastore';
import { TileLoader } from '@glazed/tile-loader';
import { CeramicClient } from '@ceramicnetwork/http-client';
import { CreateOpts } from '@ceramicnetwork/common';
import { TileDocument, TileMetadataArgs } from '@ceramicnetwork/stream-tile';
import { IDXCredentialValidator, VCValidator, VC, IDXCredential } from '@learncard/types';
import { streamIdToCeramicURI } from './helpers';
import {
CredentialsList,
CredentialsListValidator,
IDXPluginMethods,
IDXPluginDependentMethods,
CeramicIDXArgs,
CeramicURIValidator,
BackwardsCompatCredentialsListValidator,
} from './types';
import { Plugin, Wallet } from 'types/wallet';
const getCeramicClientFromWalletSuite = async <URI extends string = ''>(
wallet: Wallet<any, IDXPluginDependentMethods<URI>>,
ceramicEndpoint: string
): Promise<CeramicClient> => {
const client = new CeramicClient(ceramicEndpoint);
// only supporting did-key atm. this should be stripped into a config param
const resolver = { ...KeyDidResolver.getResolver() };
const did = new DID({ resolver });
client.did = did;
// use wallet secret key
// TODO: this is repeating work already done in the wallet. understand what the Ed25519Provider is doing to determine
// if we can just pass wallet signing key here instead of creating a duplicate from same seed.
const key = wallet.pluginMethods.getKey();
const ceramicProvider = new Ed25519Provider(toUint8Array(key));
client.did!.setProvider(ceramicProvider);
await client.did!.authenticate();
return client;
};
/**
* @group Plugins
*/
export const getIDXPlugin = async <URI extends string = ''>(
wallet: Wallet<any, IDXPluginDependentMethods<URI>>,
{ modelData, credentialAlias, ceramicEndpoint, defaultContentFamily }: CeramicIDXArgs
): Promise<Plugin<'IDX', IDXPluginMethods<URI>>> => {
const ceramic = await getCeramicClientFromWalletSuite(wallet, ceramicEndpoint);
const loader = new TileLoader({ ceramic });
const dataStore = new DIDDataStore({ ceramic, model: modelData });
const getCredentialsListFromIdx = async (alias = credentialAlias): Promise<CredentialsList> => {
const list = await dataStore.get(alias);
if (!list) return { credentials: [] };
const validationResult = await CredentialsListValidator.spa(list);
if (validationResult.success) return validationResult.data;
const backwardsCompatValidationResult = await BackwardsCompatCredentialsListValidator.spa(
list
);
if (backwardsCompatValidationResult.success) {
const oldCreds = backwardsCompatValidationResult.data.credentials;
const newCreds = oldCreds.map(cred => {
if ('uri' in cred) return cred as IDXCredential;
const { title, id, storageType, ...rest } = cred;
return {
...rest,
id: title,
uri: `lc:ceramic:${id.replace('ceramic://', '')}`,
} as IDXCredential;
});
const credentialsList = { credentials: newCreds };
await dataStore.set(credentialAlias, credentialsList);
return credentialsList;
}
console.error(validationResult.error);
throw new Error('Invalid credentials list stored in IDX');
};
const removeCredentialFromIdx = async (id: string, alias?: string) => {
if (!id) throw new Error('Must provide id to remove');
if (!alias) alias = credentialAlias;
const existing = await getCredentialsListFromIdx(alias);
existing.credentials = existing.credentials.filter(credential => credential.id !== id);
return dataStore.set(alias, existing);
};
const publishContentToCeramic = async (
content: any,
metadata: TileMetadataArgs = {},
options: CreateOpts = {}
) => {
if (!content) throw new Error('content is required');
// default to current authorized
if (!metadata.controllers) metadata.controllers = [ceramic.did!.id];
// use default
if (!metadata.family) metadata.family = defaultContentFamily;
// default to pinning
// TODO: expose
if (!('pin' in options)) options.pin = true;
// assuming TileDocument for now
const doc = await TileDocument.create(ceramic, content, metadata, options);
return doc.id.toString();
};
const readContentFromCeramic = async (streamId: string): Promise<any> => {
return (await loader.load(streamId))?.content;
};
return {
pluginMethods: {
getCredentialsListFromIdx: async (_wallet, alias = credentialAlias) =>
getCredentialsListFromIdx(alias),
publishContentToCeramic: async (_wallet, cred) =>
streamIdToCeramicURI(await publishContentToCeramic(cred)),
readContentFromCeramic: async (_wallet, streamId: string) =>
readContentFromCeramic(streamId),
getVerifiableCredentialFromIdx: async (_wallet, id) => {
const credentialList = await getCredentialsListFromIdx();
const credential = credentialList?.credentials?.find(cred => cred?.id === id);
return credential?.uri
? _wallet.pluginMethods.resolveCredential(credential.uri)
: undefined;
},
getVerifiableCredentialsFromIdx: async _wallet => {
const credentialList = await getCredentialsListFromIdx();
const uris = credentialList?.credentials?.map(credential => credential?.uri) ?? [];
return (
await Promise.all(
uris.map(async uri => _wallet.pluginMethods.resolveCredential(uri))
)
).filter((vc): vc is VC => !!vc);
},
addVerifiableCredentialInIdx: async (_wallet, idxCredential) => {
const record = IDXCredentialValidator.parse(idxCredential);
if (!record) throw new Error('record is required');
if (!record.uri) throw Error('No URI provided');
// Make sure URI can be resolved
await _wallet.pluginMethods.resolveCredential(record.uri);
const existing = await getCredentialsListFromIdx(credentialAlias);
const indexOfExistingCredential = existing.credentials.findIndex(credential => {
return credential.id === record.id;
});
if (indexOfExistingCredential > -1) {
existing.credentials[indexOfExistingCredential] = record;
} else existing.credentials.push(record);
return streamIdToCeramicURI(await dataStore.set(credentialAlias, existing));
},
removeVerifiableCredentialInIdx: async (_wallet, id) => {
return removeCredentialFromIdx(id);
},
resolveCredential: async (_wallet, uri) => {
if (!uri) return undefined;
if (uri.startsWith('ceramic://')) {
return VCValidator.parseAsync(await readContentFromCeramic(uri));
}
const verificationResult = await CeramicURIValidator.spa(uri);
if (!verificationResult.success) return wallet.pluginMethods.resolveCredential(uri);
const streamId = verificationResult.data.split(':')[2];
return VCValidator.parseAsync(await readContentFromCeramic(streamId));
},
},
};
};