@enbox/dids 0.0.4 → 0.0.5

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 (48) hide show
  1. package/dist/browser.mjs +1 -1
  2. package/dist/browser.mjs.map +4 -4
  3. package/dist/esm/methods/did-dht-dns.js +455 -0
  4. package/dist/esm/methods/did-dht-dns.js.map +1 -0
  5. package/dist/esm/methods/did-dht-pkarr.js +168 -0
  6. package/dist/esm/methods/did-dht-pkarr.js.map +1 -0
  7. package/dist/esm/methods/did-dht-types.js +116 -0
  8. package/dist/esm/methods/did-dht-types.js.map +1 -0
  9. package/dist/esm/methods/did-dht-utils.js +143 -0
  10. package/dist/esm/methods/did-dht-utils.js.map +1 -0
  11. package/dist/esm/methods/did-dht.js +65 -842
  12. package/dist/esm/methods/did-dht.js.map +1 -1
  13. package/dist/esm/methods/did-ion-utils.js +161 -0
  14. package/dist/esm/methods/did-ion-utils.js.map +1 -0
  15. package/dist/esm/methods/did-ion.js +4 -151
  16. package/dist/esm/methods/did-ion.js.map +1 -1
  17. package/dist/esm/methods/did-key-utils.js +235 -0
  18. package/dist/esm/methods/did-key-utils.js.map +1 -0
  19. package/dist/esm/methods/did-key.js +6 -222
  20. package/dist/esm/methods/did-key.js.map +1 -1
  21. package/dist/types/methods/did-dht-dns.d.ts +114 -0
  22. package/dist/types/methods/did-dht-dns.d.ts.map +1 -0
  23. package/dist/types/methods/did-dht-pkarr.d.ts +56 -0
  24. package/dist/types/methods/did-dht-pkarr.d.ts.map +1 -0
  25. package/dist/types/methods/did-dht-types.d.ts +286 -0
  26. package/dist/types/methods/did-dht-types.d.ts.map +1 -0
  27. package/dist/types/methods/did-dht-utils.d.ts +54 -0
  28. package/dist/types/methods/did-dht-utils.d.ts.map +1 -0
  29. package/dist/types/methods/did-dht.d.ts +42 -457
  30. package/dist/types/methods/did-dht.d.ts.map +1 -1
  31. package/dist/types/methods/did-ion-utils.d.ts +86 -0
  32. package/dist/types/methods/did-ion-utils.d.ts.map +1 -0
  33. package/dist/types/methods/did-ion.d.ts +2 -82
  34. package/dist/types/methods/did-ion.d.ts.map +1 -1
  35. package/dist/types/methods/did-key-utils.d.ts +138 -0
  36. package/dist/types/methods/did-key-utils.d.ts.map +1 -0
  37. package/dist/types/methods/did-key.d.ts +3 -124
  38. package/dist/types/methods/did-key.d.ts.map +1 -1
  39. package/package.json +1 -1
  40. package/src/methods/did-dht-dns.ts +516 -0
  41. package/src/methods/did-dht-pkarr.ts +192 -0
  42. package/src/methods/did-dht-types.ts +316 -0
  43. package/src/methods/did-dht-utils.ts +157 -0
  44. package/src/methods/did-dht.ts +122 -1128
  45. package/src/methods/did-ion-utils.ts +186 -0
  46. package/src/methods/did-ion.ts +14 -190
  47. package/src/methods/did-key-utils.ts +258 -0
  48. package/src/methods/did-key.ts +14 -266
@@ -0,0 +1,192 @@
1
+ import type { Packet } from '@dnsquery/dns-packet';
2
+ import type { Signer } from '@enbox/crypto';
3
+
4
+ import type { Bep44Message } from './did-dht-types.js';
5
+
6
+ import bencode from 'bencode';
7
+ import { Convert } from '@enbox/common';
8
+ import { Ed25519 } from '@enbox/crypto';
9
+ import { DidError, DidErrorCode } from '../did-error.js';
10
+ import { decode as dnsPacketDecode, encode as dnsPacketEncode } from '@dnsquery/dns-packet';
11
+
12
+ /**
13
+ * Constructs a Pkarr URL from public key bytes and a gateway URI.
14
+ *
15
+ * @param publicKeyBytes - The public key bytes to z-base-32 encode.
16
+ * @param gatewayUri - The gateway URI to use as the base URL.
17
+ * @returns The full Pkarr URL.
18
+ */
19
+ function pkarrUrl(publicKeyBytes: Uint8Array, gatewayUri: string): string {
20
+ const identifier = Convert.uint8Array(publicKeyBytes).toBase32Z();
21
+ return new URL(identifier, gatewayUri).href;
22
+ }
23
+
24
+ /**
25
+ * Retrieves a signed BEP44 message from a DID DHT Gateway or Pkarr Relay server.
26
+ *
27
+ * @see {@link https://github.com/Nuhvi/pkarr/blob/main/design/relays.md | Pkarr Relay design}
28
+ *
29
+ * @param params - The parameters for the get operation.
30
+ * @param params.gatewayUri - The DID DHT Gateway or Pkarr Relay URI.
31
+ * @param params.publicKeyBytes - The public key bytes of the Identity Key, z-base-32 encoded.
32
+ * @returns A promise resolving to a BEP44 message containing the signed DNS packet.
33
+ */
34
+ export async function pkarrGet({ gatewayUri, publicKeyBytes }: {
35
+ publicKeyBytes: Uint8Array;
36
+ gatewayUri: string;
37
+ }): Promise<Bep44Message> {
38
+ // The identifier (key in the DHT) is the z-base-32 encoding of the Identity Key.
39
+ const identifier = Convert.uint8Array(publicKeyBytes).toBase32Z();
40
+
41
+ // Concatenate the gateway URI with the identifier to form the full URL.
42
+ const url = pkarrUrl(publicKeyBytes, gatewayUri);
43
+
44
+ // Transmit the Get request to the DID DHT Gateway or Pkarr Relay and get the response.
45
+ let response: Response;
46
+ try {
47
+ response = await fetch(url, { method: 'GET' });
48
+
49
+ if (!response.ok) {
50
+ throw new DidError(DidErrorCode.NotFound, `Pkarr record not found for: ${identifier}`);
51
+ }
52
+
53
+ } catch (error: any) {
54
+ if (error instanceof DidError) {throw error;}
55
+ throw new DidError(DidErrorCode.InternalError, `Failed to fetch Pkarr record: ${error.message}`);
56
+ }
57
+
58
+ // Read the Fetch Response stream into a byte array.
59
+ const messageBytes = await response.arrayBuffer();
60
+
61
+ if (!messageBytes) {
62
+ throw new DidError(DidErrorCode.NotFound, `Pkarr record not found for: ${identifier}`);
63
+ }
64
+
65
+ if (messageBytes.byteLength < 72) {
66
+ throw new DidError(DidErrorCode.InvalidDidDocumentLength, `Pkarr response must be at least 72 bytes but got: ${messageBytes.byteLength}`);
67
+ }
68
+
69
+ if (messageBytes.byteLength > 1072) {
70
+ throw new DidError(DidErrorCode.InvalidDidDocumentLength, `Pkarr response exceeds 1000 byte limit: ${messageBytes.byteLength}`);
71
+ }
72
+
73
+ // Decode the BEP44 message from the byte array.
74
+ const bep44Message: Bep44Message = {
75
+ k : publicKeyBytes,
76
+ seq : Number(new DataView(messageBytes).getBigUint64(64)),
77
+ sig : new Uint8Array(messageBytes, 0, 64),
78
+ v : new Uint8Array(messageBytes, 72)
79
+ };
80
+
81
+ return bep44Message;
82
+ }
83
+
84
+ /**
85
+ * Publishes a signed BEP44 message to a DID DHT Gateway or Pkarr Relay server.
86
+ *
87
+ * @see {@link https://github.com/Nuhvi/pkarr/blob/main/design/relays.md | Pkarr Relay design}
88
+ *
89
+ * @param params - The parameters to use when publishing a signed BEP44 message to a Pkarr relay server.
90
+ * @param params.gatewayUri - The DID DHT Gateway or Pkarr Relay URI.
91
+ * @param params.bep44Message - The BEP44 message to be published, containing the signed DNS packet.
92
+ * @returns A promise resolving to `true` if the message was successfully published, otherwise `false`.
93
+ */
94
+ export async function pkarrPut({ gatewayUri, bep44Message }: {
95
+ bep44Message: Bep44Message;
96
+ gatewayUri: string;
97
+ }): Promise<boolean> {
98
+ // The identifier (key in the DHT) is the z-base-32 encoding of the Identity Key.
99
+ const identifier = Convert.uint8Array(bep44Message.k).toBase32Z();
100
+
101
+ // Concatenate the gateway URI with the identifier to form the full URL.
102
+ const url = pkarrUrl(bep44Message.k, gatewayUri);
103
+
104
+ // Construct the body of the request according to the Pkarr relay specification.
105
+ const body = new Uint8Array(bep44Message.v.length + 72);
106
+ body.set(bep44Message.sig, 0);
107
+ new DataView(body.buffer).setBigUint64(bep44Message.sig.length, BigInt(bep44Message.seq));
108
+ body.set(bep44Message.v, bep44Message.sig.length + 8);
109
+
110
+ // Transmit the Put request to the Pkarr relay and get the response.
111
+ let response: Response;
112
+ try {
113
+ response = await fetch(url, {
114
+ method : 'PUT',
115
+ headers : { 'Content-Type': 'application/octet-stream' },
116
+ body
117
+ });
118
+
119
+ } catch (error: any) {
120
+ throw new DidError(DidErrorCode.InternalError, `Failed to put Pkarr record for identifier ${identifier}: ${error.message}`);
121
+ }
122
+
123
+ // Return `true` if the DHT request was successful, otherwise return `false`.
124
+ return response.ok;
125
+ }
126
+
127
+ /**
128
+ * Creates a BEP44 put message, which is used to publish a DID document to the DHT network.
129
+ *
130
+ * @param params - The parameters to use when creating the BEP44 put message.
131
+ * @param params.dnsPacket - The DNS packet to encode in the BEP44 message.
132
+ * @param params.publicKeyBytes - The public key bytes of the Identity Key.
133
+ * @param params.signer - Signer that can sign and verify data using the Identity Key.
134
+ * @returns A promise that resolves to a BEP44 put message.
135
+ */
136
+ export async function createBep44PutMessage({ dnsPacket, publicKeyBytes, signer }: {
137
+ dnsPacket: Packet;
138
+ publicKeyBytes: Uint8Array;
139
+ signer: Signer;
140
+ }): Promise<Bep44Message> {
141
+ // BEP44 requires that the sequence number be a monotoically increasing integer, so we use the
142
+ // current time in seconds since Unix epoch as a simple solution. Higher precision is not
143
+ // recommended since DID DHT documents are not expected to change frequently and there are
144
+ // small differences in system clocks that can cause issues if multiple clients are publishing
145
+ // updates to the same DID document.
146
+ const sequenceNumber = Math.ceil(Date.now() / 1000);
147
+
148
+ // Encode the DNS packet into a byte array containing a UDP payload.
149
+ const encodedDnsPacket = dnsPacketEncode(dnsPacket);
150
+
151
+ // Encode the sequence and DNS byte array to bencode format.
152
+ const bencodedData = bencode.encode({ seq: sequenceNumber, v: encodedDnsPacket }).subarray(1, -1);
153
+
154
+ if (bencodedData.length > 1000) {
155
+ throw new DidError(DidErrorCode.InvalidDidDocumentLength, `DNS packet exceeds the 1000 byte maximum size: ${bencodedData.length} bytes`);
156
+ }
157
+
158
+ // Sign the BEP44 message.
159
+ const signature = await signer.sign({ data: bencodedData });
160
+
161
+ return { k: publicKeyBytes, seq: sequenceNumber, sig: signature, v: encodedDnsPacket };
162
+ }
163
+
164
+ /**
165
+ * Parses and verifies a BEP44 Get message, converting it to a DNS packet.
166
+ *
167
+ * @param params - The parameters to use when verifying and parsing the BEP44 Get response message.
168
+ * @param params.bep44Message - The BEP44 message to verify and parse.
169
+ * @returns A promise that resolves to a DNS packet.
170
+ */
171
+ export async function parseBep44GetMessage({ bep44Message }: {
172
+ bep44Message: Bep44Message;
173
+ }): Promise<Packet> {
174
+ // Convert the public key byte array to JWK format.
175
+ const publicKey = await Ed25519.bytesToPublicKey({ publicKeyBytes: bep44Message.k });
176
+
177
+ // Encode the sequence and DNS byte array to bencode format.
178
+ const bencodedData = bencode.encode({ seq: bep44Message.seq, v: bep44Message.v }).subarray(1, -1);
179
+
180
+ // Verify the signature of the BEP44 message.
181
+ const isValid = await Ed25519.verify({
182
+ key : publicKey,
183
+ signature : bep44Message.sig,
184
+ data : bencodedData
185
+ });
186
+
187
+ if (!isValid) {
188
+ throw new DidError(DidErrorCode.InvalidSignature, `Invalid signature for DHT BEP44 message`);
189
+ }
190
+
191
+ return dnsPacketDecode(bep44Message.v);
192
+ }
@@ -0,0 +1,316 @@
1
+ import type { DidCreateOptions, DidCreateVerificationMethod } from './did-method.js';
2
+
3
+ import type { DidService } from '../types/did-core.js';
4
+
5
+ /**
6
+ * Represents a BEP44 message, which is used for storing and retrieving data in the Mainline DHT
7
+ * network.
8
+ *
9
+ * A BEP44 message is used primarily in the context of the DID DHT method for publishing and
10
+ * resolving DID documents in the DHT network. This type encapsulates the data structure required
11
+ * for such operations in accordance with BEP44.
12
+ *
13
+ * @see {@link https://www.bittorrent.org/beps/bep_0044.html | BEP44}
14
+ */
15
+ export interface Bep44Message {
16
+ /**
17
+ * The public key bytes of the Identity Key, which serves as the identifier in the DHT network for
18
+ * the corresponding BEP44 message.
19
+ */
20
+ k: Uint8Array;
21
+
22
+ /**
23
+ * The sequence number of the message, used to ensure the latest version of the data is retrieved
24
+ * and updated. It's a monotonically increasing number.
25
+ */
26
+ seq: number;
27
+
28
+ /**
29
+ * The signature of the message, ensuring the authenticity and integrity of the data. It's
30
+ * computed over the bencoded sequence number and value.
31
+ */
32
+ sig: Uint8Array;
33
+
34
+ /**
35
+ * The actual data being stored or retrieved from the DHT network, typically encoded in a format
36
+ * suitable for DNS packet representation of a DID Document.
37
+ */
38
+ v: Uint8Array;
39
+ }
40
+
41
+ /**
42
+ * Options for creating a Decentralized Identifier (DID) using the DID DHT method.
43
+ */
44
+ export interface DidDhtCreateOptions<TKms> extends DidCreateOptions<TKms> {
45
+ /**
46
+ * Optionally specify that the DID Subject is also identified by one or more other DIDs or URIs.
47
+ *
48
+ * A DID subject can have multiple identifiers for different purposes, or at different times.
49
+ * The assertion that two or more DIDs (or other types of URI) refer to the same DID subject can
50
+ * be made using the `alsoKnownAs` property.
51
+ *
52
+ * @see {@link https://www.w3.org/TR/did-core/#also-known-as | DID Core Specification, § Also Known As}
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * const did = await DidDht.create({
57
+ * options: {
58
+ * alsoKnownAs: 'did:example:123'
59
+ * };
60
+ * ```
61
+ */
62
+ alsoKnownAs?: string[];
63
+
64
+ /**
65
+ * Optionally specify which DID (or DIDs) is authorized to make changes to the DID document.
66
+ *
67
+ * A DID controller is an entity that is authorized to make changes to a DID document. Typically,
68
+ * only the DID Subject (i.e., the value of `id` property in the DID document) is authoritative.
69
+ * However, another DID (or DIDs) can be specified as the DID controller, and when doing so, any
70
+ * verification methods contained in the DID document for the other DID should be accepted as
71
+ * authoritative. In other words, proofs created by the controller DID should be considered
72
+ * equivalent to proofs created by the DID Subject.
73
+ *
74
+ * @see {@link https://www.w3.org/TR/did-core/#did-controller | DID Core Specification, § DID Controller}
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * const did = await DidDht.create({
79
+ * options: {
80
+ * controller: 'did:example:123'
81
+ * };
82
+ * ```
83
+ */
84
+ controllers?: string | string[];
85
+
86
+ /**
87
+ * Optional. The URI of a server involved in executing DID method operations. In the context of
88
+ * DID creation, the endpoint is expected to be a DID DHT Gateway or Pkarr relay. If not
89
+ * specified, a default gateway node is used.
90
+ */
91
+ gatewayUri?: string;
92
+
93
+ /**
94
+ * Optional. Determines whether the created DID should be published to the DHT network.
95
+ *
96
+ * If set to `true` or omitted, the DID is publicly discoverable. If `false`, the DID is not
97
+ * published and cannot be resolved by others. By default, newly created DIDs are published.
98
+ *
99
+ * @see {@link https://did-dht.com | DID DHT Method Specification}
100
+ *
101
+ * @example
102
+ * ```ts
103
+ * const did = await DidDht.create({
104
+ * options: {
105
+ * publish: false
106
+ * };
107
+ * ```
108
+ */
109
+ publish?: boolean;
110
+
111
+ /**
112
+ * Optional. An array of service endpoints associated with the DID.
113
+ *
114
+ * Services are used in DID documents to express ways of communicating with the DID subject or
115
+ * associated entities. A service can be any type of service the DID subject wants to advertise,
116
+ * including decentralized identity management services for further discovery, authentication,
117
+ * authorization, or interaction.
118
+ *
119
+ * @see {@link https://www.w3.org/TR/did-core/#services | DID Core Specification, § Services}
120
+ *
121
+ * @example
122
+ * ```ts
123
+ * const did = await DidDht.create({
124
+ * options: {
125
+ * services: [
126
+ * {
127
+ * id: 'did:dht:i9xkp8ddcbcg8jwq54ox699wuzxyifsqx4jru45zodqu453ksz6y#dwn',
128
+ * type: 'DecentralizedWebNode',
129
+ * serviceEndpoint: ['https://example.com/dwn1', 'https://example/dwn2']
130
+ * }
131
+ * ]
132
+ * };
133
+ * ```
134
+ */
135
+ services?: DidService[];
136
+
137
+ /**
138
+ * Optionally specify one or more registered DID DHT types to make the DID discovereable.
139
+ *
140
+ * Type indexing is an OPTIONAL feature that enables DIDs to become discoverable. DIDs that wish
141
+ * to be discoverable and resolveable by type can include one or more types when publishing their
142
+ * DID document to a DID DHT Gateway.
143
+ *
144
+ * The registered DID types are published in the {@link https://did-dht.com/registry/index.html#indexed-types | DID DHT Registry}.
145
+ */
146
+ types?: (DidDhtRegisteredDidType | keyof typeof DidDhtRegisteredDidType)[];
147
+
148
+ /**
149
+ * Optional. An array of verification methods to be included in the DID document.
150
+ *
151
+ * By default, a newly created DID DHT document will contain a single Ed25519 verification method,
152
+ * also known as the {@link https://did-dht.com/#term:identity-key | Identity Key}. Additional
153
+ * verification methods can be added to the DID document using the `verificationMethods` property.
154
+ *
155
+ * @see {@link https://www.w3.org/TR/did-core/#verification-methods | DID Core Specification, § Verification Methods}
156
+ *
157
+ * @example
158
+ * ```ts
159
+ * const did = await DidDht.create({
160
+ * options: {
161
+ * verificationMethods: [
162
+ * {
163
+ * algorithm: 'Ed25519',
164
+ * purposes: ['authentication', 'assertionMethod']
165
+ * },
166
+ * {
167
+ * algorithm: 'Ed25519',
168
+ * id: 'dwn-sig',
169
+ * purposes: ['authentication', 'assertionMethod']
170
+ * }
171
+ * ]
172
+ * };
173
+ * ```
174
+ */
175
+ verificationMethods?: DidCreateVerificationMethod<TKms>[];
176
+ }
177
+
178
+ /**
179
+ * Proof to used to construct the `_prv._did.` DNS record as described in https://did-dht.com/#rotation to link a DID to a previous DID.
180
+ */
181
+ export type PreviousDidProof = {
182
+ /** The previous DID. */
183
+ previousDid: string;
184
+
185
+ /** The signature signed using the private Identity Key of the previous DID in Base64URL format. */
186
+ signature: string;
187
+ };
188
+
189
+ /**
190
+ * Represents an optional extension to a DID Document's DNS packet representation exposed as a
191
+ * type index.
192
+ *
193
+ * Type indexing is an OPTIONAL feature that enables DIDs to become discoverable. DIDs that wish to
194
+ * be discoverable and resolveable by type can include one or more types when publishing their DID
195
+ * document to a DID DHT Gateway.
196
+ *
197
+ * The registered DID types are published in the {@link https://did-dht.com/registry/index.html#indexed-types | DID DHT Registry}.
198
+ */
199
+ export enum DidDhtRegisteredDidType {
200
+ /**
201
+ * Type 0 is reserved for DIDs that do not wish to associate themselves with a specific type but
202
+ * wish to make themselves discoverable.
203
+ */
204
+ Discoverable = 0,
205
+
206
+ /**
207
+ * Organization
208
+ * @see {@link https://schema.org/Organization | schema definition}
209
+ */
210
+ Organization = 1,
211
+
212
+ /**
213
+ * Government Organization
214
+ * @see {@link https://schema.org/GovernmentOrganization | schema definition}
215
+ */
216
+ Government = 2,
217
+
218
+ /**
219
+ * Corporation
220
+ * @see {@link https://schema.org/Corporation | schema definition}
221
+ */
222
+ Corporation = 3,
223
+
224
+ /**
225
+ * Corporation
226
+ * @see {@link https://schema.org/Corporation | schema definition}
227
+ */
228
+ LocalBusiness = 4,
229
+
230
+ /**
231
+ * Software Package
232
+ * @see {@link https://schema.org/SoftwareSourceCode | schema definition}
233
+ */
234
+ SoftwarePackage = 5,
235
+
236
+ /**
237
+ * Web App
238
+ * @see {@link https://schema.org/WebApplication | schema definition}
239
+ */
240
+ WebApp = 6,
241
+
242
+ /**
243
+ * Financial Institution
244
+ * @see {@link https://schema.org/FinancialService | schema definition}
245
+ */
246
+ FinancialInstitution = 7
247
+ }
248
+
249
+ /**
250
+ * Enumerates the types of keys that can be used in a DID DHT document.
251
+ *
252
+ * The DID DHT method supports various cryptographic key types. These key types are essential for
253
+ * the creation and management of DIDs and their associated cryptographic operations like signing
254
+ * and encryption. The registered key types are published in the DID DHT Registry and each is
255
+ * assigned a unique numerical value for use by client and gateway implementations.
256
+ *
257
+ * The registered key types are published in the {@link https://did-dht.com/registry/index.html#key-type-index | DID DHT Registry}.
258
+ */
259
+ export enum DidDhtRegisteredKeyType {
260
+ /**
261
+ * Ed25519: A public-key signature system using the EdDSA (Edwards-curve Digital Signature
262
+ * Algorithm) and Curve25519.
263
+ */
264
+ Ed25519 = 0,
265
+
266
+ /**
267
+ * secp256k1: A cryptographic curve used for digital signatures in a range of decentralized
268
+ * systems.
269
+ */
270
+ secp256k1 = 1,
271
+
272
+ /**
273
+ * secp256r1: Also known as P-256 or prime256v1, this curve is used for cryptographic operations
274
+ * and is widely supported in various cryptographic libraries and standards.
275
+ */
276
+ secp256r1 = 2,
277
+
278
+ /**
279
+ * X25519: A public key used for Diffie-Hellman key exchange using Curve25519.
280
+ */
281
+ X25519 = 3,
282
+ }
283
+
284
+ /**
285
+ * Maps {@link https://www.w3.org/TR/did-core/#verification-relationships | DID Core Verification Relationship}
286
+ * values to the corresponding record name in the DNS packet representation of a DHT DID document.
287
+ */
288
+ export enum DidDhtVerificationRelationship {
289
+ /**
290
+ * Specifies how the DID subject is expected to be authenticated.
291
+ */
292
+ authentication = 'auth',
293
+
294
+ /**
295
+ * Specifies how the DID subject is expected to express claims, such as for issuing Verifiable
296
+ * Credentials.
297
+ */
298
+ assertionMethod = 'asm',
299
+
300
+ /**
301
+ * Specifies a mechanism used by the DID subject to delegate a cryptographic capability to another
302
+ * party
303
+ */
304
+ capabilityDelegation = 'del',
305
+
306
+ /**
307
+ * Specifies a verification method used by the DID subject to invoke a cryptographic capability.
308
+ */
309
+ capabilityInvocation = 'inv',
310
+
311
+ /**
312
+ * Specifies how an entity can generate encryption material to communicate confidentially with the
313
+ * DID subject.
314
+ */
315
+ keyAgreement = 'agm'
316
+ }
@@ -0,0 +1,157 @@
1
+ import type { AsymmetricKeyConverter, Jwk } from '@enbox/crypto';
2
+
3
+ import { Convert } from '@enbox/common';
4
+ import { Ed25519, Secp256k1, Secp256r1, X25519 } from '@enbox/crypto';
5
+
6
+ import type { PreviousDidProof } from './did-dht-types.js';
7
+
8
+ import { Did } from '../did.js';
9
+ import { DidError, DidErrorCode } from '../did-error.js';
10
+
11
+ /**
12
+ * The DID DHT method name.
13
+ */
14
+ const DID_DHT_METHOD_NAME = 'dht';
15
+
16
+ /**
17
+ * Converts a DID URI to a JSON Web Key (JWK) representing the Identity Key.
18
+ *
19
+ * @param params - The parameters to use for the conversion.
20
+ * @param params.didUri - The DID URI containing the Identity Key.
21
+ * @returns A promise that resolves to a JWK representing the Identity Key.
22
+ */
23
+ export async function identifierToIdentityKey({ didUri }: {
24
+ didUri: string;
25
+ }): Promise<Jwk> {
26
+ // Decode the method-specific identifier from z-base-32 to a byte array.
27
+ const identityKeyBytes = identifierToIdentityKeyBytes({ didUri });
28
+
29
+ // Convert the byte array to a JWK.
30
+ const identityKey = await Ed25519.bytesToPublicKey({ publicKeyBytes: identityKeyBytes });
31
+
32
+ return identityKey;
33
+ }
34
+
35
+ /**
36
+ * Converts a DID URI to the byte array representation of the Identity Key.
37
+ *
38
+ * @param params - The parameters to use for the conversion.
39
+ * @param params.didUri - The DID URI containing the Identity Key.
40
+ * @returns A byte array representation of the Identity Key.
41
+ */
42
+ export function identifierToIdentityKeyBytes({ didUri }: {
43
+ didUri: string;
44
+ }): Uint8Array {
45
+ // Parse the DID URI.
46
+ const parsedDid = Did.parse(didUri);
47
+
48
+ // Verify that the DID URI is valid.
49
+ if (!parsedDid) {
50
+ throw new DidError(DidErrorCode.InvalidDid, `Invalid DID URI: ${didUri}`);
51
+ }
52
+
53
+ // Verify the DID method is supported.
54
+ if (parsedDid.method !== DID_DHT_METHOD_NAME) {
55
+ throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported: ${parsedDid.method}`);
56
+ }
57
+
58
+ // Decode the method-specific identifier from z-base-32 to a byte array.
59
+ let identityKeyBytes: Uint8Array;
60
+ try {
61
+ identityKeyBytes = Convert.base32Z(parsedDid.id).toUint8Array();
62
+ } catch {
63
+ throw new DidError(DidErrorCode.InvalidPublicKey, `Failed to decode method-specific identifier`);
64
+ }
65
+
66
+ if (identityKeyBytes.length !== 32) {
67
+ throw new DidError(DidErrorCode.InvalidPublicKeyLength, `Invalid public key length: ${identityKeyBytes.length}`);
68
+ }
69
+
70
+ return identityKeyBytes;
71
+ }
72
+
73
+ /**
74
+ * Encodes a DID DHT Identity Key into a DID identifier.
75
+ *
76
+ * This method first z-base-32 encodes the Identity Key. The resulting string is prefixed with
77
+ * `did:dht:` to form the DID identifier.
78
+ *
79
+ * @param params - The parameters to use for the conversion.
80
+ * @param params.identityKey The Identity Key from which the DID identifier is computed.
81
+ * @returns A promise that resolves to a string containing the DID identifier.
82
+ */
83
+ export async function identityKeyToIdentifier({ identityKey }: {
84
+ identityKey: Jwk;
85
+ }): Promise<string> {
86
+ // Convert the key from JWK format to a byte array.
87
+ const publicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey: identityKey });
88
+
89
+ // Encode the byte array as a z-base-32 string.
90
+ const identifier = Convert.uint8Array(publicKeyBytes).toBase32Z();
91
+
92
+ return `did:${DID_DHT_METHOD_NAME}:${identifier}`;
93
+ }
94
+
95
+ /**
96
+ * Returns the appropriate key converter for the specified cryptographic curve.
97
+ *
98
+ * @param curve - The cryptographic curve to use for the key conversion.
99
+ * @returns An `AsymmetricKeyConverter` for the specified curve.
100
+ */
101
+ export function keyConverter(curve: string): AsymmetricKeyConverter {
102
+ const converters: Record<string, AsymmetricKeyConverter> = {
103
+ 'Ed25519' : Ed25519,
104
+ 'P-256' : {
105
+ // Wrap the key converter which produces uncompressed public key bytes to produce compressed key bytes as required by the DID DHT spec.
106
+ // See https://did-dht.com/#representing-keys for more info.
107
+ publicKeyToBytes: async ({ publicKey }: { publicKey: Jwk }): Promise<Uint8Array> => {
108
+ const publicKeyBytes = await Secp256r1.publicKeyToBytes({ publicKey });
109
+ const compressedPublicKey = await Secp256r1.compressPublicKey({ publicKeyBytes });
110
+ return compressedPublicKey;
111
+ },
112
+ bytesToPublicKey : Secp256r1.bytesToPublicKey,
113
+ privateKeyToBytes : Secp256r1.privateKeyToBytes,
114
+ bytesToPrivateKey : Secp256r1.bytesToPrivateKey,
115
+ },
116
+ 'secp256k1': {
117
+ // Wrap the key converter which produces uncompressed public key bytes to produce compressed key bytes as required by the DID DHT spec.
118
+ // See https://did-dht.com/#representing-keys for more info.
119
+ publicKeyToBytes: async ({ publicKey }: { publicKey: Jwk }): Promise<Uint8Array> => {
120
+ const publicKeyBytes = await Secp256k1.publicKeyToBytes({ publicKey });
121
+ const compressedPublicKey = await Secp256k1.compressPublicKey({ publicKeyBytes });
122
+ return compressedPublicKey;
123
+ },
124
+ bytesToPublicKey : Secp256k1.bytesToPublicKey,
125
+ privateKeyToBytes : Secp256k1.privateKeyToBytes,
126
+ bytesToPrivateKey : Secp256k1.bytesToPrivateKey,
127
+ },
128
+ X25519: X25519,
129
+ };
130
+
131
+ const converter = converters[curve];
132
+
133
+ if (!converter) {throw new DidError(DidErrorCode.InvalidPublicKeyType, `Unsupported curve: ${curve}`);}
134
+
135
+ return converter;
136
+ }
137
+
138
+ /**
139
+ * Validates the proof of previous DID given.
140
+ *
141
+ * @param params - The parameters to validate the previous DID proof.
142
+ * @param params.newDid - The new DID that the previous DID is linking to.
143
+ * @param params.previousDidProof - The proof of the previous DID, containing the previous DID and signature signed by the previous DID.
144
+ */
145
+ export async function validatePreviousDidProof({ newDid, previousDidProof }: {
146
+ newDid: string;
147
+ previousDidProof: PreviousDidProof;
148
+ }): Promise<void> {
149
+ const key = await identifierToIdentityKey({ didUri: previousDidProof.previousDid });
150
+ const data = identifierToIdentityKeyBytes({ didUri: newDid });
151
+ const signature = Convert.base64Url(previousDidProof.signature).toUint8Array();
152
+ const isValid = await Ed25519.verify({ key, data, signature });
153
+
154
+ if (!isValid) {
155
+ throw new DidError(DidErrorCode.InvalidPreviousDidProof, 'The previous DID proof is invalid.');
156
+ }
157
+ }