@dwn-protocol/id-sdk 0.2.5 → 0.2.6

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 (99) hide show
  1. package/package.json +2 -3
  2. package/src/agent/app-data-store.ts +0 -365
  3. package/src/agent/did-manager.ts +0 -393
  4. package/src/agent/dwn-manager.ts +0 -548
  5. package/src/agent/identity-manager.ts +0 -165
  6. package/src/agent/index.ts +0 -19
  7. package/src/agent/json-rpc.ts +0 -107
  8. package/src/agent/key-manager.ts +0 -302
  9. package/src/agent/kms-local.ts +0 -412
  10. package/src/agent/outbox.ts +0 -128
  11. package/src/agent/rpc-client.ts +0 -223
  12. package/src/agent/store-managed-did.ts +0 -295
  13. package/src/agent/store-managed-identity.ts +0 -243
  14. package/src/agent/store-managed-key.ts +0 -754
  15. package/src/agent/sync-manager.ts +0 -631
  16. package/src/agent/test-managed-agent.ts +0 -299
  17. package/src/agent/types/agent.ts +0 -145
  18. package/src/agent/types/managed-key.ts +0 -442
  19. package/src/agent/utils.ts +0 -190
  20. package/src/common/convert.ts +0 -424
  21. package/src/common/index.ts +0 -9
  22. package/src/common/multicodec.ts +0 -176
  23. package/src/common/object.ts +0 -43
  24. package/src/common/stores.ts +0 -125
  25. package/src/common/stream-node.ts +0 -381
  26. package/src/common/stream.ts +0 -406
  27. package/src/common/type-utils.ts +0 -117
  28. package/src/common/types.ts +0 -48
  29. package/src/credentials/credential-bbs.ts +0 -419
  30. package/src/credentials/credential.ts +0 -324
  31. package/src/credentials/index.ts +0 -5
  32. package/src/credentials/presentation.ts +0 -182
  33. package/src/credentials/status-list.ts +0 -365
  34. package/src/credentials/utils.ts +0 -58
  35. package/src/credentials/validators.ts +0 -52
  36. package/src/crypto/algorithms-api/aes/base.ts +0 -49
  37. package/src/crypto/algorithms-api/aes/ctr.ts +0 -51
  38. package/src/crypto/algorithms-api/aes/index.ts +0 -2
  39. package/src/crypto/algorithms-api/crypto-algorithm.ts +0 -127
  40. package/src/crypto/algorithms-api/crypto-key.ts +0 -56
  41. package/src/crypto/algorithms-api/ec/base.ts +0 -39
  42. package/src/crypto/algorithms-api/ec/ecdh.ts +0 -53
  43. package/src/crypto/algorithms-api/ec/ecdsa.ts +0 -37
  44. package/src/crypto/algorithms-api/ec/eddsa.ts +0 -30
  45. package/src/crypto/algorithms-api/ec/index.ts +0 -4
  46. package/src/crypto/algorithms-api/errors.ts +0 -29
  47. package/src/crypto/algorithms-api/index.ts +0 -6
  48. package/src/crypto/algorithms-api/pbkdf/index.ts +0 -1
  49. package/src/crypto/algorithms-api/pbkdf/pbkdf2.ts +0 -91
  50. package/src/crypto/crypto-algorithms/aes-ctr.ts +0 -70
  51. package/src/crypto/crypto-algorithms/bbs.ts +0 -110
  52. package/src/crypto/crypto-algorithms/ecdh.ts +0 -115
  53. package/src/crypto/crypto-algorithms/ecdsa.ts +0 -111
  54. package/src/crypto/crypto-algorithms/eddsa.ts +0 -110
  55. package/src/crypto/crypto-algorithms/index.ts +0 -6
  56. package/src/crypto/crypto-algorithms/pbkdf2.ts +0 -54
  57. package/src/crypto/crypto-primitives/aes-ctr.ts +0 -131
  58. package/src/crypto/crypto-primitives/aes-gcm.ts +0 -138
  59. package/src/crypto/crypto-primitives/bbs.ts +0 -183
  60. package/src/crypto/crypto-primitives/concat-kdf.ts +0 -207
  61. package/src/crypto/crypto-primitives/ed25519.ts +0 -201
  62. package/src/crypto/crypto-primitives/index.ts +0 -10
  63. package/src/crypto/crypto-primitives/pbkdf2.ts +0 -78
  64. package/src/crypto/crypto-primitives/secp256k1.ts +0 -322
  65. package/src/crypto/crypto-primitives/x25519.ts +0 -101
  66. package/src/crypto/crypto-primitives/xchacha20-poly1305.ts +0 -46
  67. package/src/crypto/crypto-primitives/xchacha20.ts +0 -34
  68. package/src/crypto/index.ts +0 -8
  69. package/src/crypto/jose.ts +0 -948
  70. package/src/crypto/types/crypto-key.ts +0 -4
  71. package/src/crypto/types/iddwn-crypto.ts +0 -119
  72. package/src/crypto/utils.ts +0 -200
  73. package/src/did-api.ts +0 -72
  74. package/src/dids/dht.ts +0 -412
  75. package/src/dids/did-dht.ts +0 -436
  76. package/src/dids/did-ion.ts +0 -613
  77. package/src/dids/did-key.ts +0 -791
  78. package/src/dids/did-resolver.ts +0 -107
  79. package/src/dids/index.ts +0 -9
  80. package/src/dids/resolver-cache-level.ts +0 -82
  81. package/src/dids/resolver-cache-noop.ts +0 -25
  82. package/src/dids/types.ts +0 -278
  83. package/src/dids/utils.ts +0 -129
  84. package/src/dwn-api.ts +0 -584
  85. package/src/iddwn.ts +0 -241
  86. package/src/identity-agent/index.ts +0 -270
  87. package/src/index.ts +0 -26
  88. package/src/interfaces/metadata.ts +0 -163
  89. package/src/interfaces/queue.ts +0 -108
  90. package/src/interfaces/services.ts +0 -122
  91. package/src/interfaces/transactions.ts +0 -220
  92. package/src/protocol.ts +0 -68
  93. package/src/proxy-agent/index.ts +0 -255
  94. package/src/record.ts +0 -521
  95. package/src/service-options.ts +0 -62
  96. package/src/typings/decentralized-identity__ion-pow-sdk.d.ts +0 -7
  97. package/src/user-agent/index.ts +0 -295
  98. package/src/utils.ts +0 -29
  99. package/src/vc-api.ts +0 -505
@@ -1,107 +0,0 @@
1
- import type {
2
- DidResolverCache,
3
- DidMethodResolver,
4
- DidResolutionResult,
5
- DidResolutionOptions,
6
- } from './types.js';
7
-
8
- import { parseDid } from './utils.js';
9
- import { DidResolverCacheNoop } from './resolver-cache-noop.js';
10
-
11
- export type DidResolverOptions = {
12
- didResolvers: DidMethodResolver[];
13
- cache?: DidResolverCache;
14
- }
15
-
16
- /**
17
- * The `DidResolver` class is responsible for resolving DIDs to DID documents.
18
- * It uses method resolvers to resolve DIDs of different methods and a cache
19
- * to store resolved DID documents.
20
- */
21
- export class DidResolver {
22
- /**
23
- * A cache for storing resolved DID documents.
24
- */
25
- private cache: DidResolverCache;
26
-
27
- /**
28
- * A map to store method resolvers against method names.
29
- */
30
- private didResolvers: Map<string, DidMethodResolver> = new Map();
31
-
32
- /**
33
- * Constructs a new `DidResolver`.
34
- *
35
- * @param options - The options for constructing the `DidResolver`.
36
- * @param options.didResolvers - An array of `DidMethodResolver` instances.
37
- * @param options.cache - Optional. A cache for storing resolved DID documents. If not provided, a no-operation cache is used.
38
- */
39
- constructor(options: DidResolverOptions) {
40
- this.cache = options.cache || DidResolverCacheNoop;
41
-
42
- for (const resolver of options.didResolvers) {
43
- this.didResolvers.set(resolver.methodName, resolver);
44
- }
45
- }
46
-
47
- /**
48
- * Resolves a DID to a DID Resolution Result.
49
- * If the DID Resolution Result is present in the cache, it returns the cached
50
- * result. Otherwise, it uses the appropriate method resolver to resolve
51
- * the DID, stores the resolution result in the cache, and returns the
52
- * resolultion result.
53
- *
54
- * Note: The method signature for resolve() in this implementation must match
55
- * the `DidResolver` implementation in
56
- * {@link https://github.com/@dwn-protocol/id | @dwn-protocol/id} so that
57
- * IDDwn apps and the underlying DWN instance can share the same DID
58
- * resolution cache.
59
- *
60
- * @param didUrl - The DID or DID URL to resolve.
61
- * @returns A promise that resolves to the DID Resolution Result.
62
- */
63
- async resolve(didUrl: string, resolutionOptions?: DidResolutionOptions): Promise<DidResolutionResult> {
64
-
65
- const parsedDid = parseDid({ didUrl });
66
- if (!parsedDid) {
67
- return {
68
- '@context' : 'https://w3id.org/did-resolution/v1',
69
- didDocument : undefined,
70
- didDocumentMetadata : {},
71
- didResolutionMetadata : {
72
- contentType : 'application/did+json',
73
- error : 'invalidDid',
74
- errorMessage : `Cannot parse DID: ${didUrl}`
75
- }
76
- };
77
- }
78
-
79
- const resolver = this.didResolvers.get(parsedDid.method);
80
- if (!resolver) {
81
- return {
82
- '@context' : 'https://w3id.org/did-resolution/v1',
83
- didDocument : undefined,
84
- didDocumentMetadata : {},
85
- didResolutionMetadata : {
86
- contentType : 'application/did+json',
87
- error : 'methodNotSupported',
88
- errorMessage : `Method not supported: ${parsedDid.method}`
89
- }
90
- };
91
- }
92
-
93
- const cachedResolutionResult = await this.cache.get(parsedDid.did);
94
-
95
- if (cachedResolutionResult) {
96
- return cachedResolutionResult;
97
- } else {
98
- const resolutionResult = await resolver.resolve({
99
- didUrl: parsedDid.did,
100
- resolutionOptions
101
- });
102
- await this.cache.set(parsedDid.did, resolutionResult);
103
-
104
- return resolutionResult;
105
- }
106
- }
107
- }
package/src/dids/index.ts DELETED
@@ -1,9 +0,0 @@
1
- export * from './dht.js';
2
- export * from './did-dht.js';
3
- export * from './did-ion.js';
4
- export * from './did-key.js';
5
- export * from './did-resolver.js';
6
- export * from './resolver-cache-level.js';
7
- export * from './resolver-cache-noop.js';
8
- export * from './types.js';
9
- export * as utils from './utils.js';
@@ -1,82 +0,0 @@
1
- import type { DidResolutionResult, DidResolverCache } from './types.js';
2
-
3
- import ms from 'ms';
4
- import { Level } from 'level';
5
-
6
- export type DidResolverCacheOptions = {
7
- location?: string;
8
- ttl?: string;
9
- }
10
-
11
- type CacheWrapper = {
12
- ttlMillis: number;
13
- value: DidResolutionResult;
14
- }
15
-
16
- /**
17
- * Naive level-based cache for did resolution results. It just so happens that level aggressively keeps as much as it
18
- * can in memory when possible while also writing to the filesystem (in node runtime) and indexedDB (in browser runtime).
19
- * the persistent aspect is especially useful across page refreshes.
20
- */
21
- export class DidResolverCacheLevel implements DidResolverCache {
22
- private cache: Level<string, string>;
23
- private ttl: number;
24
-
25
- private static defaultOptions: Required<DidResolverCacheOptions> = {
26
- location : 'data/AGENT/DID_RESOLVERCACHE',
27
- ttl : '15m'
28
- };
29
-
30
- constructor(options: DidResolverCacheOptions = {}) {
31
- let { location, ttl } = options;
32
-
33
- location ??= DidResolverCacheLevel.defaultOptions.location;
34
- ttl ??= DidResolverCacheLevel.defaultOptions.ttl;
35
-
36
- this.cache = new Level(location);
37
- this.ttl = ms(ttl);
38
- }
39
-
40
- async get(did: string): Promise<DidResolutionResult | void> {
41
- try {
42
- const str = await this.cache.get(did);
43
- const cacheWrapper: CacheWrapper = JSON.parse(str);
44
-
45
- if (Date.now() >= cacheWrapper.ttlMillis) {
46
- // defer deletion to be called in the next tick of the js event loop
47
- this.cache.nextTick(() => this.cache.del(did));
48
-
49
- return;
50
- } else {
51
- return cacheWrapper.value;
52
- }
53
-
54
- } catch(error: any) {
55
- // Don't throw when a key wasn't found.
56
- if (error.code === 'LEVEL_NOT_FOUND') {
57
- return;
58
- }
59
-
60
- throw error;
61
- }
62
- }
63
-
64
- set(did: string, value: DidResolutionResult): Promise<void> {
65
- const cacheWrapper: CacheWrapper = { ttlMillis: Date.now() + this.ttl, value };
66
- const str = JSON.stringify(cacheWrapper);
67
-
68
- return this.cache.put(did, str);
69
- }
70
-
71
- delete(did: string): Promise<void> {
72
- return this.cache.del(did);
73
- }
74
-
75
- clear(): Promise<void> {
76
- return this.cache.clear();
77
- }
78
-
79
- close(): Promise<void> {
80
- return this.cache.close();
81
- }
82
- }
@@ -1,25 +0,0 @@
1
- import type { DidResolutionResult, DidResolverCache } from './types.js';
2
-
3
- /**
4
- * no-op cache that is used as the default cache for did-resolver.
5
- * The motivation behind using a no-op cache as the default stems from
6
- * the desire to maximize the potential for this library to be used
7
- * in as many JS runtimes as possible
8
- */
9
- export const DidResolverCacheNoop: DidResolverCache = {
10
- get: function (_key: string): Promise<DidResolutionResult> {
11
- return null as any;
12
- },
13
- set: function (_key: string, _value: DidResolutionResult): Promise<void> {
14
- return null as any;
15
- },
16
- delete: function (_key: string): Promise<void> {
17
- return null as any;
18
- },
19
- clear: function (): Promise<void> {
20
- return null as any;
21
- },
22
- close: function (): Promise<void> {
23
- return null as any;
24
- }
25
- };
package/src/dids/types.ts DELETED
@@ -1,278 +0,0 @@
1
- import type { KeyValueStore } from '../common/index.js';
2
- import type { PrivateKeyJwk, PublicKeyJwk } from '../crypto/index.js';
3
-
4
- import { DidKeyKeySet } from './did-key.js';
5
- import { DidIonKeySet } from './did-ion.js';
6
- import { DidDhtKeySet } from './did-dht.js';
7
-
8
- export type DidDocument = {
9
- '@context'?: 'https://www.w3.org/ns/did/v1' | string | string[];
10
- id: string;
11
- alsoKnownAs?: string[];
12
- controller?: string | string[];
13
- verificationMethod?: VerificationMethod[];
14
- service?: DidService[];
15
- assertionMethod?: VerificationMethod[] | string[];
16
- authentication?: VerificationMethod[] | string[];
17
- keyAgreement?: VerificationMethod[] | string[];
18
- capabilityDelegation?: VerificationMethod[] | string[];
19
- capabilityInvocation?: VerificationMethod[] | string[];
20
- }
21
-
22
- export type DidDocumentMetadata = {
23
- // indicates the timestamp of the Create operation. ISO8601 timestamp
24
- created?: string
25
- // indicates the timestamp of the last Update operation for the document version which was
26
- // resolved. ISO8601 timestamp
27
- updated?: string
28
- // indicates whether the DID has been deactivated
29
- deactivated?: boolean
30
- // indicates the version of the last Update operation for the document version which
31
- // was resolved
32
- versionId?: string
33
- // indicates the timestamp of the next Update operation if the resolved document version
34
- // is not the latest version of the document.
35
- nextUpdate?: string
36
- // indicates the version of the next Update operation if the resolved document version
37
- // is not the latest version of the document.
38
- nextVersionId?: string
39
- // @see https://www.w3.org/TR/did-core/#dfn-equivalentid
40
- equivalentId?: string
41
- // @see https://www.w3.org/TR/did-core/#dfn-canonicalid
42
- canonicalId?: string
43
- // Additional output metadata generated during DID Resolution.
44
- [key: string]: any
45
- };
46
-
47
- export type DidKeySet = DidKeyKeySet | DidIonKeySet | DidDhtKeySet;
48
-
49
- export type DidKeySetVerificationMethodKey = {
50
- /** Unique identifier for the key in the KeyManager store. */
51
- keyManagerId?: string;
52
- publicKeyJwk?: PublicKeyJwk;
53
- privateKeyJwk?: PrivateKeyJwk;
54
- relationships: VerificationRelationship[];
55
- }
56
-
57
- export type DidMetadata = {
58
- /**
59
- * Additional properties of any type.
60
- */
61
- [key: string]: any;
62
- }
63
-
64
- // eslint-disable-next-line @typescript-eslint/no-empty-interface
65
- export interface DidMethod {}
66
-
67
- export interface DidMethodApi extends DidMethodOperator, DidMethodResolver {
68
- new (): DidMethod;
69
- methodName: string;
70
- }
71
-
72
- export interface DidMethodResolver {
73
- new (): DidMethod;
74
- methodName: string;
75
-
76
- resolve(options: {
77
- didUrl: string,
78
- resolutionOptions?: DidResolutionOptions
79
- }): Promise<DidResolutionResult>;
80
- }
81
-
82
- export interface DidMethodOperator {
83
- new (): DidMethod;
84
- methodName: string;
85
-
86
- create(options: any): Promise<PortableDid>;
87
-
88
- generateKeySet(): Promise<DidKeySet>;
89
-
90
- getDefaultSigningKey(options: { didDocument: DidDocument }): Promise<string | undefined>;
91
- }
92
-
93
- /**
94
- * Services are used in DID documents to express ways of communicating with the DID subject or associated entities.
95
- * A service can be any type of service the DID subject wants to advertise.
96
- *
97
- * @see {@link https://www.w3.org/TR/did-core/#services}
98
- */
99
- export type DidService = {
100
- id: string;
101
- type: string;
102
- serviceEndpoint: string | DidServiceEndpoint | DidServiceEndpoint[];
103
- description?: string;
104
- };
105
-
106
- /**
107
- * A service endpoint is a URI (Uniform Resource Identifier) that can be used to interact with the service.
108
- *
109
- * @see {@link https://www.w3.org/TR/did-core/#dfn-serviceendpoint}
110
- */
111
- export interface DidServiceEndpoint {
112
- [key: string]: any;
113
- }
114
-
115
- export interface DwnServiceEndpoint extends DidServiceEndpoint {
116
- encryptionKeys?: string[];
117
- nodes: string[];
118
- signingKeys: string[];
119
- }
120
-
121
- export type DidResolutionMetadata = {
122
- contentType?: string
123
-
124
- error?:
125
- /**
126
- * When an unexpected error occurs during DID Resolution or DID URL dereferencing, the value of the DID Resolution or DID URL Dereferencing Metadata error property MUST be internalError.
127
- */
128
- | 'internalError'
129
-
130
- /**
131
- * If an invalid DID is detected during DID Resolution, the value of the
132
- * DID Resolution Metadata error property MUST be invalidDid.
133
- */
134
- | 'invalidDid'
135
-
136
- /**
137
- * If a DID method is not supported during DID Resolution or DID URL
138
- * dereferencing, the value of the DID Resolution or DID URL Dereferencing
139
- * Metadata error property MUST be methodNotSupported.
140
- */
141
- | 'methodNotSupported'
142
-
143
- /**
144
- * If during DID Resolution or DID URL dereferencing a DID or DID URL
145
- * doesn't exist, the value of the DID Resolution or DID URL dereferencing
146
- * Metadata error property MUST be notFound.
147
- */
148
- | 'notFound'
149
-
150
- /**
151
- * If a DID document representation is not supported during DID Resolution
152
- * or DID URL dereferencing, the value of the DID Resolution Metadata error
153
- * property MUST be representationNotSupported.
154
- */
155
- | 'representationNotSupported'
156
- | string
157
-
158
- // Additional output metadata generated during DID Resolution.
159
- [key: string]: any
160
- };
161
-
162
- /**
163
- * DID Resolution input metadata.
164
- *
165
- * @see {@link https://www.w3.org/TR/did-core/#did-resolution-options}
166
- */
167
- export interface DidResolutionOptions {
168
- accept?: string
169
-
170
- // Additional properties used during DID Resolution.
171
- [key: string]: any
172
- }
173
-
174
- export type DidResolutionResult = {
175
- '@context'?: 'https://w3id.org/did-resolution/v1' | string | string[]
176
- didResolutionMetadata: DidResolutionMetadata
177
- didDocument?: DidDocument
178
- didDocumentMetadata: DidDocumentMetadata
179
- };
180
-
181
- /**
182
- * implement this interface to provide your own cache for did resolution results. can be plugged in through IDDwn API
183
- */
184
- export type DidResolverCache = KeyValueStore<string, DidResolutionResult | void>;
185
-
186
- /**
187
- * Format to document a DID identifier, along with its associated data,
188
- * which can be exported, saved to a file, or imported. The intent is
189
- * bundle all of the necessary metadata to enable usage of the DID in
190
- * different contexts.
191
- */
192
- export interface PortableDid {
193
- did: string;
194
-
195
- /**
196
- * A DID method can define different forms of a DID that are logically
197
- * equivalent. An example is when a DID takes one form prior to registration
198
- * in a verifiable data registry and another form after such registration.
199
- * This is the purpose of the canonicalId property.
200
- *
201
- * The `canonicalId` must be used as the primary ID for the DID subject,
202
- * with all other equivalent values treated as secondary aliases.
203
- *
204
- * @see {@link https://www.w3.org/TR/did-core/#dfn-canonicalid | W3C DID Document Metadata}
205
- */
206
- canonicalId?: string;
207
-
208
- /**
209
- * A set of data describing the DID subject, including mechanisms, such as
210
- * cryptographic public keys, that the DID subject or a DID delegate can use
211
- * to authenticate itself and prove its association with the DID.
212
- */
213
- document: DidDocument;
214
-
215
- /**
216
- * A collection of cryptographic keys associated with the DID subject. The
217
- * `keySet` encompasses various forms, such as recovery keys, update keys,
218
- * and verification method keys, to enable authentication and verification
219
- * of the DID subject's association with the DID.
220
- */
221
- keySet: DidKeySet;
222
-
223
- /**
224
- * This property can be used to store method specific data about
225
- * each managed DID and additional properties of any type.
226
- */
227
- metadata?: DidMetadata;
228
- }
229
-
230
- export type VerificationMethod = {
231
- id: string;
232
- // one of the valid verification method types as per
233
- // https://www.w3.org/TR/did-spec-registries/#verification-method-types
234
- type: string;
235
- // DID of the key's controller
236
- controller: string;
237
- // a JSON Web Key that conforms to https://datatracker.ietf.org/doc/html/rfc7517
238
- publicKeyJwk?: PublicKeyJwk;
239
- // an encoded (e.g, base58) key with a Multibase-prefix that conforms to
240
- // https://datatracker.ietf.org/doc/draft-multiformats-multibase/
241
- publicKeyMultibase?: string;
242
- };
243
-
244
- export type VerificationRelationship =
245
- /**
246
- * Used to specify how the DID subject is expected to express claims, such
247
- * as for the purposes of issuing a Verifiable Credential
248
- */
249
- | 'assertionMethod'
250
-
251
- /**
252
- * Used to specify how the DID subject is expected to be authenticated, for
253
- * purposes such as logging into a website or engaging in any sort of
254
- * challenge-response protocol.
255
- */
256
- | 'authentication'
257
-
258
- /**
259
- * Used to specify how an entity can generate encryption material in order to
260
- * transmit confidential information intended for the DID subject, such as
261
- * for the purposes of establishing a secure communication channel with the
262
- * recipient.
263
- */
264
- | 'keyAgreement'
265
-
266
- /**
267
- * Used to specify a mechanism that might be used by the DID subject to
268
- * delegate a cryptographic capability to another party, such as delegating
269
- * the authority to access a specific HTTP API to a subordinate.
270
- */
271
- | 'capabilityDelegation'
272
-
273
- /**
274
- * Used to specify a verification method that might be used by the DID
275
- * subject to invoke a cryptographic capability, such as the authorization
276
- * to update the DID Document.
277
- */
278
- | 'capabilityInvocation';
package/src/dids/utils.ts DELETED
@@ -1,129 +0,0 @@
1
- import type { PublicKeyJwk } from '../crypto/index.js';
2
- import { parse, type ParsedDID } from 'did-resolver';
3
-
4
- import type { DidDocument, DidService, DidServiceEndpoint, DwnServiceEndpoint } from './types.js';
5
-
6
- export interface ParsedDid {
7
- did: string
8
- didUrl: string
9
- method: string
10
- id: string
11
- path?: string
12
- fragment?: string
13
- query?: string
14
- params?: ParsedDID['params']
15
- }
16
-
17
- export const DID_REGEX = /^did:([a-z0-9]+):((?:(?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))*:)*((?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))+))((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)(\/[^#?]*)?([?][^#]*)?(#.*)?$/;
18
-
19
- /**
20
- * Retrieves services from a given DID document based on provided options.
21
- * If no `id` or `type` filters are provided, all defined services are returned.
22
- *
23
- * Note: The DID document must adhere to the W3C DID specification.
24
- *
25
- * @param options - An object containing input parameters for retrieving services.
26
- * @param options.didDocument - The DID document from which services are retrieved.
27
- * @param options.id - Optional. A string representing the specific service ID to match. If provided, only the service with this ID will be returned.
28
- * @param options.type - Optional. A string representing the specific service type to match. If provided, only the service(s) of this type will be returned.
29
- *
30
- * @returns An array of services. If no matching service is found, an empty array is returned.
31
- *
32
- * @example
33
- *
34
- * const didDoc = { ... }; // W3C DID document
35
- * const services = getServices({ didDocument: didDoc, type: 'DecentralizedWebNode' });
36
- */
37
- export function getServices(options: {
38
- didDocument: DidDocument,
39
- id?: string,
40
- type?: string
41
- }): DidService[] {
42
- const { didDocument, id, type } = options ?? {};
43
-
44
- return didDocument?.service?.filter(service => {
45
- if (id) {
46
- const serviceId = service.id ?? '';
47
- const matchesExact = serviceId === id;
48
- const matchesFragment = id.startsWith('#') && serviceId.endsWith(id);
49
- if (!matchesExact && !matchesFragment) return false;
50
- }
51
- if (type && service.type !== type) return false;
52
- return true;
53
- }) ?? [ ];
54
- }
55
-
56
- export function getVerificationMethodIds(options: {
57
- didDocument: DidDocument,
58
- publicKeyJwk?: PublicKeyJwk,
59
- publicKeyMultibase?: string
60
- }): string | undefined {
61
- const { didDocument, publicKeyJwk, publicKeyMultibase } = options;
62
- if (!didDocument) throw new Error(`Required parameter missing: 'didDocument'`);
63
- if (!didDocument.verificationMethod) throw new Error('Given `didDocument` is missing `verificationMethod` entries.');
64
-
65
- for (let method of didDocument.verificationMethod) {
66
- if (publicKeyMultibase && 'publicKeyMultibase' in method) {
67
- if (publicKeyMultibase === method.publicKeyMultibase) {
68
- return method.id;
69
- }
70
- } else if (publicKeyJwk && 'crv' in publicKeyJwk &&
71
- 'publicKeyJwk' in method && 'crv' in method.publicKeyJwk) {
72
- if (publicKeyJwk.crv === method.publicKeyJwk.crv &&
73
- publicKeyJwk.x === method.publicKeyJwk.x) {
74
- return method.id;
75
- }
76
- }
77
- }
78
- }
79
-
80
- /**
81
- * Retrieves DID verification method types from a given DID document.
82
- *
83
- * Note: The DID document must adhere to the W3C DID specification.
84
- *
85
- * @param options - An object containing input parameters for retrieving types.
86
- * @param options.didDocument - The DID document from which types are retrieved.
87
- *
88
- * @returns An array of types. If no types were found, an empty array is returned.
89
- */
90
- export function getVerificationMethodTypes(options: {
91
- didDocument: Record<string, any>
92
- }): string[] {
93
- const { didDocument } = options;
94
-
95
- let types: string[] = [];
96
-
97
- for (let key in didDocument) {
98
- if (typeof didDocument[key] === 'object') {
99
- types = types.concat(getVerificationMethodTypes({
100
- didDocument: didDocument[key]
101
- }));
102
-
103
- } else if (key === 'type') {
104
- types.push(didDocument[key]);
105
- }
106
- }
107
-
108
- return [...new Set(types)]; // return only unique types
109
- }
110
-
111
- /**
112
- * Type guard function to check if the given endpoint is a DwnServiceEndpoint.
113
- *
114
- * @param key The endpoint to check.
115
- * @returns True if the endpoint is a DwnServiceEndpoint, false otherwise.
116
- */
117
- export function isDwnServiceEndpoint(endpoint: string | DidServiceEndpoint | DidServiceEndpoint[]): endpoint is DwnServiceEndpoint {
118
- return endpoint !== undefined &&
119
- typeof endpoint !== 'string' &&
120
- !Array.isArray(endpoint) &&
121
- 'nodes' in endpoint &&
122
- 'signingKeys' in endpoint;
123
- }
124
-
125
- export function parseDid({ didUrl }: { didUrl: string }): ParsedDid | undefined {
126
- const parsedDid: ParsedDid = parse(didUrl);
127
-
128
- return parsedDid;
129
- }