@enbox/dids 0.0.1

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 (104) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +1 -0
  3. package/dist/browser.js +77 -0
  4. package/dist/browser.js.map +7 -0
  5. package/dist/browser.mjs +77 -0
  6. package/dist/browser.mjs.map +7 -0
  7. package/dist/cjs/index.js +6303 -0
  8. package/dist/cjs/index.js.map +7 -0
  9. package/dist/cjs/package.json +1 -0
  10. package/dist/cjs/utils.js +245 -0
  11. package/dist/cjs/utils.js.map +7 -0
  12. package/dist/esm/bearer-did.js +201 -0
  13. package/dist/esm/bearer-did.js.map +1 -0
  14. package/dist/esm/did-error.js +62 -0
  15. package/dist/esm/did-error.js.map +1 -0
  16. package/dist/esm/did.js +114 -0
  17. package/dist/esm/did.js.map +1 -0
  18. package/dist/esm/index.js +16 -0
  19. package/dist/esm/index.js.map +1 -0
  20. package/dist/esm/methods/did-dht.js +1241 -0
  21. package/dist/esm/methods/did-dht.js.map +1 -0
  22. package/dist/esm/methods/did-ion.js +570 -0
  23. package/dist/esm/methods/did-ion.js.map +1 -0
  24. package/dist/esm/methods/did-jwk.js +298 -0
  25. package/dist/esm/methods/did-jwk.js.map +1 -0
  26. package/dist/esm/methods/did-key.js +983 -0
  27. package/dist/esm/methods/did-key.js.map +1 -0
  28. package/dist/esm/methods/did-method.js +53 -0
  29. package/dist/esm/methods/did-method.js.map +1 -0
  30. package/dist/esm/methods/did-web.js +83 -0
  31. package/dist/esm/methods/did-web.js.map +1 -0
  32. package/dist/esm/resolver/resolver-cache-level.js +101 -0
  33. package/dist/esm/resolver/resolver-cache-level.js.map +1 -0
  34. package/dist/esm/resolver/resolver-cache-noop.js +24 -0
  35. package/dist/esm/resolver/resolver-cache-noop.js.map +1 -0
  36. package/dist/esm/resolver/universal-resolver.js +187 -0
  37. package/dist/esm/resolver/universal-resolver.js.map +1 -0
  38. package/dist/esm/types/did-core.js +51 -0
  39. package/dist/esm/types/did-core.js.map +1 -0
  40. package/dist/esm/types/did-resolution.js +12 -0
  41. package/dist/esm/types/did-resolution.js.map +1 -0
  42. package/dist/esm/types/multibase.js +2 -0
  43. package/dist/esm/types/multibase.js.map +1 -0
  44. package/dist/esm/types/portable-did.js +2 -0
  45. package/dist/esm/types/portable-did.js.map +1 -0
  46. package/dist/esm/utils.js +458 -0
  47. package/dist/esm/utils.js.map +1 -0
  48. package/dist/types/bearer-did.d.ts +143 -0
  49. package/dist/types/bearer-did.d.ts.map +1 -0
  50. package/dist/types/did-error.d.ts +50 -0
  51. package/dist/types/did-error.d.ts.map +1 -0
  52. package/dist/types/did.d.ts +125 -0
  53. package/dist/types/did.d.ts.map +1 -0
  54. package/dist/types/index.d.ts +18 -0
  55. package/dist/types/index.d.ts.map +1 -0
  56. package/dist/types/methods/did-dht.d.ts +682 -0
  57. package/dist/types/methods/did-dht.d.ts.map +1 -0
  58. package/dist/types/methods/did-ion.d.ts +492 -0
  59. package/dist/types/methods/did-ion.d.ts.map +1 -0
  60. package/dist/types/methods/did-jwk.d.ts +236 -0
  61. package/dist/types/methods/did-jwk.d.ts.map +1 -0
  62. package/dist/types/methods/did-key.d.ts +499 -0
  63. package/dist/types/methods/did-key.d.ts.map +1 -0
  64. package/dist/types/methods/did-method.d.ts +238 -0
  65. package/dist/types/methods/did-method.d.ts.map +1 -0
  66. package/dist/types/methods/did-web.d.ts +37 -0
  67. package/dist/types/methods/did-web.d.ts.map +1 -0
  68. package/dist/types/resolver/resolver-cache-level.d.ts +86 -0
  69. package/dist/types/resolver/resolver-cache-level.d.ts.map +1 -0
  70. package/dist/types/resolver/resolver-cache-noop.d.ts +9 -0
  71. package/dist/types/resolver/resolver-cache-noop.d.ts.map +1 -0
  72. package/dist/types/resolver/universal-resolver.d.ts +109 -0
  73. package/dist/types/resolver/universal-resolver.d.ts.map +1 -0
  74. package/dist/types/types/did-core.d.ts +523 -0
  75. package/dist/types/types/did-core.d.ts.map +1 -0
  76. package/dist/types/types/did-resolution.d.ts +85 -0
  77. package/dist/types/types/did-resolution.d.ts.map +1 -0
  78. package/dist/types/types/multibase.d.ts +28 -0
  79. package/dist/types/types/multibase.d.ts.map +1 -0
  80. package/dist/types/types/portable-did.d.ts +59 -0
  81. package/dist/types/types/portable-did.d.ts.map +1 -0
  82. package/dist/types/utils.d.ts +378 -0
  83. package/dist/types/utils.d.ts.map +1 -0
  84. package/dist/utils.js +28 -0
  85. package/dist/utils.js.map +7 -0
  86. package/package.json +116 -0
  87. package/src/bearer-did.ts +287 -0
  88. package/src/did-error.ts +75 -0
  89. package/src/did.ts +186 -0
  90. package/src/index.ts +21 -0
  91. package/src/methods/did-dht.ts +1637 -0
  92. package/src/methods/did-ion.ts +887 -0
  93. package/src/methods/did-jwk.ts +410 -0
  94. package/src/methods/did-key.ts +1248 -0
  95. package/src/methods/did-method.ts +276 -0
  96. package/src/methods/did-web.ts +96 -0
  97. package/src/resolver/resolver-cache-level.ts +163 -0
  98. package/src/resolver/resolver-cache-noop.ts +26 -0
  99. package/src/resolver/universal-resolver.ts +238 -0
  100. package/src/types/did-core.ts +580 -0
  101. package/src/types/did-resolution.ts +93 -0
  102. package/src/types/multibase.ts +29 -0
  103. package/src/types/portable-did.ts +64 -0
  104. package/src/utils.ts +532 -0
@@ -0,0 +1,1241 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ var __rest = (this && this.__rest) || function (s, e) {
11
+ var t = {};
12
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
13
+ t[p] = s[p];
14
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
15
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
16
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
17
+ t[p[i]] = s[p[i]];
18
+ }
19
+ return t;
20
+ };
21
+ import bencode from 'bencode';
22
+ import { Convert } from '@enbox/common';
23
+ import { computeJwkThumbprint, Ed25519, LocalKeyManager, Secp256k1, Secp256r1, X25519 } from '@enbox/crypto';
24
+ import { AUTHORITATIVE_ANSWER, decode as dnsPacketDecode, encode as dnsPacketEncode } from '@dnsquery/dns-packet';
25
+ import { Did } from '../did.js';
26
+ import { DidMethod } from './did-method.js';
27
+ import { BearerDid } from '../bearer-did.js';
28
+ import { extractDidFragment } from '../utils.js';
29
+ import { DidError, DidErrorCode } from '../did-error.js';
30
+ import { DidVerificationRelationship } from '../types/did-core.js';
31
+ import { EMPTY_DID_RESOLUTION_RESULT } from '../types/did-resolution.js';
32
+ /**
33
+ * The default DID DHT Gateway or Pkarr Relay server to use when publishing and resolving DID
34
+ * documents.
35
+ */
36
+ const DEFAULT_GATEWAY_URI = 'https://did-dht-production.up.railway.app';
37
+ /**
38
+ * The version of the DID DHT specification that is implemented by this library.
39
+ *
40
+ * When a DID DHT document is published to the DHT network, the version of the specification that
41
+ * was used to create the document is included in the DNS TXT record for the root record. This
42
+ * allows clients to determine whether the DID DHT document is compatible with the client's
43
+ * implementation of the DID DHT specification. The version number is not present in the
44
+ * corresponding DID document.
45
+ *
46
+ * @see {@link https://did-dht.com | DID DHT Method Specification}
47
+ */
48
+ const DID_DHT_SPECIFICATION_VERSION = 0;
49
+ /**
50
+ * The default TTL for DNS records published to the DHT network.
51
+ *
52
+ * The recommended TTL value is 7200 seconds (2 hours) since it matches the default TTL for
53
+ * Mainline DHT records.
54
+ */
55
+ const DNS_RECORD_TTL = 7200;
56
+ /**
57
+ * Character used to separate distinct elements or entries in the DNS packet representation
58
+ * of a DID Document.
59
+ *
60
+ * For example, verification methods, verification relationships, and services are separated by
61
+ * semicolons (`;`) in the root record:
62
+ * ```
63
+ * vm=k1;auth=k1;asm=k2;inv=k3;del=k3;srv=s1
64
+ * ```
65
+ */
66
+ const PROPERTY_SEPARATOR = ';';
67
+ /**
68
+ * Character used to separate distinct values within a single element or entry in the DNS packet
69
+ * representation of a DID Document.
70
+ *
71
+ * For example, multiple key references for the `authentication` verification relationships are
72
+ * separated by commas (`,`):
73
+ * ```
74
+ * auth=0,1,2
75
+ * ```
76
+ */
77
+ const VALUE_SEPARATOR = ',';
78
+ /**
79
+ * Represents an optional extension to a DID Document’s DNS packet representation exposed as a
80
+ * type index.
81
+ *
82
+ * Type indexing is an OPTIONAL feature that enables DIDs to become discoverable. DIDs that wish to
83
+ * be discoverable and resolveable by type can include one or more types when publishing their DID
84
+ * document to a DID DHT Gateway.
85
+ *
86
+ * The registered DID types are published in the {@link https://did-dht.com/registry/index.html#indexed-types | DID DHT Registry}.
87
+ */
88
+ export var DidDhtRegisteredDidType;
89
+ (function (DidDhtRegisteredDidType) {
90
+ /**
91
+ * Type 0 is reserved for DIDs that do not wish to associate themselves with a specific type but
92
+ * wish to make themselves discoverable.
93
+ */
94
+ DidDhtRegisteredDidType[DidDhtRegisteredDidType["Discoverable"] = 0] = "Discoverable";
95
+ /**
96
+ * Organization
97
+ * @see {@link https://schema.org/Organization | schema definition}
98
+ */
99
+ DidDhtRegisteredDidType[DidDhtRegisteredDidType["Organization"] = 1] = "Organization";
100
+ /**
101
+ * Government Organization
102
+ * @see {@link https://schema.org/GovernmentOrganization | schema definition}
103
+ */
104
+ DidDhtRegisteredDidType[DidDhtRegisteredDidType["Government"] = 2] = "Government";
105
+ /**
106
+ * Corporation
107
+ * @see {@link https://schema.org/Corporation | schema definition}
108
+ */
109
+ DidDhtRegisteredDidType[DidDhtRegisteredDidType["Corporation"] = 3] = "Corporation";
110
+ /**
111
+ * Corporation
112
+ * @see {@link https://schema.org/Corporation | schema definition}
113
+ */
114
+ DidDhtRegisteredDidType[DidDhtRegisteredDidType["LocalBusiness"] = 4] = "LocalBusiness";
115
+ /**
116
+ * Software Package
117
+ * @see {@link https://schema.org/SoftwareSourceCode | schema definition}
118
+ */
119
+ DidDhtRegisteredDidType[DidDhtRegisteredDidType["SoftwarePackage"] = 5] = "SoftwarePackage";
120
+ /**
121
+ * Web App
122
+ * @see {@link https://schema.org/WebApplication | schema definition}
123
+ */
124
+ DidDhtRegisteredDidType[DidDhtRegisteredDidType["WebApp"] = 6] = "WebApp";
125
+ /**
126
+ * Financial Institution
127
+ * @see {@link https://schema.org/FinancialService | schema definition}
128
+ */
129
+ DidDhtRegisteredDidType[DidDhtRegisteredDidType["FinancialInstitution"] = 7] = "FinancialInstitution";
130
+ })(DidDhtRegisteredDidType || (DidDhtRegisteredDidType = {}));
131
+ /**
132
+ * Enumerates the types of keys that can be used in a DID DHT document.
133
+ *
134
+ * The DID DHT method supports various cryptographic key types. These key types are essential for
135
+ * the creation and management of DIDs and their associated cryptographic operations like signing
136
+ * and encryption. The registered key types are published in the DID DHT Registry and each is
137
+ * assigned a unique numerical value for use by client and gateway implementations.
138
+ *
139
+ * The registered key types are published in the {@link https://did-dht.com/registry/index.html#key-type-index | DID DHT Registry}.
140
+ */
141
+ export var DidDhtRegisteredKeyType;
142
+ (function (DidDhtRegisteredKeyType) {
143
+ /**
144
+ * Ed25519: A public-key signature system using the EdDSA (Edwards-curve Digital Signature
145
+ * Algorithm) and Curve25519.
146
+ */
147
+ DidDhtRegisteredKeyType[DidDhtRegisteredKeyType["Ed25519"] = 0] = "Ed25519";
148
+ /**
149
+ * secp256k1: A cryptographic curve used for digital signatures in a range of decentralized
150
+ * systems.
151
+ */
152
+ DidDhtRegisteredKeyType[DidDhtRegisteredKeyType["secp256k1"] = 1] = "secp256k1";
153
+ /**
154
+ * secp256r1: Also known as P-256 or prime256v1, this curve is used for cryptographic operations
155
+ * and is widely supported in various cryptographic libraries and standards.
156
+ */
157
+ DidDhtRegisteredKeyType[DidDhtRegisteredKeyType["secp256r1"] = 2] = "secp256r1";
158
+ /**
159
+ * X25519: A public key used for Diffie-Hellman key exchange using Curve25519.
160
+ */
161
+ DidDhtRegisteredKeyType[DidDhtRegisteredKeyType["X25519"] = 3] = "X25519";
162
+ })(DidDhtRegisteredKeyType || (DidDhtRegisteredKeyType = {}));
163
+ /**
164
+ * Maps {@link https://www.w3.org/TR/did-core/#verification-relationships | DID Core Verification Relationship}
165
+ * values to the corresponding record name in the DNS packet representation of a DHT DID document.
166
+ */
167
+ export var DidDhtVerificationRelationship;
168
+ (function (DidDhtVerificationRelationship) {
169
+ /**
170
+ * Specifies how the DID subject is expected to be authenticated.
171
+ */
172
+ DidDhtVerificationRelationship["authentication"] = "auth";
173
+ /**
174
+ * Specifies how the DID subject is expected to express claims, such as for issuing Verifiable
175
+ * Credentials.
176
+ */
177
+ DidDhtVerificationRelationship["assertionMethod"] = "asm";
178
+ /**
179
+ * Specifies a mechanism used by the DID subject to delegate a cryptographic capability to another
180
+ * party
181
+ */
182
+ DidDhtVerificationRelationship["capabilityDelegation"] = "del";
183
+ /**
184
+ * Specifies a verification method used by the DID subject to invoke a cryptographic capability.
185
+ */
186
+ DidDhtVerificationRelationship["capabilityInvocation"] = "inv";
187
+ /**
188
+ * Specifies how an entity can generate encryption material to communicate confidentially with the
189
+ * DID subject.
190
+ */
191
+ DidDhtVerificationRelationship["keyAgreement"] = "agm";
192
+ })(DidDhtVerificationRelationship || (DidDhtVerificationRelationship = {}));
193
+ /**
194
+ * Private helper that maps algorithm identifiers to their corresponding DID DHT
195
+ * {@link DidDhtRegisteredKeyType | registered key type}.
196
+ */
197
+ const AlgorithmToKeyTypeMap = {
198
+ Ed25519: DidDhtRegisteredKeyType.Ed25519,
199
+ ES256K: DidDhtRegisteredKeyType.secp256k1,
200
+ ES256: DidDhtRegisteredKeyType.secp256r1,
201
+ 'P-256': DidDhtRegisteredKeyType.secp256r1,
202
+ secp256k1: DidDhtRegisteredKeyType.secp256k1,
203
+ secp256r1: DidDhtRegisteredKeyType.secp256r1,
204
+ X25519: DidDhtRegisteredKeyType.X25519,
205
+ };
206
+ /**
207
+ * Private helper that maps did dht registered key types to their corresponding default algorithm identifiers.
208
+ */
209
+ const KeyTypeToDefaultAlgorithmMap = {
210
+ [DidDhtRegisteredKeyType.Ed25519]: 'EdDSA',
211
+ [DidDhtRegisteredKeyType.secp256k1]: 'ES256K',
212
+ [DidDhtRegisteredKeyType.secp256r1]: 'ES256',
213
+ [DidDhtRegisteredKeyType.X25519]: 'ECDH-ES+A256KW',
214
+ };
215
+ /**
216
+ * The `DidDht` class provides an implementation of the `did:dht` DID method.
217
+ *
218
+ * Features:
219
+ * - DID Creation: Create new `did:dht` DIDs.
220
+ * - DID Key Management: Instantiate a DID object from an existing verification method keys or
221
+ * or a key in a Key Management System (KMS). If supported by the KMS, a DID's
222
+ * key can be exported to a portable DID format.
223
+ * - DID Resolution: Resolve a `did:dht` to its corresponding DID Document stored in the DHT network.
224
+ * - Signature Operations: Sign and verify messages using keys associated with a DID.
225
+ *
226
+ * @remarks
227
+ * The `did:dht` method leverages the distributed nature of the Mainline DHT network for
228
+ * decentralized identity management. This method allows DIDs to be resolved without relying on
229
+ * centralized registries or ledgers, enhancing privacy and control for users. The DID Document is
230
+ * stored and retrieved from the DHT network, and the method includes optional mechanisms for
231
+ * discovering DIDs by type.
232
+ *
233
+ * The DID URI in the `did:dht` method includes a method-specific identifier called the Identity Key
234
+ * which corresponds to the DID's entry in the DHT network. The Identity Key required to make
235
+ * changes to the DID Document since Mainline DHT nodes validate the signature of each message
236
+ * before storing the value in the DHT.
237
+ *
238
+ * @see {@link https://did-dht.com | DID DHT Method Specification}
239
+ *
240
+ * @example
241
+ * ```ts
242
+ * // DID Creation
243
+ * const did = await DidDht.create();
244
+ *
245
+ * // DID Creation with a KMS
246
+ * const keyManager = new LocalKeyManager();
247
+ * const did = await DidDht.create({ keyManager });
248
+ *
249
+ * // DID Resolution
250
+ * const resolutionResult = await DidDht.resolve({ did: did.uri });
251
+ *
252
+ * // Signature Operations
253
+ * const signer = await did.getSigner();
254
+ * const signature = await signer.sign({ data: new TextEncoder().encode('Message') });
255
+ * const isValid = await signer.verify({ data: new TextEncoder().encode('Message'), signature });
256
+ *
257
+ * // Import / Export
258
+ *
259
+ * // Export a BearerDid object to the PortableDid format.
260
+ * const portableDid = await did.export();
261
+ *
262
+ * // Reconstruct a BearerDid object from a PortableDid
263
+ * const did = await DidDht.import(portableDid);
264
+ * ```
265
+ */
266
+ export class DidDht extends DidMethod {
267
+ /**
268
+ * Creates a new DID using the `did:dht` method formed from a newly generated key.
269
+ *
270
+ * @remarks
271
+ * The DID URI is formed by z-base-32 encoding the Identity Key public key and prefixing with
272
+ * `did:dht:`.
273
+ *
274
+ * Notes:
275
+ * - If no `options` are given, by default a new Ed25519 key will be generated which serves as the
276
+ * Identity Key.
277
+ *
278
+ * @example
279
+ * ```ts
280
+ * // DID Creation
281
+ * const did = await DidDht.create();
282
+ *
283
+ * // DID Creation with a KMS
284
+ * const keyManager = new LocalKeyManager();
285
+ * const did = await DidDht.create({ keyManager });
286
+ * ```
287
+ *
288
+ * @param params - The parameters for the create operation.
289
+ * @param params.keyManager - Optionally specify a Key Management System (KMS) used to generate
290
+ * keys and sign data.
291
+ * @param params.options - Optional parameters that can be specified when creating a new DID.
292
+ * @returns A Promise resolving to a {@link BearerDid} object representing the new DID.
293
+ */
294
+ static create() {
295
+ return __awaiter(this, arguments, void 0, function* ({ keyManager = new LocalKeyManager(), options = {} } = {}) {
296
+ // Before processing the create operation, validate DID-method-specific requirements to prevent
297
+ // keys from being generated unnecessarily.
298
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
299
+ // Check 1: Validate that the algorithm for any given verification method is supported by the
300
+ // DID DHT specification.
301
+ if ((_a = options.verificationMethods) === null || _a === void 0 ? void 0 : _a.some(vm => !(vm.algorithm in AlgorithmToKeyTypeMap))) {
302
+ throw new Error('One or more verification method algorithms are not supported');
303
+ }
304
+ // Check 2: Validate that the ID for any given verification method is unique.
305
+ const methodIds = (_b = options.verificationMethods) === null || _b === void 0 ? void 0 : _b.filter(vm => 'id' in vm).map(vm => vm.id);
306
+ if (methodIds && methodIds.length !== new Set(methodIds).size) {
307
+ throw new Error('One or more verification method IDs are not unique');
308
+ }
309
+ // Check 3: Validate that the required properties for any given services are present.
310
+ if ((_c = options.services) === null || _c === void 0 ? void 0 : _c.some(s => !s.id || !s.type || !s.serviceEndpoint)) {
311
+ throw new Error('One or more services are missing required properties');
312
+ }
313
+ // Generate random key material for the Identity Key.
314
+ const identityKeyUri = yield keyManager.generateKey({ algorithm: 'Ed25519' });
315
+ const identityKey = yield keyManager.getPublicKey({ keyUri: identityKeyUri });
316
+ // Compute the DID URI from the Identity Key.
317
+ const didUri = yield DidDhtUtils.identityKeyToIdentifier({ identityKey });
318
+ // Begin constructing the DID Document.
319
+ const document = Object.assign(Object.assign({ id: didUri }, options.alsoKnownAs && { alsoKnownAs: options.alsoKnownAs }), options.controllers && { controller: options.controllers });
320
+ // If the given verification methods do not contain an Identity Key, add one.
321
+ const verificationMethodsToAdd = [...(_d = options.verificationMethods) !== null && _d !== void 0 ? _d : []];
322
+ if (!(verificationMethodsToAdd === null || verificationMethodsToAdd === void 0 ? void 0 : verificationMethodsToAdd.some(vm => { var _a; return ((_a = vm.id) === null || _a === void 0 ? void 0 : _a.split('#').pop()) === '0'; }))) {
323
+ // Add the Identity Key to the beginning of the key set.
324
+ verificationMethodsToAdd.unshift({
325
+ algorithm: 'Ed25519',
326
+ id: '0',
327
+ purposes: ['authentication', 'assertionMethod', 'capabilityDelegation', 'capabilityInvocation']
328
+ });
329
+ }
330
+ // Generate random key material for the Identity Key and any additional verification methods.
331
+ // Add verification methods to the DID document.
332
+ for (const verificationMethod of verificationMethodsToAdd) {
333
+ // Generate a random key for the verification method, or if its the Identity Key's
334
+ // verification method (`id` is 0) use the key previously generated.
335
+ const keyUri = (verificationMethod.id && verificationMethod.id.split('#').pop() === '0')
336
+ ? identityKeyUri
337
+ : yield keyManager.generateKey({ algorithm: verificationMethod.algorithm });
338
+ const publicKey = yield keyManager.getPublicKey({ keyUri });
339
+ // Use the given ID, the key's ID, or the key's thumbprint as the verification method ID.
340
+ let methodId = (_f = (_e = verificationMethod.id) !== null && _e !== void 0 ? _e : publicKey.kid) !== null && _f !== void 0 ? _f : yield computeJwkThumbprint({ jwk: publicKey });
341
+ methodId = `${didUri}#${extractDidFragment(methodId)}`; // Remove fragment prefix, if any.
342
+ // Initialize the `verificationMethod` array if it does not already exist.
343
+ (_g = document.verificationMethod) !== null && _g !== void 0 ? _g : (document.verificationMethod = []);
344
+ // Add the verification method to the DID document.
345
+ document.verificationMethod.push({
346
+ id: methodId,
347
+ type: 'JsonWebKey',
348
+ controller: (_h = verificationMethod.controller) !== null && _h !== void 0 ? _h : didUri,
349
+ publicKeyJwk: publicKey,
350
+ });
351
+ // Add the verification method to the specified purpose properties of the DID document.
352
+ for (const purpose of (_j = verificationMethod.purposes) !== null && _j !== void 0 ? _j : []) {
353
+ // Initialize the purpose property if it does not already exist.
354
+ if (!document[purpose])
355
+ document[purpose] = [];
356
+ // Add the verification method to the purpose property.
357
+ document[purpose].push(methodId);
358
+ }
359
+ }
360
+ // Add services, if any, to the DID document.
361
+ (_k = options.services) === null || _k === void 0 ? void 0 : _k.forEach(service => {
362
+ var _a;
363
+ (_a = document.service) !== null && _a !== void 0 ? _a : (document.service = []);
364
+ service.id = `${didUri}#${service.id.split('#').pop()}`; // Remove fragment prefix, if any.
365
+ document.service.push(service);
366
+ });
367
+ // Create the BearerDid object, including the registered DID types (if any), and specify that
368
+ // the DID has not yet been published.
369
+ const did = new BearerDid({
370
+ uri: didUri,
371
+ document,
372
+ metadata: Object.assign({ published: false }, options.types && { types: options.types }),
373
+ keyManager
374
+ });
375
+ // By default, publish the DID document to a DHT Gateway unless explicitly disabled.
376
+ if ((_l = options.publish) !== null && _l !== void 0 ? _l : true) {
377
+ const registrationResult = yield DidDht.publish({ did, gatewayUri: options.gatewayUri });
378
+ did.metadata = registrationResult.didDocumentMetadata;
379
+ }
380
+ return did;
381
+ });
382
+ }
383
+ /**
384
+ * Instantiates a {@link BearerDid} object for the DID DHT method from a given {@link PortableDid}.
385
+ *
386
+ * This method allows for the creation of a `BearerDid` object using a previously created DID's
387
+ * key material, DID document, and metadata.
388
+ *
389
+ * @example
390
+ * ```ts
391
+ * // Export an existing BearerDid to PortableDid format.
392
+ * const portableDid = await did.export();
393
+ * // Reconstruct a BearerDid object from the PortableDid.
394
+ * const did = await DidDht.import({ portableDid });
395
+ * ```
396
+ *
397
+ * @param params - The parameters for the import operation.
398
+ * @param params.portableDid - The PortableDid object to import.
399
+ * @param params.keyManager - Optionally specify an external Key Management System (KMS) used to
400
+ * generate keys and sign data. If not given, a new
401
+ * {@link LocalKeyManager} instance will be created and
402
+ * used.
403
+ * @returns A Promise resolving to a `BearerDid` object representing the DID formed from the
404
+ * provided PortableDid.
405
+ * @throws An error if the PortableDid document does not contain any verification methods, lacks
406
+ * an Identity Key, or the keys for any verification method are missing in the key
407
+ * manager.
408
+ */
409
+ static import(_a) {
410
+ return __awaiter(this, arguments, void 0, function* ({ portableDid, keyManager = new LocalKeyManager() }) {
411
+ var _b;
412
+ // Verify the DID method is supported.
413
+ const parsedDid = Did.parse(portableDid.uri);
414
+ if ((parsedDid === null || parsedDid === void 0 ? void 0 : parsedDid.method) !== DidDht.methodName) {
415
+ throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported`);
416
+ }
417
+ const did = yield BearerDid.import({ portableDid, keyManager });
418
+ // Validate that the given verification methods contain an Identity Key.
419
+ if (!((_b = did.document.verificationMethod) === null || _b === void 0 ? void 0 : _b.some(vm => { var _a; return ((_a = vm.id) === null || _a === void 0 ? void 0 : _a.split('#').pop()) === '0'; }))) {
420
+ throw new DidError(DidErrorCode.InvalidDidDocument, `DID document must contain an Identity Key`);
421
+ }
422
+ return did;
423
+ });
424
+ }
425
+ /**
426
+ * Given the W3C DID Document of a `did:dht` DID, return the verification method that will be used
427
+ * for signing messages and credentials. If given, the `methodId` parameter is used to select the
428
+ * verification method. If not given, the Identity Key's verification method with an ID fragment
429
+ * of '#0' is used.
430
+ *
431
+ * @param params - The parameters for the `getSigningMethod` operation.
432
+ * @param params.didDocument - DID Document to get the verification method from.
433
+ * @param params.methodId - ID of the verification method to use for signing.
434
+ * @returns Verification method to use for signing.
435
+ */
436
+ static getSigningMethod(_a) {
437
+ return __awaiter(this, arguments, void 0, function* ({ didDocument, methodId = '#0' }) {
438
+ var _b;
439
+ // Verify the DID method is supported.
440
+ const parsedDid = Did.parse(didDocument.id);
441
+ if (parsedDid && parsedDid.method !== this.methodName) {
442
+ throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported: ${parsedDid.method}`);
443
+ }
444
+ // Attempt to find a verification method that matches the given method ID, or if not given,
445
+ // find the first verification method intended for signing claims.
446
+ const verificationMethod = (_b = didDocument.verificationMethod) === null || _b === void 0 ? void 0 : _b.find(vm => { var _a, _b; return extractDidFragment(vm.id) === ((_a = extractDidFragment(methodId)) !== null && _a !== void 0 ? _a : extractDidFragment((_b = didDocument.assertionMethod) === null || _b === void 0 ? void 0 : _b[0])); });
447
+ if (!(verificationMethod && verificationMethod.publicKeyJwk)) {
448
+ throw new DidError(DidErrorCode.InternalError, 'A verification method intended for signing could not be determined from the DID Document');
449
+ }
450
+ return verificationMethod;
451
+ });
452
+ }
453
+ /**
454
+ * Publishes a DID to the DHT, making it publicly discoverable and resolvable.
455
+ *
456
+ * This method handles the publication of a DID Document associated with a `did:dht` DID to the
457
+ * Mainline DHT network. The publication process involves storing the DID Document in Mainline DHT
458
+ * via a Pkarr relay server.
459
+ *
460
+ * @remarks
461
+ * - This method is typically invoked automatically during the creation of a new DID unless the
462
+ * `publish` option is set to `false`.
463
+ * - For existing, unpublished DIDs, it can be used to publish the DID Document to Mainline DHT.
464
+ * - The method relies on the specified Pkarr relay server to interface with the DHT network.
465
+ *
466
+ * @example
467
+ * ```ts
468
+ * // Generate a new DID and keys but explicitly disable publishing.
469
+ * const did = await DidDht.create({ options: { publish: false } });
470
+ * // Publish the DID to the DHT.
471
+ * const registrationResult = await DidDht.publish({ did });
472
+ * // `registrationResult.didDocumentMetadata.published` is true if the DID was successfully published.
473
+ * ```
474
+ *
475
+ * @param params - The parameters for the `publish` operation.
476
+ * @param params.did - The `BearerDid` object representing the DID to be published.
477
+ * @param params.gatewayUri - Optional. The URI of a server involved in executing DID method
478
+ * operations. In the context of publishing, the endpoint is expected
479
+ * to be a DID DHT Gateway or Pkarr Relay. If not specified, a default
480
+ * gateway node is used.
481
+ * @returns A promise that resolves to a {@link DidRegistrationResult} object that contains
482
+ * the result of registering the DID with a DID DHT Gateway or Pkarr relay.
483
+ */
484
+ static publish(_a) {
485
+ return __awaiter(this, arguments, void 0, function* ({ did, gatewayUri = DEFAULT_GATEWAY_URI }) {
486
+ const registrationResult = yield DidDhtDocument.put({ did, gatewayUri });
487
+ return registrationResult;
488
+ });
489
+ }
490
+ /**
491
+ * Resolves a `did:dht` identifier to its corresponding DID document.
492
+ *
493
+ * This method performs the resolution of a `did:dht` DID, retrieving its DID Document from the
494
+ * Mainline DHT network. The process involves querying the DHT network via a Pkarr relay server to
495
+ * retrieve the DID Document that corresponds to the given DID identifier.
496
+ *
497
+ * @remarks
498
+ * - If a `gatewayUri` option is not specified, a default Pkarr relay is used to access the DHT
499
+ * network.
500
+ * - It decodes the DID identifier and retrieves the associated DID Document and metadata.
501
+ * - In case of resolution failure, appropriate error information is returned.
502
+ *
503
+ * @example
504
+ * ```ts
505
+ * const resolutionResult = await DidDht.resolve('did:dht:example');
506
+ * ```
507
+ *
508
+ * @param didUri - The DID to be resolved.
509
+ * @param options - Optional parameters for resolving the DID. Unused by this DID method.
510
+ * @returns A Promise resolving to a {@link DidResolutionResult} object representing the result of
511
+ * the resolution.
512
+ */
513
+ static resolve(didUri_1) {
514
+ return __awaiter(this, arguments, void 0, function* (didUri, options = {}) {
515
+ var _a;
516
+ // To execute the read method operation, use the given gateway URI or a default.
517
+ const gatewayUri = (_a = options === null || options === void 0 ? void 0 : options.gatewayUri) !== null && _a !== void 0 ? _a : DEFAULT_GATEWAY_URI;
518
+ try {
519
+ // Attempt to decode the z-base-32-encoded identifier.
520
+ yield DidDhtUtils.identifierToIdentityKey({ didUri });
521
+ // Attempt to retrieve the DID document and metadata from the DHT network.
522
+ const { didDocument, didDocumentMetadata } = yield DidDhtDocument.get({ didUri, gatewayUri });
523
+ // If the DID document was retrieved successfully, return it.
524
+ return Object.assign(Object.assign({}, EMPTY_DID_RESOLUTION_RESULT), { didDocument,
525
+ didDocumentMetadata });
526
+ }
527
+ catch (error) {
528
+ // Rethrow any unexpected errors that are not a `DidError`.
529
+ if (!(error instanceof DidError))
530
+ throw new Error(error);
531
+ // Return a DID Resolution Result with the appropriate error code.
532
+ return Object.assign(Object.assign({}, EMPTY_DID_RESOLUTION_RESULT), { didResolutionMetadata: Object.assign({ error: error.code }, error.message && { errorMessage: error.message }) });
533
+ }
534
+ });
535
+ }
536
+ }
537
+ /**
538
+ * Name of the DID method, as defined in the DID DHT specification.
539
+ */
540
+ DidDht.methodName = 'dht';
541
+ /**
542
+ * The `DidDhtDocument` class provides functionality for interacting with the DID document stored in
543
+ * Mainline DHT in support of DID DHT method create, resolve, update, and deactivate operations.
544
+ *
545
+ * This class includes methods for retrieving and publishing DID documents to and from the DHT,
546
+ * using DNS packet encoding and DID DHT Gateway or Pkarr Relay servers.
547
+ */
548
+ export class DidDhtDocument {
549
+ /**
550
+ * Retrieves a DID document and its metadata from the DHT network.
551
+ *
552
+ * @param params - The parameters for the get operation.
553
+ * @param params.didUri - The DID URI containing the Identity Key.
554
+ * @param params.gatewayUri - The DID DHT Gateway or Pkarr Relay URI.
555
+ * @returns A Promise resolving to a {@link DidResolutionResult} object containing the DID
556
+ * document and its metadata.
557
+ */
558
+ static get(_a) {
559
+ return __awaiter(this, arguments, void 0, function* ({ didUri, gatewayUri }) {
560
+ // Decode the z-base-32 DID identifier to public key as a byte array.
561
+ const publicKeyBytes = DidDhtUtils.identifierToIdentityKeyBytes({ didUri });
562
+ // Retrieve the signed BEP44 message from a DID DHT Gateway or Pkarr relay.
563
+ const bep44Message = yield DidDhtDocument.pkarrGet({ gatewayUri, publicKeyBytes });
564
+ // Verify the signature of the BEP44 message and parse the value to a DNS packet.
565
+ const dnsPacket = yield DidDhtUtils.parseBep44GetMessage({ bep44Message });
566
+ // Convert the DNS packet to a DID document and metadata.
567
+ const resolutionResult = yield DidDhtDocument.fromDnsPacket({ didUri, dnsPacket });
568
+ // Set the version ID of the DID document metadata to the sequence number of the BEP44 message.
569
+ resolutionResult.didDocumentMetadata.versionId = bep44Message.seq.toString();
570
+ return resolutionResult;
571
+ });
572
+ }
573
+ /**
574
+ * Publishes a DID document to the DHT network.
575
+ *
576
+ * @param params - The parameters to use when publishing the DID document to the DHT network.
577
+ * @param params.did - The DID object whose DID document will be published.
578
+ * @param params.gatewayUri - The DID DHT Gateway or Pkarr Relay URI.
579
+ * @returns A promise that resolves to a {@link DidRegistrationResult} object that contains
580
+ * the result of registering the DID with a DID DHT Gateway or Pkarr relay.
581
+ */
582
+ static put(_a) {
583
+ return __awaiter(this, arguments, void 0, function* ({ did, gatewayUri }) {
584
+ // Convert the DID document and DID metadata (such as DID types) to a DNS packet.
585
+ const dnsPacket = yield DidDhtDocument.toDnsPacket({
586
+ didDocument: did.document,
587
+ didMetadata: did.metadata,
588
+ authoritativeGatewayUris: [gatewayUri]
589
+ });
590
+ // Create a signed BEP44 put message from the DNS packet.
591
+ const bep44Message = yield DidDhtUtils.createBep44PutMessage({
592
+ dnsPacket,
593
+ publicKeyBytes: DidDhtUtils.identifierToIdentityKeyBytes({ didUri: did.uri }),
594
+ signer: yield did.getSigner({ methodId: '0' })
595
+ });
596
+ // Publish the DNS packet to the DHT network.
597
+ const putResult = yield DidDhtDocument.pkarrPut({ gatewayUri, bep44Message });
598
+ // Return the result of processing the PUT operation, including the updated DID metadata with
599
+ // the version ID and the publishing result.
600
+ return {
601
+ didDocument: did.document,
602
+ didDocumentMetadata: Object.assign(Object.assign({}, did.metadata), { published: putResult, versionId: bep44Message.seq.toString() }),
603
+ didRegistrationMetadata: {}
604
+ };
605
+ });
606
+ }
607
+ /**
608
+ * Retrieves a signed BEP44 message from a DID DHT Gateway or Pkarr Relay server.
609
+ *
610
+ * @see {@link https://github.com/Nuhvi/pkarr/blob/main/design/relays.md | Pkarr Relay design}
611
+ *
612
+ * @param params
613
+ * @param params.gatewayUri - The DID DHT Gateway or Pkarr Relay URI.
614
+ * @param params.publicKeyBytes - The public key bytes of the Identity Key, z-base-32 encoded.
615
+ * @returns A promise resolving to a BEP44 message containing the signed DNS packet.
616
+ */
617
+ static pkarrGet(_a) {
618
+ return __awaiter(this, arguments, void 0, function* ({ gatewayUri, publicKeyBytes }) {
619
+ // The identifier (key in the DHT) is the z-base-32 encoding of the Identity Key.
620
+ const identifier = Convert.uint8Array(publicKeyBytes).toBase32Z();
621
+ // Concatenate the gateway URI with the identifier to form the full URL.
622
+ const url = new URL(identifier, gatewayUri).href;
623
+ // Transmit the Get request to the DID DHT Gateway or Pkarr Relay and get the response.
624
+ let response;
625
+ try {
626
+ response = yield fetch(url, { method: 'GET' });
627
+ if (!response.ok) {
628
+ throw new DidError(DidErrorCode.NotFound, `Pkarr record not found for: ${identifier}`);
629
+ }
630
+ }
631
+ catch (error) {
632
+ if (error instanceof DidError)
633
+ throw error;
634
+ throw new DidError(DidErrorCode.InternalError, `Failed to fetch Pkarr record: ${error.message}`);
635
+ }
636
+ // Read the Fetch Response stream into a byte array.
637
+ const messageBytes = yield response.arrayBuffer();
638
+ if (!messageBytes) {
639
+ throw new DidError(DidErrorCode.NotFound, `Pkarr record not found for: ${identifier}`);
640
+ }
641
+ if (messageBytes.byteLength < 72) {
642
+ throw new DidError(DidErrorCode.InvalidDidDocumentLength, `Pkarr response must be at least 72 bytes but got: ${messageBytes.byteLength}`);
643
+ }
644
+ if (messageBytes.byteLength > 1072) {
645
+ throw new DidError(DidErrorCode.InvalidDidDocumentLength, `Pkarr response exceeds 1000 byte limit: ${messageBytes.byteLength}`);
646
+ }
647
+ // Decode the BEP44 message from the byte array.
648
+ const bep44Message = {
649
+ k: publicKeyBytes,
650
+ seq: Number(new DataView(messageBytes).getBigUint64(64)),
651
+ sig: new Uint8Array(messageBytes, 0, 64),
652
+ v: new Uint8Array(messageBytes, 72)
653
+ };
654
+ return bep44Message;
655
+ });
656
+ }
657
+ /**
658
+ * Publishes a signed BEP44 message to a DID DHT Gateway or Pkarr Relay server.
659
+ *
660
+ * @see {@link https://github.com/Nuhvi/pkarr/blob/main/design/relays.md | Pkarr Relay design}
661
+ *
662
+ * @param params - The parameters to use when publishing a signed BEP44 message to a Pkarr relay server.
663
+ * @param params.gatewayUri - The DID DHT Gateway or Pkarr Relay URI.
664
+ * @param params.bep44Message - The BEP44 message to be published, containing the signed DNS packet.
665
+ * @returns A promise resolving to `true` if the message was successfully published, otherwise `false`.
666
+ */
667
+ static pkarrPut(_a) {
668
+ return __awaiter(this, arguments, void 0, function* ({ gatewayUri, bep44Message }) {
669
+ // The identifier (key in the DHT) is the z-base-32 encoding of the Identity Key.
670
+ const identifier = Convert.uint8Array(bep44Message.k).toBase32Z();
671
+ // Concatenate the gateway URI with the identifier to form the full URL.
672
+ const url = new URL(identifier, gatewayUri).href;
673
+ // Construct the body of the request according to the Pkarr relay specification.
674
+ const body = new Uint8Array(bep44Message.v.length + 72);
675
+ body.set(bep44Message.sig, 0);
676
+ new DataView(body.buffer).setBigUint64(bep44Message.sig.length, BigInt(bep44Message.seq));
677
+ body.set(bep44Message.v, bep44Message.sig.length + 8);
678
+ // Transmit the Put request to the Pkarr relay and get the response.
679
+ let response;
680
+ try {
681
+ response = yield fetch(url, {
682
+ method: 'PUT',
683
+ headers: { 'Content-Type': 'application/octet-stream' },
684
+ body
685
+ });
686
+ }
687
+ catch (error) {
688
+ throw new DidError(DidErrorCode.InternalError, `Failed to put Pkarr record for identifier ${identifier}: ${error.message}`);
689
+ }
690
+ // Return `true` if the DHT request was successful, otherwise return `false`.
691
+ return response.ok;
692
+ });
693
+ }
694
+ /**
695
+ * Converts a DNS packet to a DID document according to the DID DHT specification.
696
+ *
697
+ * @see {@link https://did-dht.com/#dids-as-dns-records | DID DHT Specification, § DIDs as DNS Records}
698
+ *
699
+ * @param params - The parameters to use when converting a DNS packet to a DID document.
700
+ * @param params.didUri - The DID URI of the DID document.
701
+ * @param params.dnsPacket - The DNS packet to convert to a DID document.
702
+ * @returns A Promise resolving to a {@link DidResolutionResult} object containing the DID
703
+ * document and its metadata.
704
+ */
705
+ static fromDnsPacket(_a) {
706
+ return __awaiter(this, arguments, void 0, function* ({ didUri, dnsPacket }) {
707
+ var _b, _c, _d;
708
+ // Begin constructing the DID Document.
709
+ const didDocument = { id: didUri };
710
+ // Since the DID document is being retrieved from the DHT, it is considered published.
711
+ const didDocumentMetadata = {
712
+ published: true
713
+ };
714
+ const idLookup = new Map();
715
+ for (const answer of (_b = dnsPacket === null || dnsPacket === void 0 ? void 0 : dnsPacket.answers) !== null && _b !== void 0 ? _b : []) {
716
+ // DID DHT properties are ONLY present in DNS TXT records.
717
+ if (answer.type !== 'TXT')
718
+ continue;
719
+ // Get the DID DHT record identifier (e.g., k0, aka, did, etc.) from the DNS resource name.
720
+ const dnsRecordId = answer.name.split('.')[0].substring(1);
721
+ switch (true) {
722
+ // Process an also known as record.
723
+ case dnsRecordId.startsWith('aka'): {
724
+ // Decode the DNS TXT record data value to a string.
725
+ const data = DidDhtUtils.parseTxtDataToString(answer.data);
726
+ // Add the 'alsoKnownAs' property to the DID document.
727
+ didDocument.alsoKnownAs = data.split(VALUE_SEPARATOR);
728
+ break;
729
+ }
730
+ // Process a controller record.
731
+ case dnsRecordId.startsWith('cnt'): {
732
+ // Decode the DNS TXT record data value to a string.
733
+ const data = DidDhtUtils.parseTxtDataToString(answer.data);
734
+ // Add the 'controller' property to the DID document.
735
+ didDocument.controller = data.includes(VALUE_SEPARATOR) ? data.split(VALUE_SEPARATOR) : data;
736
+ break;
737
+ }
738
+ // Process verification methods.
739
+ case dnsRecordId.startsWith('k'): {
740
+ // Get the key type (t), Base64URL-encoded public key (k), algorithm (a), and
741
+ // optionally, controller (c) or Verification Method ID (id) from the decoded TXT record data.
742
+ const { id, t, k, c, a: parsedAlg } = DidDhtUtils.parseTxtDataToObject(answer.data);
743
+ // Convert the public key from Base64URL format to a byte array.
744
+ const publicKeyBytes = Convert.base64Url(k).toUint8Array();
745
+ // Use the key type integer to look up the cryptographic curve name.
746
+ const namedCurve = DidDhtRegisteredKeyType[Number(t)];
747
+ // Convert the public key from a byte array to JWK format.
748
+ let publicKey = yield DidDhtUtils.keyConverter(namedCurve).bytesToPublicKey({ publicKeyBytes });
749
+ publicKey.alg = parsedAlg || KeyTypeToDefaultAlgorithmMap[Number(t)];
750
+ // TOOD: when this is complete https://github.com/TBD54566975/web5-js/issues/638 then we can add this back and
751
+ // update the test vectors kid back to '0'
752
+ // if(dnsRecordId === 'k0') {
753
+ // publicKey.kid = '0';
754
+ // }
755
+ // Determine the Verification Method ID: '0' for the identity key,
756
+ // the id from the TXT Data Object, or the JWK thumbprint if an explicity Verification Method ID not defined.
757
+ const vmId = dnsRecordId === 'k0' ? '0' : id !== undefined ? id : yield computeJwkThumbprint({ jwk: publicKey });
758
+ // Initialize the `verificationMethod` array if it does not already exist.
759
+ (_c = didDocument.verificationMethod) !== null && _c !== void 0 ? _c : (didDocument.verificationMethod = []);
760
+ // Prepend the DID URI to the ID fragment to form the full verification method ID.
761
+ const methodId = `${didUri}#${vmId}`;
762
+ // Add the verification method to the DID document.
763
+ didDocument.verificationMethod.push({
764
+ id: methodId,
765
+ type: 'JsonWebKey',
766
+ controller: c !== null && c !== void 0 ? c : didUri,
767
+ publicKeyJwk: publicKey,
768
+ });
769
+ // Add a mapping from the DNS record ID (e.g., 'k0', 'k1', etc.) to the verification
770
+ // method ID (e.g., 'did:dht:...#0', etc.).
771
+ idLookup.set(dnsRecordId, methodId);
772
+ break;
773
+ }
774
+ // Process services.
775
+ case dnsRecordId.startsWith('s'): {
776
+ // Get the service ID fragment (id), type (t), service endpoint (se), and optionally,
777
+ // other properties from the decoded TXT record data.
778
+ const _e = DidDhtUtils.parseTxtDataToObject(answer.data), { id, t, se } = _e, customProperties = __rest(_e, ["id", "t", "se"]);
779
+ // if multi-values: 'a,b,c' -> ['a', 'b', 'c'], if single-value: 'a' -> ['a']
780
+ // NOTE: The service endpoint technically can either be a string or an array of strings,
781
+ // we enforce an array for single-value to simplify verification of vector 3 in the spec: https://did-dht.com/#vector-3
782
+ const serviceEndpoint = se.includes(VALUE_SEPARATOR) ? se.split(VALUE_SEPARATOR) : [se];
783
+ // Convert custom property values to either a string or an array of strings.
784
+ const serviceProperties = Object.fromEntries(Object.entries(customProperties).map(([k, v]) => [k, v.includes(VALUE_SEPARATOR) ? v.split(VALUE_SEPARATOR) : v]));
785
+ // Initialize the `service` array if it does not already exist.
786
+ (_d = didDocument.service) !== null && _d !== void 0 ? _d : (didDocument.service = []);
787
+ didDocument.service.push(Object.assign(Object.assign({}, serviceProperties), { id: `${didUri}#${id}`, type: t, serviceEndpoint }));
788
+ break;
789
+ }
790
+ // Process DID DHT types.
791
+ case dnsRecordId.startsWith('typ'): {
792
+ // Decode the DNS TXT record data value to an object.
793
+ const { id: types } = DidDhtUtils.parseTxtDataToObject(answer.data);
794
+ // Add the DID DHT Registered DID Types represented as numbers to DID metadata.
795
+ didDocumentMetadata.types = types.split(VALUE_SEPARATOR).map(typeInteger => Number(typeInteger));
796
+ break;
797
+ }
798
+ // Process root record.
799
+ case dnsRecordId.startsWith('did'): {
800
+ // Helper function that maps verification relationship values to verification method IDs.
801
+ const recordIdsToMethodIds = (data) => data
802
+ .split(VALUE_SEPARATOR)
803
+ .map(dnsRecordId => idLookup.get(dnsRecordId))
804
+ .filter((id) => typeof id === 'string');
805
+ // Decode the DNS TXT record data and destructure verification relationship properties.
806
+ const { auth, asm, del, inv, agm } = DidDhtUtils.parseTxtDataToObject(answer.data);
807
+ // Add the verification relationships, if any, to the DID document.
808
+ if (auth)
809
+ didDocument.authentication = recordIdsToMethodIds(auth);
810
+ if (asm)
811
+ didDocument.assertionMethod = recordIdsToMethodIds(asm);
812
+ if (del)
813
+ didDocument.capabilityDelegation = recordIdsToMethodIds(del);
814
+ if (inv)
815
+ didDocument.capabilityInvocation = recordIdsToMethodIds(inv);
816
+ if (agm)
817
+ didDocument.keyAgreement = recordIdsToMethodIds(agm);
818
+ break;
819
+ }
820
+ }
821
+ }
822
+ return { didDocument, didDocumentMetadata, didResolutionMetadata: {} };
823
+ });
824
+ }
825
+ /**
826
+ * Converts a DID document to a DNS packet according to the DID DHT specification.
827
+ *
828
+ * @see {@link https://did-dht.com/#dids-as-dns-records | DID DHT Specification, § DIDs as DNS Records}
829
+ *
830
+ * @param params - The parameters to use when converting a DID document to a DNS packet.
831
+ * @param params.didDocument - The DID document to convert to a DNS packet.
832
+ * @param params.didMetadata - The DID metadata to include in the DNS packet.
833
+ * @param params.authoritativeGatewayUris - The URIs of the Authoritative Gateways to generate NS records from.
834
+ * @param params.previousDidProof - The signature proof that this DID is linked to the given previous DID.
835
+ * @returns A promise that resolves to a DNS packet.
836
+ */
837
+ static toDnsPacket(_a) {
838
+ return __awaiter(this, arguments, void 0, function* ({ didDocument, didMetadata, authoritativeGatewayUris, previousDidProof }) {
839
+ var _b, _c, _d, _e, _f;
840
+ const txtRecords = [];
841
+ const nsRecords = [];
842
+ const idLookup = new Map();
843
+ const serviceIds = [];
844
+ const verificationMethodIds = [];
845
+ // Add `_prv._did.` TXT record if previous DID proof is provided and valid.
846
+ if (previousDidProof !== undefined) {
847
+ const { signature, previousDid } = previousDidProof;
848
+ yield DidDhtUtils.validatePreviousDidProof({
849
+ newDid: didDocument.id,
850
+ previousDidProof
851
+ });
852
+ txtRecords.push({
853
+ type: 'TXT',
854
+ name: '_prv._did.',
855
+ ttl: DNS_RECORD_TTL,
856
+ data: `id=${previousDid};s=${signature}`
857
+ });
858
+ }
859
+ // Add DNS TXT records if the DID document contains an `alsoKnownAs` property.
860
+ if (didDocument.alsoKnownAs) {
861
+ txtRecords.push({
862
+ type: 'TXT',
863
+ name: '_aka._did.',
864
+ ttl: DNS_RECORD_TTL,
865
+ data: didDocument.alsoKnownAs.join(VALUE_SEPARATOR)
866
+ });
867
+ }
868
+ // Add DNS TXT records if the DID document contains a `controller` property.
869
+ if (didDocument.controller) {
870
+ const controller = Array.isArray(didDocument.controller)
871
+ ? didDocument.controller.join(VALUE_SEPARATOR)
872
+ : didDocument.controller;
873
+ txtRecords.push({
874
+ type: 'TXT',
875
+ name: '_cnt._did.',
876
+ ttl: DNS_RECORD_TTL,
877
+ data: controller
878
+ });
879
+ }
880
+ // Add DNS TXT records for each verification method.
881
+ for (const [index, verificationMethod] of (_c = (_b = didDocument.verificationMethod) === null || _b === void 0 ? void 0 : _b.entries()) !== null && _c !== void 0 ? _c : []) {
882
+ const dnsRecordId = `k${index}`;
883
+ verificationMethodIds.push(dnsRecordId);
884
+ let methodId = verificationMethod.id.split('#').pop(); // Remove fragment prefix, if any.
885
+ idLookup.set(methodId, dnsRecordId);
886
+ const publicKey = verificationMethod.publicKeyJwk;
887
+ if (!((publicKey === null || publicKey === void 0 ? void 0 : publicKey.crv) && publicKey.crv in AlgorithmToKeyTypeMap)) {
888
+ throw new DidError(DidErrorCode.InvalidPublicKeyType, `Verification method '${verificationMethod.id}' contains an unsupported key type: ${(_d = publicKey === null || publicKey === void 0 ? void 0 : publicKey.crv) !== null && _d !== void 0 ? _d : 'undefined'}`);
889
+ }
890
+ // Use the public key's `crv` property to get the DID DHT key type.
891
+ const keyType = DidDhtRegisteredKeyType[publicKey.crv];
892
+ // Convert the public key from JWK format to a byte array.
893
+ const publicKeyBytes = yield DidDhtUtils.keyConverter(publicKey.crv).publicKeyToBytes({ publicKey });
894
+ // Convert the public key from a byte array to Base64URL format.
895
+ const publicKeyBase64Url = Convert.uint8Array(publicKeyBytes).toBase64Url();
896
+ // Define the data for the DNS TXT record.
897
+ const txtData = [`t=${keyType}`, `k=${publicKeyBase64Url}`];
898
+ // if the methodId is not the identity key or a thumbprint, explicity define the id within the DNS TXT record.
899
+ // otherwise the id can be inferred from the thumbprint.
900
+ if (methodId !== '0' && (yield computeJwkThumbprint({ jwk: publicKey })) !== methodId) {
901
+ txtData.unshift(`id=${methodId}`);
902
+ }
903
+ // Only set the algorithm property (`a`) if it differs from the default algorithm for the key type.
904
+ if (publicKey.alg !== KeyTypeToDefaultAlgorithmMap[keyType]) {
905
+ txtData.push(`a=${publicKey.alg}`);
906
+ }
907
+ // Add the controller property, if set to a value other than the Identity Key (DID Subject).
908
+ if (verificationMethod.controller !== didDocument.id)
909
+ txtData.push(`c=${verificationMethod.controller}`);
910
+ // Add a TXT record for the verification method.
911
+ txtRecords.push({
912
+ type: 'TXT',
913
+ name: `_${dnsRecordId}._did.`,
914
+ ttl: DNS_RECORD_TTL,
915
+ data: txtData.join(PROPERTY_SEPARATOR)
916
+ });
917
+ }
918
+ // Add DNS TXT records for each service.
919
+ (_e = didDocument.service) === null || _e === void 0 ? void 0 : _e.forEach((service, index) => {
920
+ const dnsRecordId = `s${index}`;
921
+ serviceIds.push(dnsRecordId);
922
+ let { id, type: t, serviceEndpoint: se } = service, customProperties = __rest(service, ["id", "type", "serviceEndpoint"]);
923
+ id = extractDidFragment(id);
924
+ se = Array.isArray(se) ? se.join(',') : se;
925
+ // Define the data for the DNS TXT record.
926
+ const txtData = Object.entries(Object.assign({ id, t, se }, customProperties)).map(([key, value]) => `${key}=${value}`);
927
+ const txtDataString = txtData.join(PROPERTY_SEPARATOR);
928
+ const data = DidDhtUtils.chunkDataIfNeeded(txtDataString);
929
+ // Add a TXT record for the verification method.
930
+ txtRecords.push({
931
+ type: 'TXT',
932
+ name: `_${dnsRecordId}._did.`,
933
+ ttl: DNS_RECORD_TTL,
934
+ data
935
+ });
936
+ });
937
+ // Initialize the root DNS TXT record with the DID DHT specification version.
938
+ const rootRecord = [`v=${DID_DHT_SPECIFICATION_VERSION}`];
939
+ // Add verification methods to the root record.
940
+ if (verificationMethodIds.length) {
941
+ rootRecord.push(`vm=${verificationMethodIds.join(VALUE_SEPARATOR)}`);
942
+ }
943
+ // Add verification relationships to the root record.
944
+ Object.keys(DidVerificationRelationship).forEach(relationship => {
945
+ var _a;
946
+ // Collect the verification method IDs for the given relationship.
947
+ const dnsRecordIds = (_a = didDocument[relationship]) === null || _a === void 0 ? void 0 : _a.map(id => idLookup.get(id.split('#').pop()));
948
+ // If the relationship includes verification methods, add them to the root record.
949
+ if (dnsRecordIds) {
950
+ const recordName = DidDhtVerificationRelationship[relationship];
951
+ rootRecord.push(`${recordName}=${dnsRecordIds.join(VALUE_SEPARATOR)}`);
952
+ }
953
+ });
954
+ // Add services to the root record.
955
+ if (serviceIds.length) {
956
+ rootRecord.push(`svc=${serviceIds.join(VALUE_SEPARATOR)}`);
957
+ }
958
+ // If defined, add a DNS TXT record for each registered DID type.
959
+ if ((_f = didMetadata.types) === null || _f === void 0 ? void 0 : _f.length) {
960
+ // DID types can be specified as either a string or a number, so we need to normalize the
961
+ // values to integers.
962
+ const types = didMetadata.types;
963
+ const typeIntegers = types.map(type => typeof type === 'string' ? DidDhtRegisteredDidType[type] : type);
964
+ txtRecords.push({
965
+ type: 'TXT',
966
+ name: '_typ._did.',
967
+ ttl: DNS_RECORD_TTL,
968
+ data: `id=${typeIntegers.join(VALUE_SEPARATOR)}`
969
+ });
970
+ }
971
+ // Add a DNS TXT record for the root record.
972
+ txtRecords.push({
973
+ type: 'TXT',
974
+ name: '_did.' + DidDhtDocument.getUniqueDidSuffix(didDocument.id) + '.', // name of a Root Record MUST end in `<ID>.`
975
+ ttl: DNS_RECORD_TTL,
976
+ data: rootRecord.join(PROPERTY_SEPARATOR)
977
+ });
978
+ // Add an NS record for each authoritative gateway URI.
979
+ for (const gatewayUri of authoritativeGatewayUris || []) {
980
+ nsRecords.push({
981
+ type: 'NS',
982
+ name: '_did.' + DidDhtDocument.getUniqueDidSuffix(didDocument.id) + '.', // name of an NS record a authoritative gateway MUST end in `<ID>.`
983
+ ttl: DNS_RECORD_TTL,
984
+ data: gatewayUri + '.'
985
+ });
986
+ }
987
+ // Create a DNS response packet with the authoritative answer flag set.
988
+ const dnsPacket = {
989
+ id: 0,
990
+ type: 'response',
991
+ flags: AUTHORITATIVE_ANSWER,
992
+ answers: [...txtRecords, ...nsRecords]
993
+ };
994
+ return dnsPacket;
995
+ });
996
+ }
997
+ /**
998
+ * Gets the unique portion of the DID identifier after the last `:` character.
999
+ * e.g. `did:dht:example` -> `example`
1000
+ *
1001
+ * @param did - The DID to extract the unique suffix from.
1002
+ */
1003
+ static getUniqueDidSuffix(did) {
1004
+ return did.split(':')[2];
1005
+ }
1006
+ }
1007
+ /**
1008
+ * The `DidDhtUtils` class provides utility functions to support operations in the DID DHT method.
1009
+ * This includes functions for creating and parsing BEP44 messages, handling identity keys, and
1010
+ * converting between different formats and representations.
1011
+ */
1012
+ export class DidDhtUtils {
1013
+ /**
1014
+ * Creates a BEP44 put message, which is used to publish a DID document to the DHT network.
1015
+ *
1016
+ * @param params - The parameters to use when creating the BEP44 put message
1017
+ * @param params.dnsPacket - The DNS packet to encode in the BEP44 message.
1018
+ * @param params.publicKeyBytes - The public key bytes of the Identity Key.
1019
+ * @param params.signer - Signer that can sign and verify data using the Identity Key.
1020
+ * @returns A promise that resolves to a BEP44 put message.
1021
+ */
1022
+ static createBep44PutMessage(_a) {
1023
+ return __awaiter(this, arguments, void 0, function* ({ dnsPacket, publicKeyBytes, signer }) {
1024
+ // BEP44 requires that the sequence number be a monotoically increasing integer, so we use the
1025
+ // current time in seconds since Unix epoch as a simple solution. Higher precision is not
1026
+ // recommended since DID DHT documents are not expected to change frequently and there are
1027
+ // small differences in system clocks that can cause issues if multiple clients are publishing
1028
+ // updates to the same DID document.
1029
+ const sequenceNumber = Math.ceil(Date.now() / 1000);
1030
+ // Encode the DNS packet into a byte array containing a UDP payload.
1031
+ const encodedDnsPacket = dnsPacketEncode(dnsPacket);
1032
+ // Encode the sequence and DNS byte array to bencode format.
1033
+ const bencodedData = bencode.encode({ seq: sequenceNumber, v: encodedDnsPacket }).subarray(1, -1);
1034
+ if (bencodedData.length > 1000) {
1035
+ throw new DidError(DidErrorCode.InvalidDidDocumentLength, `DNS packet exceeds the 1000 byte maximum size: ${bencodedData.length} bytes`);
1036
+ }
1037
+ // Sign the BEP44 message.
1038
+ const signature = yield signer.sign({ data: bencodedData });
1039
+ return { k: publicKeyBytes, seq: sequenceNumber, sig: signature, v: encodedDnsPacket };
1040
+ });
1041
+ }
1042
+ /**
1043
+ * Converts a DID URI to a JSON Web Key (JWK) representing the Identity Key.
1044
+ *
1045
+ * @param params - The parameters to use for the conversion.
1046
+ * @param params.didUri - The DID URI containing the Identity Key.
1047
+ * @returns A promise that resolves to a JWK representing the Identity Key.
1048
+ */
1049
+ static identifierToIdentityKey(_a) {
1050
+ return __awaiter(this, arguments, void 0, function* ({ didUri }) {
1051
+ // Decode the method-specific identifier from z-base-32 to a byte array.
1052
+ let identityKeyBytes = DidDhtUtils.identifierToIdentityKeyBytes({ didUri });
1053
+ // Convert the byte array to a JWK.
1054
+ const identityKey = yield Ed25519.bytesToPublicKey({ publicKeyBytes: identityKeyBytes });
1055
+ return identityKey;
1056
+ });
1057
+ }
1058
+ /**
1059
+ * Converts a DID URI to the byte array representation of the Identity Key.
1060
+ *
1061
+ * @param params - The parameters to use for the conversion.
1062
+ * @param params.didUri - The DID URI containing the Identity Key.
1063
+ * @returns A byte array representation of the Identity Key.
1064
+ */
1065
+ static identifierToIdentityKeyBytes({ didUri }) {
1066
+ // Parse the DID URI.
1067
+ const parsedDid = Did.parse(didUri);
1068
+ // Verify that the DID URI is valid.
1069
+ if (!parsedDid) {
1070
+ throw new DidError(DidErrorCode.InvalidDid, `Invalid DID URI: ${didUri}`);
1071
+ }
1072
+ // Verify the DID method is supported.
1073
+ if (parsedDid.method !== DidDht.methodName) {
1074
+ throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported: ${parsedDid.method}`);
1075
+ }
1076
+ // Decode the method-specific identifier from z-base-32 to a byte array.
1077
+ let identityKeyBytes;
1078
+ try {
1079
+ identityKeyBytes = Convert.base32Z(parsedDid.id).toUint8Array();
1080
+ }
1081
+ catch (_a) {
1082
+ throw new DidError(DidErrorCode.InvalidPublicKey, `Failed to decode method-specific identifier`);
1083
+ }
1084
+ if (identityKeyBytes.length !== 32) {
1085
+ throw new DidError(DidErrorCode.InvalidPublicKeyLength, `Invalid public key length: ${identityKeyBytes.length}`);
1086
+ }
1087
+ return identityKeyBytes;
1088
+ }
1089
+ /**
1090
+ * Encodes a DID DHT Identity Key into a DID identifier.
1091
+ *
1092
+ * This method first z-base-32 encodes the Identity Key. The resulting string is prefixed with
1093
+ * `did:dht:` to form the DID identifier.
1094
+ *
1095
+ * @param params - The parameters to use for the conversion.
1096
+ * @param params.identityKey The Identity Key from which the DID identifier is computed.
1097
+ * @returns A promise that resolves to a string containing the DID identifier.
1098
+ */
1099
+ static identityKeyToIdentifier(_a) {
1100
+ return __awaiter(this, arguments, void 0, function* ({ identityKey }) {
1101
+ // Convert the key from JWK format to a byte array.
1102
+ const publicKeyBytes = yield Ed25519.publicKeyToBytes({ publicKey: identityKey });
1103
+ // Encode the byte array as a z-base-32 string.
1104
+ const identifier = Convert.uint8Array(publicKeyBytes).toBase32Z();
1105
+ return `did:${DidDht.methodName}:${identifier}`;
1106
+ });
1107
+ }
1108
+ /**
1109
+ * Returns the appropriate key converter for the specified cryptographic curve.
1110
+ *
1111
+ * @param curve - The cryptographic curve to use for the key conversion.
1112
+ * @returns An `AsymmetricKeyConverter` for the specified curve.
1113
+ */
1114
+ static keyConverter(curve) {
1115
+ const converters = {
1116
+ 'Ed25519': Ed25519,
1117
+ 'P-256': {
1118
+ // Wrap the key converter which produces uncompressed public key bytes to produce compressed key bytes as required by the DID DHT spec.
1119
+ // See https://did-dht.com/#representing-keys for more info.
1120
+ publicKeyToBytes: (_a) => __awaiter(this, [_a], void 0, function* ({ publicKey }) {
1121
+ const publicKeyBytes = yield Secp256r1.publicKeyToBytes({ publicKey });
1122
+ const compressedPublicKey = yield Secp256r1.compressPublicKey({ publicKeyBytes });
1123
+ return compressedPublicKey;
1124
+ }),
1125
+ bytesToPublicKey: Secp256r1.bytesToPublicKey,
1126
+ privateKeyToBytes: Secp256r1.privateKeyToBytes,
1127
+ bytesToPrivateKey: Secp256r1.bytesToPrivateKey,
1128
+ },
1129
+ 'secp256k1': {
1130
+ // Wrap the key converter which produces uncompressed public key bytes to produce compressed key bytes as required by the DID DHT spec.
1131
+ // See https://did-dht.com/#representing-keys for more info.
1132
+ publicKeyToBytes: (_a) => __awaiter(this, [_a], void 0, function* ({ publicKey }) {
1133
+ const publicKeyBytes = yield Secp256k1.publicKeyToBytes({ publicKey });
1134
+ const compressedPublicKey = yield Secp256k1.compressPublicKey({ publicKeyBytes });
1135
+ return compressedPublicKey;
1136
+ }),
1137
+ bytesToPublicKey: Secp256k1.bytesToPublicKey,
1138
+ privateKeyToBytes: Secp256k1.privateKeyToBytes,
1139
+ bytesToPrivateKey: Secp256k1.bytesToPrivateKey,
1140
+ },
1141
+ X25519: X25519,
1142
+ };
1143
+ const converter = converters[curve];
1144
+ if (!converter)
1145
+ throw new DidError(DidErrorCode.InvalidPublicKeyType, `Unsupported curve: ${curve}`);
1146
+ return converter;
1147
+ }
1148
+ /**
1149
+ * Parses and verifies a BEP44 Get message, converting it to a DNS packet.
1150
+ *
1151
+ * @param params - The parameters to use when verifying and parsing the BEP44 Get response message.
1152
+ * @param params.bep44Message - The BEP44 message to verify and parse.
1153
+ * @returns A promise that resolves to a DNS packet.
1154
+ */
1155
+ static parseBep44GetMessage(_a) {
1156
+ return __awaiter(this, arguments, void 0, function* ({ bep44Message }) {
1157
+ // Convert the public key byte array to JWK format.
1158
+ const publicKey = yield Ed25519.bytesToPublicKey({ publicKeyBytes: bep44Message.k });
1159
+ // Encode the sequence and DNS byte array to bencode format.
1160
+ const bencodedData = bencode.encode({ seq: bep44Message.seq, v: bep44Message.v }).subarray(1, -1);
1161
+ // Verify the signature of the BEP44 message.
1162
+ const isValid = yield Ed25519.verify({
1163
+ key: publicKey,
1164
+ signature: bep44Message.sig,
1165
+ data: bencodedData
1166
+ });
1167
+ if (!isValid) {
1168
+ throw new DidError(DidErrorCode.InvalidSignature, `Invalid signature for DHT BEP44 message`);
1169
+ }
1170
+ return dnsPacketDecode(bep44Message.v);
1171
+ });
1172
+ }
1173
+ /**
1174
+ * Decodes and parses the data value of a DNS TXT record into a key-value object.
1175
+ *
1176
+ * @param txtData - The data value of a DNS TXT record.
1177
+ * @returns An object containing the key/value pairs of the TXT record data.
1178
+ */
1179
+ static parseTxtDataToObject(txtData) {
1180
+ return this.parseTxtDataToString(txtData).split(PROPERTY_SEPARATOR).reduce((acc, pair) => {
1181
+ const [key, value] = pair.split('=');
1182
+ acc[key] = value;
1183
+ return acc;
1184
+ }, {});
1185
+ }
1186
+ /**
1187
+ * Decodes and parses the data value of a DNS TXT record into a string.
1188
+ *
1189
+ * @param txtData - The data value of a DNS TXT record.
1190
+ * @returns A string representation of the TXT record data.
1191
+ */
1192
+ static parseTxtDataToString(txtData) {
1193
+ if (typeof txtData === 'string') {
1194
+ return txtData;
1195
+ }
1196
+ else if (txtData instanceof Uint8Array) {
1197
+ return Convert.uint8Array(txtData).toString();
1198
+ }
1199
+ else if (Array.isArray(txtData)) {
1200
+ return txtData.map(item => this.parseTxtDataToString(item)).join('');
1201
+ }
1202
+ else {
1203
+ throw new DidError(DidErrorCode.InternalError, 'Pkarr returned DNS TXT record with invalid data type');
1204
+ }
1205
+ }
1206
+ /**
1207
+ * Validates the proof of previous DID given.
1208
+ *
1209
+ * @param params - The parameters to validate the previous DID proof.
1210
+ * @param params.newDid - The new DID that the previous DID is linking to.
1211
+ * @param params.previousDidProof - The proof of the previous DID, containing the previous DID and signature signed by the previous DID.
1212
+ */
1213
+ static validatePreviousDidProof(_a) {
1214
+ return __awaiter(this, arguments, void 0, function* ({ newDid, previousDidProof }) {
1215
+ const key = yield DidDhtUtils.identifierToIdentityKey({ didUri: previousDidProof.previousDid });
1216
+ const data = DidDhtUtils.identifierToIdentityKeyBytes({ didUri: newDid });
1217
+ const signature = Convert.base64Url(previousDidProof.signature).toUint8Array();
1218
+ const isValid = yield Ed25519.verify({ key, data, signature });
1219
+ if (!isValid) {
1220
+ throw new DidError(DidErrorCode.InvalidPreviousDidProof, 'The previous DID proof is invalid.');
1221
+ }
1222
+ });
1223
+ }
1224
+ /**
1225
+ * Splits a string into chunks of length 255 if the string exceeds length 255.
1226
+ * @param data - The string to split into chunks.
1227
+ * @returns The original string if its length is less than or equal to 255, otherwise an array of chunked strings.
1228
+ */
1229
+ static chunkDataIfNeeded(data) {
1230
+ if (data.length <= 255) {
1231
+ return data;
1232
+ }
1233
+ // Split the data into chunks of 255 characters.
1234
+ const chunks = [];
1235
+ for (let i = 0; i < data.length; i += 255) {
1236
+ chunks.push(data.slice(i, i + 255)); // end index is ignored if it exceeds the length of the string
1237
+ }
1238
+ return chunks;
1239
+ }
1240
+ }
1241
+ //# sourceMappingURL=did-dht.js.map