@interop/did-web-resolver 5.0.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +38 -12
  2. package/dist/DidWebResolver.d.ts +267 -0
  3. package/dist/DidWebResolver.d.ts.map +1 -0
  4. package/dist/DidWebResolver.js +557 -0
  5. package/dist/DidWebResolver.js.map +1 -0
  6. package/dist/assertions.d.ts +47 -0
  7. package/dist/assertions.d.ts.map +1 -0
  8. package/dist/assertions.js +90 -0
  9. package/dist/assertions.js.map +1 -0
  10. package/dist/constants.d.ts +23 -0
  11. package/dist/constants.d.ts.map +1 -0
  12. package/dist/constants.js +45 -0
  13. package/dist/constants.js.map +1 -0
  14. package/dist/index.d.ts +8 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +6 -0
  17. package/dist/index.js.map +1 -0
  18. package/package.json +64 -72
  19. package/dist/esm/DidWebResolver.d.ts +0 -147
  20. package/dist/esm/DidWebResolver.d.ts.map +0 -1
  21. package/dist/esm/DidWebResolver.js +0 -322
  22. package/dist/esm/DidWebResolver.js.map +0 -1
  23. package/dist/esm/index.d.ts +0 -8
  24. package/dist/esm/index.d.ts.map +0 -1
  25. package/dist/esm/index.js +0 -6
  26. package/dist/esm/index.js.map +0 -1
  27. package/dist/src/DidWebResolver.d.ts +0 -146
  28. package/dist/src/DidWebResolver.js +0 -329
  29. package/dist/src/DidWebResolver.js.map +0 -1
  30. package/dist/src/index.d.ts +0 -7
  31. package/dist/src/index.js +0 -12
  32. package/dist/src/index.js.map +0 -1
  33. package/dist/test/DidWebResolver.spec.d.ts +0 -1
  34. package/dist/test/DidWebResolver.spec.js +0 -183
  35. package/dist/test/DidWebResolver.spec.js.map +0 -1
  36. package/src/DidWebResolver.ts +0 -366
  37. package/src/declarations.d.ts +0 -11
  38. package/src/index.ts +0 -8
  39. /package/{LICENSE → LICENSE.md} +0 -0
@@ -1,366 +0,0 @@
1
- /* eslint-disable @typescript-eslint/strict-boolean-expressions */
2
- import { httpClient } from '@digitalcredentials/http-client'
3
- import * as didIo from '@digitalcredentials/did-io'
4
- import * as ed25519Context from 'ed25519-signature-2020-context'
5
- import * as x25519Context from 'x25519-key-agreement-2020-context'
6
- import * as didContext from 'did-context'
7
- import { decodeSecretKeySeed } from '@digitalcredentials/bnid'
8
- import { URL } from 'whatwg-url'
9
-
10
- const { VERIFICATION_RELATIONSHIPS } = didIo
11
-
12
- const DEFAULT_KEY_MAP = {
13
- capabilityInvocation: 'Ed25519VerificationKey2020',
14
- authentication: 'Ed25519VerificationKey2020',
15
- assertionMethod: 'Ed25519VerificationKey2020',
16
- capabilityDelegation: 'Ed25519VerificationKey2020',
17
- keyAgreement: 'X25519KeyAgreementKey2020'
18
- }
19
-
20
- export function didFromUrl ({ url }: { url?: string } = {}): string {
21
- if (!url) {
22
- throw new TypeError('Cannot convert url to did, missing url.')
23
- }
24
- if (url.startsWith('http:')) {
25
- throw new TypeError('did:web does not support non-HTTPS URLs.')
26
- }
27
-
28
- let parsedUrl
29
- try {
30
- parsedUrl = new URL(url)
31
- } catch (error) {
32
- throw new TypeError(`Invalid url: "${url}".`)
33
- }
34
-
35
- let { host, pathname } = parsedUrl
36
- let pathComponent = ''
37
-
38
- const didJsonSuffix = '/did.json'
39
- const wellKnownSuffix = '/.well-known'
40
-
41
- if (pathname?.endsWith(didJsonSuffix)) {
42
- pathname = pathname.substring(0, pathname.length - didJsonSuffix.length)
43
- }
44
-
45
- if (pathname?.endsWith(wellKnownSuffix)) {
46
- pathname = pathname.substring(0, pathname.length - wellKnownSuffix.length)
47
- }
48
-
49
- if (pathname && pathname !== '/') {
50
- pathComponent = pathname.split('/').map(encodeURIComponent).join(':')
51
- }
52
-
53
- return 'did:web:' + encodeURIComponent(host) + pathComponent
54
- }
55
-
56
- export function urlFromDid ({ did }: { did: string | undefined }): string {
57
- if (!did?.startsWith('did:web:')) {
58
- throw new TypeError(`DID Method not supported: "${did ?? ''}".`)
59
- }
60
-
61
- const [didUrl, hashFragment] = did.split('#')
62
- // eslint-disable-next-line no-unused-vars
63
- // const [didResource, query] = didUrl.split('?')
64
-
65
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
66
- const [_did, _web, urlNoProtocol, ...pathFragments] = didUrl.split(':')
67
-
68
- if (urlNoProtocol.includes('/')) {
69
- throw new TypeError(`Cannot construct url from did: "${did}". domain-name cannot contain a path.`)
70
- }
71
-
72
- let parsedUrl
73
- try {
74
- // URI-decode the url (in case it contained a port number,
75
- // for example, `did:web:localhost%3A8080`
76
- parsedUrl = new URL('https://' + decodeURIComponent(urlNoProtocol))
77
- } catch (error) {
78
- throw new TypeError(`Cannot construct url from did: "${did}".`)
79
- }
80
-
81
- if (pathFragments.length === 0) {
82
- parsedUrl.pathname = '/.well-known/did.json'
83
- } else {
84
- parsedUrl.pathname = pathFragments.map(decodeURIComponent).join('/') + '/did.json'
85
- }
86
-
87
- if (hashFragment) {
88
- parsedUrl.hash = hashFragment
89
- }
90
- return parsedUrl.toString()
91
- }
92
-
93
- /**
94
- * Initializes the DID Document's keys/proof methods.
95
- *
96
- * @example
97
- * didDocument.id = 'did:ex:123';
98
- * const {didDocument, keyPairs} = await initKeys({
99
- * didDocument,
100
- * cryptoLd,
101
- * keyMap: {
102
- * capabilityInvocation: someExistingKey,
103
- * authentication: 'Ed25519VerificationKey2020',
104
- * assertionMethod: 'Ed25519VerificationKey2020',
105
- * keyAgreement: 'X25519KeyAgreementKey2019'
106
- * }
107
- * });.
108
- *
109
- * @param {object} options - Options hashmap.
110
- * @param {object} options.didDocument - DID Document.
111
- * @typedef {object} CryptoLD
112
- * @param {CryptoLD} [options.cryptoLd] - CryptoLD driver instance,
113
- * initialized with the key types this DID Document intends to support.
114
- * @param {object} [options.keyMap] - Map of keys (or key types) by purpose.
115
- *
116
- * @returns {Promise<{didDocument: object, keyPairs: Map}>} Resolves with the
117
- * DID Document initialized with keys, as well as the map of the corresponding
118
- * key pairs (by key id).
119
- */
120
- export async function initKeys (
121
- { didDocument, cryptoLd, keyMap }:
122
- { didDocument?: object, cryptoLd?: any, keyMap?: any } = {}
123
- ): Promise<{ didDocument: object, keyPairs: Map<string, any> }> {
124
- const doc: any = { ...didDocument }
125
- if (!doc.id) {
126
- throw new TypeError(
127
- 'DID Document "id" property is required to initialize keys.')
128
- }
129
-
130
- const keyPairs = new Map()
131
-
132
- // Set the defaults for the created keys (if needed)
133
- const options = { controller: doc.id }
134
-
135
- for (const purpose in keyMap) {
136
- if (!VERIFICATION_RELATIONSHIPS.has(purpose)) {
137
- throw new Error(`Unsupported key purpose: "${purpose}".`)
138
- }
139
-
140
- let key
141
- if (typeof keyMap[purpose] === 'string') {
142
- if (!cryptoLd) {
143
- throw new Error('Please provide an initialized CryptoLD instance.')
144
- }
145
- key = await cryptoLd.generate({ type: keyMap[purpose], ...options })
146
- } else {
147
- // An existing key has been provided
148
- key = keyMap[purpose]
149
- }
150
-
151
- doc[purpose] = [key.export({ publicKey: true })]
152
- keyPairs.set(key.id, key)
153
- }
154
-
155
- return { didDocument: doc, keyPairs }
156
- }
157
-
158
- export class DidWebResolver {
159
- public cryptoLd: any
160
- public keyMap: object
161
- public method: string
162
- public logger: any
163
-
164
- /**
165
- * @param cryptoLd {CryptoLD}
166
- * @param keyMap {object}
167
- * @param [logger] {object} Logger object (with .log, .error, .warn,
168
- * etc methods).
169
- */
170
- constructor ({ cryptoLd, keyMap = DEFAULT_KEY_MAP, logger = console }:
171
- { cryptoLd?: any, keyMap?: object, logger?: any } = {}) {
172
- this.method = 'web' // did:web:... (used for didIo resolver harness)
173
- this.cryptoLd = cryptoLd
174
- this.keyMap = keyMap
175
- this.logger = logger
176
- }
177
-
178
- /**
179
- * Generates a new DID Document and initializes various authentication
180
- * and authorization proof purpose keys.
181
- *
182
- * @example
183
- * const url = 'https://example.com'
184
- * const { didDocument, didKeys } = await didWeb.generate({url})
185
- * didDocument.id
186
- * // -> 'did:web:example.com'
187
- *
188
- *
189
- * Either an `id` or a `url` is required:
190
- * @param [id] {string} - A did:web DID. If absent, will be converted from url
191
- * @param [url] {string}
192
- * @param [seed] {string|Uint8Array}
193
- *
194
- * @param [keyMap] {object} A hashmap of key types by purpose.
195
- *
196
- * @param cryptoLd
197
- * @parma [cryptoLd] {object} CryptoLD instance with support for supported
198
- * crypto suites installed.
199
- *
200
- * @returns {Promise<{didDocument: object, keyPairs: object,
201
- * methodFor: Function}>} Resolves with the generated DID Document, along
202
- * with the corresponding key pairs used to generate it (for storage in a
203
- * KMS).
204
- */
205
- async generate (
206
- { id, url, seed, keyMap, cryptoLd = this.cryptoLd }:
207
- { id?: string, url?: string, seed?: string | Uint8Array, keyMap?: any, cryptoLd?: any } = {}):
208
- Promise<{ didDocument: any, keyPairs: object, methodFor: Function }> {
209
- if (!id && !url) {
210
- throw new TypeError('A "url" or an "id" parameter is required.')
211
- }
212
- if (seed && keyMap) {
213
- throw new TypeError(
214
- 'Either a "seed" or a "keyMap" param must be provided, but not both.'
215
- )
216
- }
217
-
218
- const did = id ?? didFromUrl({ url })
219
-
220
- if (seed) {
221
- const keyPair = await _keyPairFromSecretSeed({
222
- seed, controller: did, cryptoLd
223
- })
224
- keyMap = { assertionMethod: keyPair }
225
- } else {
226
- keyMap = keyMap || this.keyMap
227
- }
228
-
229
- // Compose the DID Document
230
- let didDocument = {
231
- '@context': [
232
- didContext.constants.DID_CONTEXT_URL,
233
- ed25519Context.constants.CONTEXT_URL,
234
- x25519Context.constants.CONTEXT_URL
235
- ],
236
- id: did
237
- }
238
-
239
- const result: any = await initKeys({ didDocument, cryptoLd, keyMap })
240
- const keyPairs = result.keyPairs
241
- didDocument = result.didDocument
242
-
243
- // Convenience function that returns the public/private key pair instance
244
- // for a given purpose (authentication, assertionMethod, keyAgreement, etc).
245
- const methodFor = ({ purpose }: { purpose: string }): any => {
246
- const { id: methodId } = didIo.findVerificationMethod({
247
- doc: didDocument, purpose
248
- })
249
- return keyPairs.get(methodId)
250
- }
251
-
252
- return { didDocument, keyPairs, methodFor }
253
- }
254
-
255
- /**
256
- * Fetches a DID Document for a given DID.
257
- *
258
- * @example
259
- * // In Node.js tests, use an agent to avoid self-signed certificate errors
260
- * const agent = new https.agent({rejectUnauthorized: false});
261
- *
262
- * @param {string} [did] For example, 'did:web:example.com'
263
- * @param {string} [url]
264
- * @param {https.Agent} [agent] Optional agent used to customize network
265
- * behavior in Node.js (such as `rejectUnauthorized: false`).
266
- * @param {object} [logger] Logger object (with .log, .error, .warn,
267
- * etc methods).
268
- *
269
- * @throws {Error}
270
- *
271
- * @returns {Promise<object>} Plain parsed JSON object of the DID Document.
272
- */
273
- async get ({ did, url, agent, logger = this.logger }: { did?: string | undefined, url?: string | undefined, agent?: any, logger?: any }): Promise<object> {
274
- const didUrl = url ?? urlFromDid({ did })
275
- if (!didUrl) {
276
- throw new TypeError('A DID or a URL is required.')
277
- }
278
-
279
- const [urlAuthority, keyIdFragment] = didUrl.split('#')
280
-
281
- let didDocument
282
- try {
283
- logger.info(`Fetching "${urlAuthority}" via http client.`)
284
- const result = await httpClient.get(urlAuthority, { agent })
285
- didDocument = result.data
286
- } catch (e: any) {
287
- // status is HTTP status code
288
- // data is JSON error from the server if available
289
- const { data, status } = e
290
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
291
- logger.error(`Http ${status ?? ''} error:`, data)
292
- throw e
293
- }
294
- if (didDocument && keyIdFragment) {
295
- // resolve an individual key
296
- // Keys are expected to have format: <did:web:...>#<keyIdFragment>
297
- const didAuthority = didFromUrl({ url: urlAuthority })
298
- const methodId = `${didAuthority}#${keyIdFragment}`
299
-
300
- const key = didIo.findVerificationMethod({ doc: didDocument, methodId })
301
- if (!key) {
302
- throw new Error(`Key id ${methodId} not found.`)
303
- }
304
-
305
- const keyPair = await this.cryptoLd.from(key)
306
-
307
- return keyPair.export({ publicKey: true, includeContext: true })
308
- }
309
-
310
- return didDocument
311
- }
312
-
313
- /**
314
- * Returns the public key (verification method) object for a given DID
315
- * Document and purpose. Useful in conjunction with a `.get()` call.
316
- *
317
- * @example
318
- * const didDocument = await didKeyDriver.get({did});
319
- * const authKeyData = didDriver.publicMethodFor({
320
- * didDocument, purpose: 'authentication'
321
- * });
322
- * // You can then create a suite instance object to verify signatures etc.
323
- * const authPublicKey = await cryptoLd.from(authKeyData);
324
- * const {verify} = authPublicKey.verifier();
325
- *
326
- * @param {object} options - Options hashmap.
327
- * @param {object} options.didDocument - DID Document (retrieved via a
328
- * `.get()` or from some other source).
329
- * @param {string} options.purpose - Verification method purpose, such as
330
- * 'authentication', 'assertionMethod', 'keyAgreement' and so on.
331
- *
332
- * @returns {object} Returns the public key object (obtained from the DID
333
- * Document), without a `@context`.
334
- */
335
- publicMethodFor ({ didDocument, purpose }: { didDocument: any, purpose: string }): any {
336
- const method = didIo.findVerificationMethod({ doc: didDocument, purpose })
337
- if (!method) {
338
- throw new Error(`No verification method found for purpose "${purpose}"`)
339
- }
340
- return method
341
- }
342
- }
343
-
344
- /**
345
- * @param options {object}
346
- * @param options.seed {string|Uint8Array}
347
- * @param controller {string}
348
- * @param cryptoLd {object}
349
- *
350
- * @return {Promise<LDKeyPair>}
351
- */
352
- async function _keyPairFromSecretSeed ({ seed, controller, cryptoLd }: { seed: string | Uint8Array, controller?: string, cryptoLd?: any }): Promise<any> {
353
- let seedBytes
354
- if (typeof seed === 'string') {
355
- // Currently only supports base58 multibase / identity multihash encoding.
356
- if (!seed.startsWith('z1A')) {
357
- throw new TypeError('"seed" parameter must be a multibase/multihash encoded string, or a Uint8Array.')
358
- }
359
- seedBytes = decodeSecretKeySeed({ secretKeySeed: seed })
360
- } else {
361
- seedBytes = new Uint8Array(seed)
362
- }
363
- return cryptoLd.generate({
364
- controller, seed: seedBytes, type: 'Ed25519VerificationKey2020'
365
- })
366
- }
@@ -1,11 +0,0 @@
1
- declare module '@digitalcredentials/http-client'
2
- declare module '@digitalcredentials/did-io'
3
- declare module 'ed25519-signature-2020-context'
4
- declare module 'x25519-key-agreement-2020-context'
5
- declare module 'did-context'
6
- declare module '@digitalcredentials/bnid'
7
- declare module '@digitalcredentials/ed25519-verification-key-2020'
8
- declare module '@digitalcredentials/x25519-key-agreement-key-2020'
9
- declare module 'crypto-ld'
10
- declare module 'whatwg-url'
11
- declare module 'dirty-chai'
package/src/index.ts DELETED
@@ -1,8 +0,0 @@
1
-
2
- import { DidWebResolver, didFromUrl, urlFromDid } from './DidWebResolver'
3
-
4
- const driver = (options: { cryptoLd?: any, keyMap?: object | undefined, logger?: any } | undefined): DidWebResolver => {
5
- return new DidWebResolver(options)
6
- }
7
-
8
- export { driver, DidWebResolver, didFromUrl, urlFromDid }
File without changes