@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.
- package/LICENSE +201 -0
- package/README.md +1 -0
- package/dist/browser.js +77 -0
- package/dist/browser.js.map +7 -0
- package/dist/browser.mjs +77 -0
- package/dist/browser.mjs.map +7 -0
- package/dist/cjs/index.js +6303 -0
- package/dist/cjs/index.js.map +7 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/utils.js +245 -0
- package/dist/cjs/utils.js.map +7 -0
- package/dist/esm/bearer-did.js +201 -0
- package/dist/esm/bearer-did.js.map +1 -0
- package/dist/esm/did-error.js +62 -0
- package/dist/esm/did-error.js.map +1 -0
- package/dist/esm/did.js +114 -0
- package/dist/esm/did.js.map +1 -0
- package/dist/esm/index.js +16 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/methods/did-dht.js +1241 -0
- package/dist/esm/methods/did-dht.js.map +1 -0
- package/dist/esm/methods/did-ion.js +570 -0
- package/dist/esm/methods/did-ion.js.map +1 -0
- package/dist/esm/methods/did-jwk.js +298 -0
- package/dist/esm/methods/did-jwk.js.map +1 -0
- package/dist/esm/methods/did-key.js +983 -0
- package/dist/esm/methods/did-key.js.map +1 -0
- package/dist/esm/methods/did-method.js +53 -0
- package/dist/esm/methods/did-method.js.map +1 -0
- package/dist/esm/methods/did-web.js +83 -0
- package/dist/esm/methods/did-web.js.map +1 -0
- package/dist/esm/resolver/resolver-cache-level.js +101 -0
- package/dist/esm/resolver/resolver-cache-level.js.map +1 -0
- package/dist/esm/resolver/resolver-cache-noop.js +24 -0
- package/dist/esm/resolver/resolver-cache-noop.js.map +1 -0
- package/dist/esm/resolver/universal-resolver.js +187 -0
- package/dist/esm/resolver/universal-resolver.js.map +1 -0
- package/dist/esm/types/did-core.js +51 -0
- package/dist/esm/types/did-core.js.map +1 -0
- package/dist/esm/types/did-resolution.js +12 -0
- package/dist/esm/types/did-resolution.js.map +1 -0
- package/dist/esm/types/multibase.js +2 -0
- package/dist/esm/types/multibase.js.map +1 -0
- package/dist/esm/types/portable-did.js +2 -0
- package/dist/esm/types/portable-did.js.map +1 -0
- package/dist/esm/utils.js +458 -0
- package/dist/esm/utils.js.map +1 -0
- package/dist/types/bearer-did.d.ts +143 -0
- package/dist/types/bearer-did.d.ts.map +1 -0
- package/dist/types/did-error.d.ts +50 -0
- package/dist/types/did-error.d.ts.map +1 -0
- package/dist/types/did.d.ts +125 -0
- package/dist/types/did.d.ts.map +1 -0
- package/dist/types/index.d.ts +18 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/methods/did-dht.d.ts +682 -0
- package/dist/types/methods/did-dht.d.ts.map +1 -0
- package/dist/types/methods/did-ion.d.ts +492 -0
- package/dist/types/methods/did-ion.d.ts.map +1 -0
- package/dist/types/methods/did-jwk.d.ts +236 -0
- package/dist/types/methods/did-jwk.d.ts.map +1 -0
- package/dist/types/methods/did-key.d.ts +499 -0
- package/dist/types/methods/did-key.d.ts.map +1 -0
- package/dist/types/methods/did-method.d.ts +238 -0
- package/dist/types/methods/did-method.d.ts.map +1 -0
- package/dist/types/methods/did-web.d.ts +37 -0
- package/dist/types/methods/did-web.d.ts.map +1 -0
- package/dist/types/resolver/resolver-cache-level.d.ts +86 -0
- package/dist/types/resolver/resolver-cache-level.d.ts.map +1 -0
- package/dist/types/resolver/resolver-cache-noop.d.ts +9 -0
- package/dist/types/resolver/resolver-cache-noop.d.ts.map +1 -0
- package/dist/types/resolver/universal-resolver.d.ts +109 -0
- package/dist/types/resolver/universal-resolver.d.ts.map +1 -0
- package/dist/types/types/did-core.d.ts +523 -0
- package/dist/types/types/did-core.d.ts.map +1 -0
- package/dist/types/types/did-resolution.d.ts +85 -0
- package/dist/types/types/did-resolution.d.ts.map +1 -0
- package/dist/types/types/multibase.d.ts +28 -0
- package/dist/types/types/multibase.d.ts.map +1 -0
- package/dist/types/types/portable-did.d.ts +59 -0
- package/dist/types/types/portable-did.d.ts.map +1 -0
- package/dist/types/utils.d.ts +378 -0
- package/dist/types/utils.d.ts.map +1 -0
- package/dist/utils.js +28 -0
- package/dist/utils.js.map +7 -0
- package/package.json +116 -0
- package/src/bearer-did.ts +287 -0
- package/src/did-error.ts +75 -0
- package/src/did.ts +186 -0
- package/src/index.ts +21 -0
- package/src/methods/did-dht.ts +1637 -0
- package/src/methods/did-ion.ts +887 -0
- package/src/methods/did-jwk.ts +410 -0
- package/src/methods/did-key.ts +1248 -0
- package/src/methods/did-method.ts +276 -0
- package/src/methods/did-web.ts +96 -0
- package/src/resolver/resolver-cache-level.ts +163 -0
- package/src/resolver/resolver-cache-noop.ts +26 -0
- package/src/resolver/universal-resolver.ts +238 -0
- package/src/types/did-core.ts +580 -0
- package/src/types/did-resolution.ts +93 -0
- package/src/types/multibase.ts +29 -0
- package/src/types/portable-did.ts +64 -0
- package/src/utils.ts +532 -0
|
@@ -0,0 +1,983 @@
|
|
|
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
|
+
import { Multicodec, universalTypeOf } from '@enbox/common';
|
|
11
|
+
import { X25519, Ed25519, Secp256k1, Secp256r1, LocalKeyManager, } from '@enbox/crypto';
|
|
12
|
+
import { Did } from '../did.js';
|
|
13
|
+
import { DidMethod } from './did-method.js';
|
|
14
|
+
import { BearerDid } from '../bearer-did.js';
|
|
15
|
+
import { DidError, DidErrorCode } from '../did-error.js';
|
|
16
|
+
import { EMPTY_DID_RESOLUTION_RESULT } from '../types/did-resolution.js';
|
|
17
|
+
import { getVerificationMethodTypes, keyBytesToMultibaseId, multibaseIdToKeyBytes } from '../utils.js';
|
|
18
|
+
/**
|
|
19
|
+
* Enumerates the types of keys that can be used in a DID Key document.
|
|
20
|
+
*
|
|
21
|
+
* The DID Key method supports various cryptographic key types. These key types are essential for
|
|
22
|
+
* the creation and management of DIDs and their associated cryptographic operations like signing
|
|
23
|
+
* and encryption.
|
|
24
|
+
*/
|
|
25
|
+
export var DidKeyRegisteredKeyType;
|
|
26
|
+
(function (DidKeyRegisteredKeyType) {
|
|
27
|
+
/**
|
|
28
|
+
* Ed25519: A public-key signature system using the EdDSA (Edwards-curve Digital Signature
|
|
29
|
+
* Algorithm) and Curve25519.
|
|
30
|
+
*/
|
|
31
|
+
DidKeyRegisteredKeyType["Ed25519"] = "Ed25519";
|
|
32
|
+
/**
|
|
33
|
+
* secp256k1: A cryptographic curve used for digital signatures in a range of decentralized
|
|
34
|
+
* systems.
|
|
35
|
+
*/
|
|
36
|
+
DidKeyRegisteredKeyType["secp256k1"] = "secp256k1";
|
|
37
|
+
/**
|
|
38
|
+
* secp256r1: Also known as P-256 or prime256v1, this curve is used for cryptographic operations
|
|
39
|
+
* and is widely supported in various cryptographic libraries and standards.
|
|
40
|
+
*/
|
|
41
|
+
DidKeyRegisteredKeyType["secp256r1"] = "secp256r1";
|
|
42
|
+
/**
|
|
43
|
+
* X25519: A Diffie-Hellman key exchange algorithm using Curve25519.
|
|
44
|
+
*/
|
|
45
|
+
DidKeyRegisteredKeyType["X25519"] = "X25519";
|
|
46
|
+
})(DidKeyRegisteredKeyType || (DidKeyRegisteredKeyType = {}));
|
|
47
|
+
/**
|
|
48
|
+
* Enumerates the verification method types supported by the DID Key method.
|
|
49
|
+
*
|
|
50
|
+
* This enum defines the URIs associated with common verification methods used in DID Documents.
|
|
51
|
+
* These URIs represent cryptographic suites or key types standardized for use across decentralized
|
|
52
|
+
* identifiers (DIDs).
|
|
53
|
+
*/
|
|
54
|
+
export const DidKeyVerificationMethodType = {
|
|
55
|
+
/** Represents an Ed25519 public key used for digital signatures. */
|
|
56
|
+
Ed25519VerificationKey2020: 'https://w3id.org/security/suites/ed25519-2020/v1',
|
|
57
|
+
/** Represents a JSON Web Key (JWK) used for digital signatures and key agreement protocols. */
|
|
58
|
+
JsonWebKey2020: 'https://w3id.org/security/suites/jws-2020/v1',
|
|
59
|
+
/** Represents an X25519 public key used for key agreement protocols. */
|
|
60
|
+
X25519KeyAgreementKey2020: 'https://w3id.org/security/suites/x25519-2020/v1',
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Private helper that maps algorithm identifiers to their corresponding DID Key
|
|
64
|
+
* {@link DidKeyRegisteredKeyType | registered key type}.
|
|
65
|
+
*/
|
|
66
|
+
const AlgorithmToKeyTypeMap = {
|
|
67
|
+
Ed25519: DidKeyRegisteredKeyType.Ed25519,
|
|
68
|
+
ES256K: DidKeyRegisteredKeyType.secp256k1,
|
|
69
|
+
ES256: DidKeyRegisteredKeyType.secp256r1,
|
|
70
|
+
'P-256': DidKeyRegisteredKeyType.secp256r1,
|
|
71
|
+
secp256k1: DidKeyRegisteredKeyType.secp256k1,
|
|
72
|
+
secp256r1: DidKeyRegisteredKeyType.secp256r1,
|
|
73
|
+
X25519: DidKeyRegisteredKeyType.X25519
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* The `DidKey` class provides an implementation of the 'did:key' DID method.
|
|
77
|
+
*
|
|
78
|
+
* Features:
|
|
79
|
+
* - DID Creation: Create new `did:key` DIDs.
|
|
80
|
+
* - DID Key Management: Instantiate a DID object from an existing verification method key set or
|
|
81
|
+
* or a key in a Key Management System (KMS). If supported by the KMS, a DID's
|
|
82
|
+
* key can be exported to a portable DID format.
|
|
83
|
+
* - DID Resolution: Resolve a `did:key` to its corresponding DID Document.
|
|
84
|
+
* - Signature Operations: Sign and verify messages using keys associated with a DID.
|
|
85
|
+
*
|
|
86
|
+
* @remarks
|
|
87
|
+
* The `did:key` DID method uses a single public key to generate a DID and does not rely
|
|
88
|
+
* on any external system such as a blockchain or centralized database. This characteristic makes
|
|
89
|
+
* it suitable for use cases where a assertions about a DID Subject can be self-verifiable by
|
|
90
|
+
* third parties.
|
|
91
|
+
*
|
|
92
|
+
* The method-specific identifier is formed by
|
|
93
|
+
* {@link https://datatracker.ietf.org/doc/html/draft-multiformats-multibase#name-base-58-bitcoin-encoding | Multibase base58-btc}
|
|
94
|
+
* encoding the concatenation of the
|
|
95
|
+
* {@link https://github.com/multiformats/multicodec/blob/master/README.md | Multicodec} identifier
|
|
96
|
+
* for the public key type and the raw public key bytes. To form the DID URI, the method-specific
|
|
97
|
+
* identifier is prefixed with the string 'did:key:'.
|
|
98
|
+
*
|
|
99
|
+
* This method can optionally derive an encryption key from the public key used to create the DID
|
|
100
|
+
* if and only if the public key algorithm is `Ed25519`. This feature enables the same DID to be
|
|
101
|
+
* used for encrypted communication, in addition to signature verification. To enable this
|
|
102
|
+
* feature when calling {@link DidKey.create | `DidKey.create()`}, first specify an `algorithm` of
|
|
103
|
+
* `Ed25519` or provide a `keySet` referencing an `Ed25519` key and then set the
|
|
104
|
+
* `enableEncryptionKeyDerivation` option to `true`.
|
|
105
|
+
*
|
|
106
|
+
* Note:
|
|
107
|
+
* - The authors of the DID Key specification have indicated that use of this method for long-lived
|
|
108
|
+
* use cases is only recommended when accompanied with high confidence that private keys are
|
|
109
|
+
* securely protected by software or hardware isolation.
|
|
110
|
+
*
|
|
111
|
+
* @see {@link https://w3c-ccg.github.io/did-method-key/ | DID Key Specification}
|
|
112
|
+
*
|
|
113
|
+
* @example
|
|
114
|
+
* ```ts
|
|
115
|
+
* // DID Creation
|
|
116
|
+
* const did = await DidKey.create();
|
|
117
|
+
*
|
|
118
|
+
* // DID Creation with a KMS
|
|
119
|
+
* const keyManager = new LocalKeyManager();
|
|
120
|
+
* const did = await DidKey.create({ keyManager });
|
|
121
|
+
*
|
|
122
|
+
* // DID Resolution
|
|
123
|
+
* const resolutionResult = await DidKey.resolve({ did: did.uri });
|
|
124
|
+
*
|
|
125
|
+
* // Signature Operations
|
|
126
|
+
* const signer = await did.getSigner();
|
|
127
|
+
* const signature = await signer.sign({ data: new TextEncoder().encode('Message') });
|
|
128
|
+
* const isValid = await signer.verify({ data: new TextEncoder().encode('Message'), signature });
|
|
129
|
+
*
|
|
130
|
+
* // Key Management
|
|
131
|
+
*
|
|
132
|
+
* // Instantiate a DID object from an existing key in a KMS
|
|
133
|
+
* const did = await DidKey.fromKeyManager({
|
|
134
|
+
* didUri: 'did:key:z6MkpUzNmYVTGpqhStxK8yRKXWCRNm1bGYz8geAg2zmjYHKX',
|
|
135
|
+
* keyManager
|
|
136
|
+
* });
|
|
137
|
+
*
|
|
138
|
+
* // Instantiate a DID object from an existing verification method key
|
|
139
|
+
* const did = await DidKey.fromKeys({
|
|
140
|
+
* verificationMethods: [{
|
|
141
|
+
* publicKeyJwk: {
|
|
142
|
+
* kty: 'OKP',
|
|
143
|
+
* crv: 'Ed25519',
|
|
144
|
+
* x: 'cHs7YMLQ3gCWjkacMURBsnEJBcEsvlsE5DfnsfTNDP4'
|
|
145
|
+
* },
|
|
146
|
+
* privateKeyJwk: {
|
|
147
|
+
* kty: 'OKP',
|
|
148
|
+
* crv: 'Ed25519',
|
|
149
|
+
* x: 'cHs7YMLQ3gCWjkacMURBsnEJBcEsvlsE5DfnsfTNDP4',
|
|
150
|
+
* d: 'bdcGE4KzEaekOwoa-ee3gAm1a991WvNj_Eq3WKyqTnE'
|
|
151
|
+
* }
|
|
152
|
+
* }]
|
|
153
|
+
* });
|
|
154
|
+
*
|
|
155
|
+
* // Convert a DID object to a portable format
|
|
156
|
+
* const portableDid = await DidKey.toKeys({ did });
|
|
157
|
+
*
|
|
158
|
+
* // Reconstruct a DID object from a portable format
|
|
159
|
+
* const did = await DidKey.fromKeys(portableDid);
|
|
160
|
+
* ```
|
|
161
|
+
*/
|
|
162
|
+
export class DidKey extends DidMethod {
|
|
163
|
+
/**
|
|
164
|
+
* Creates a new DID using the `did:key` method formed from a newly generated key.
|
|
165
|
+
*
|
|
166
|
+
* @remarks
|
|
167
|
+
* The DID URI is formed by
|
|
168
|
+
* {@link https://datatracker.ietf.org/doc/html/draft-multiformats-multibase#name-base-58-bitcoin-encoding | Multibase base58-btc}
|
|
169
|
+
* encoding the
|
|
170
|
+
* {@link https://github.com/multiformats/multicodec/blob/master/README.md | Multicodec}-encoded
|
|
171
|
+
* public key and prefixing with `did:key:`.
|
|
172
|
+
*
|
|
173
|
+
* This method can optionally derive an encryption key from the public key used to create the DID
|
|
174
|
+
* if and only if the public key algorithm is `Ed25519`. This feature enables the same DID to be
|
|
175
|
+
* used for encrypted communication, in addition to signature verification. To enable this
|
|
176
|
+
* feature, specify an `algorithm` of `Ed25519` as either a top-level option or in a
|
|
177
|
+
* `verificationMethod` and set the `enableEncryptionKeyDerivation` option to `true`.
|
|
178
|
+
*
|
|
179
|
+
* Notes:
|
|
180
|
+
* - If no `options` are given, by default a new Ed25519 key will be generated.
|
|
181
|
+
* - The `algorithm` and `verificationMethods` options are mutually exclusive. If both are given,
|
|
182
|
+
* an error will be thrown.
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* ```ts
|
|
186
|
+
* // DID Creation
|
|
187
|
+
* const did = await DidKey.create();
|
|
188
|
+
*
|
|
189
|
+
* // DID Creation with a KMS
|
|
190
|
+
* const keyManager = new LocalKeyManager();
|
|
191
|
+
* const did = await DidKey.create({ keyManager });
|
|
192
|
+
* ```
|
|
193
|
+
*
|
|
194
|
+
* @param params - The parameters for the create operation.
|
|
195
|
+
* @param params.keyManager - Key Management System (KMS) used to generate keys and sign data.
|
|
196
|
+
* @param params.options - Optional parameters that can be specified when creating a new DID.
|
|
197
|
+
* @returns A Promise resolving to a {@link BearerDid} object representing the new DID.
|
|
198
|
+
*/
|
|
199
|
+
static create() {
|
|
200
|
+
return __awaiter(this, arguments, void 0, function* ({ keyManager = new LocalKeyManager(), options = {} } = {}) {
|
|
201
|
+
// Before processing the create operation, validate DID-method-specific requirements to prevent
|
|
202
|
+
// keys from being generated unnecessarily.
|
|
203
|
+
var _a, _b, _c, _d;
|
|
204
|
+
// Check 1: Validate that `algorithm` or `verificationMethods` options are not both given.
|
|
205
|
+
if (options.algorithm && options.verificationMethods) {
|
|
206
|
+
throw new Error(`The 'algorithm' and 'verificationMethods' options are mutually exclusive`);
|
|
207
|
+
}
|
|
208
|
+
// Check 2: If `verificationMethods` is given, it must contain exactly one entry since DID Key
|
|
209
|
+
// only supports a single verification method.
|
|
210
|
+
if (options.verificationMethods && options.verificationMethods.length !== 1) {
|
|
211
|
+
throw new Error(`The 'verificationMethods' option must contain exactly one entry`);
|
|
212
|
+
}
|
|
213
|
+
// Default to Ed25519 key generation if an algorithm is not given.
|
|
214
|
+
const algorithm = (_d = (_a = options.algorithm) !== null && _a !== void 0 ? _a : (_c = (_b = options.verificationMethods) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.algorithm) !== null && _d !== void 0 ? _d : 'Ed25519';
|
|
215
|
+
// Generate a new key using the specified `algorithm`.
|
|
216
|
+
const keyUri = yield keyManager.generateKey({ algorithm });
|
|
217
|
+
const publicKey = yield keyManager.getPublicKey({ keyUri });
|
|
218
|
+
// Compute the DID identifier from the public key by converting the JWK to a multibase-encoded
|
|
219
|
+
// multicodec value.
|
|
220
|
+
const identifier = yield DidKeyUtils.publicKeyToMultibaseId({ publicKey });
|
|
221
|
+
// Attach the prefix `did:key` to form the complete DID URI.
|
|
222
|
+
const didUri = `did:${DidKey.methodName}:${identifier}`;
|
|
223
|
+
// Expand the DID URI string to a DID document.
|
|
224
|
+
const didResolutionResult = yield DidKey.resolve(didUri, options);
|
|
225
|
+
const document = didResolutionResult.didDocument;
|
|
226
|
+
// Create the BearerDid object from the generated key material.
|
|
227
|
+
const did = new BearerDid({
|
|
228
|
+
uri: didUri,
|
|
229
|
+
document,
|
|
230
|
+
metadata: {},
|
|
231
|
+
keyManager
|
|
232
|
+
});
|
|
233
|
+
return did;
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Given the W3C DID Document of a `did:key` DID, return the verification method that will be used
|
|
238
|
+
* for signing messages and credentials. With DID Key, the first verification method in the
|
|
239
|
+
* authentication property in the DID Document is used.
|
|
240
|
+
*
|
|
241
|
+
* Note that for DID Key, only one verification method intended for signing can exist so
|
|
242
|
+
* specifying `methodId` could be considered redundant or unnecessary. The option is provided for
|
|
243
|
+
* consistency with other DID method implementations.
|
|
244
|
+
*
|
|
245
|
+
* @param params - The parameters for the `getSigningMethod` operation.
|
|
246
|
+
* @param params.didDocument - DID Document to get the verification method from.
|
|
247
|
+
* @param params.methodId - ID of the verification method to use for signing.
|
|
248
|
+
* @returns Verification method to use for signing.
|
|
249
|
+
*/
|
|
250
|
+
static getSigningMethod(_a) {
|
|
251
|
+
return __awaiter(this, arguments, void 0, function* ({ didDocument }) {
|
|
252
|
+
var _b;
|
|
253
|
+
// Verify the DID method is supported.
|
|
254
|
+
const parsedDid = Did.parse(didDocument.id);
|
|
255
|
+
if (parsedDid && parsedDid.method !== this.methodName) {
|
|
256
|
+
throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported: ${parsedDid.method}`);
|
|
257
|
+
}
|
|
258
|
+
// Attempt to ge the first verification method intended for signing claims.
|
|
259
|
+
const [methodId] = didDocument.assertionMethod || [];
|
|
260
|
+
const verificationMethod = (_b = didDocument.verificationMethod) === null || _b === void 0 ? void 0 : _b.find(vm => vm.id === methodId);
|
|
261
|
+
if (!(verificationMethod && verificationMethod.publicKeyJwk)) {
|
|
262
|
+
throw new DidError(DidErrorCode.InternalError, 'A verification method intended for signing could not be determined from the DID Document');
|
|
263
|
+
}
|
|
264
|
+
return verificationMethod;
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Instantiates a {@link BearerDid} object for the DID Key method from a given {@link PortableDid}.
|
|
269
|
+
*
|
|
270
|
+
* This method allows for the creation of a `BearerDid` object using a previously created DID's
|
|
271
|
+
* key material, DID document, and metadata.
|
|
272
|
+
*
|
|
273
|
+
* @remarks
|
|
274
|
+
* The `verificationMethod` array of the DID document must contain exactly one key since the
|
|
275
|
+
* `did:key` method only supports a single verification method.
|
|
276
|
+
*
|
|
277
|
+
* @example
|
|
278
|
+
* ```ts
|
|
279
|
+
* // Export an existing BearerDid to PortableDid format.
|
|
280
|
+
* const portableDid = await did.export();
|
|
281
|
+
* // Reconstruct a BearerDid object from the PortableDid.
|
|
282
|
+
* const did = await DidKey.import({ portableDid });
|
|
283
|
+
* ```
|
|
284
|
+
*
|
|
285
|
+
* @param params - The parameters for the import operation.
|
|
286
|
+
* @param params.portableDid - The PortableDid object to import.
|
|
287
|
+
* @param params.keyManager - Optionally specify an external Key Management System (KMS) used to
|
|
288
|
+
* generate keys and sign data. If not given, a new
|
|
289
|
+
* {@link LocalKeyManager} instance will be created and
|
|
290
|
+
* used.
|
|
291
|
+
* @returns A Promise resolving to a `BearerDid` object representing the DID formed from the provided keys.
|
|
292
|
+
* @throws An error if the DID document does not contain exactly one verification method.
|
|
293
|
+
*/
|
|
294
|
+
static import(_a) {
|
|
295
|
+
return __awaiter(this, arguments, void 0, function* ({ portableDid, keyManager = new LocalKeyManager() }) {
|
|
296
|
+
// Verify the DID method is supported.
|
|
297
|
+
const parsedDid = Did.parse(portableDid.uri);
|
|
298
|
+
if ((parsedDid === null || parsedDid === void 0 ? void 0 : parsedDid.method) !== DidKey.methodName) {
|
|
299
|
+
throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported`);
|
|
300
|
+
}
|
|
301
|
+
// Use the given PortableDid to construct the BearerDid object.
|
|
302
|
+
const did = yield BearerDid.import({ portableDid, keyManager });
|
|
303
|
+
// Validate that the given DID document contains exactly one verification method.
|
|
304
|
+
// Note: The non-undefined assertion is necessary because the type system cannot infer that
|
|
305
|
+
// the `verificationMethod` property is defined -- which is checked by `BearerDid.import()`.
|
|
306
|
+
if (did.document.verificationMethod.length !== 1) {
|
|
307
|
+
throw new DidError(DidErrorCode.InvalidDidDocument, `DID document must contain exactly one verification method`);
|
|
308
|
+
}
|
|
309
|
+
return did;
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Resolves a `did:key` identifier to a DID Document.
|
|
314
|
+
*
|
|
315
|
+
* @param didUri - The DID to be resolved.
|
|
316
|
+
* @param options - Optional parameters for resolving the DID.
|
|
317
|
+
* @returns A Promise resolving to a {@link DidResolutionResult} object representing the result of the resolution.
|
|
318
|
+
*/
|
|
319
|
+
static resolve(didUri, options) {
|
|
320
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
321
|
+
try {
|
|
322
|
+
// Attempt to expand the DID URI string to a DID document.
|
|
323
|
+
const didDocument = yield DidKey.createDocument({ didUri, options });
|
|
324
|
+
// If the DID document was created successfully, return it.
|
|
325
|
+
return Object.assign(Object.assign({}, EMPTY_DID_RESOLUTION_RESULT), { didDocument });
|
|
326
|
+
}
|
|
327
|
+
catch (error) {
|
|
328
|
+
// Rethrow any unexpected errors that are not a `DidError`.
|
|
329
|
+
if (!(error instanceof DidError))
|
|
330
|
+
throw new Error(error);
|
|
331
|
+
// Return a DID Resolution Result with the appropriate error code.
|
|
332
|
+
return Object.assign(Object.assign({}, EMPTY_DID_RESOLUTION_RESULT), { didResolutionMetadata: Object.assign({ error: error.code }, error.message && { errorMessage: error.message }) });
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Expands a did:key identifier to a DID Document.
|
|
338
|
+
*
|
|
339
|
+
* Reference: https://w3c-ccg.github.io/did-method-key/#document-creation-algorithm
|
|
340
|
+
*
|
|
341
|
+
* @param options
|
|
342
|
+
* @returns - A DID dodcument.
|
|
343
|
+
*/
|
|
344
|
+
static createDocument(_a) {
|
|
345
|
+
return __awaiter(this, arguments, void 0, function* ({ didUri, options = {} }) {
|
|
346
|
+
const { defaultContext = 'https://www.w3.org/ns/did/v1', enableEncryptionKeyDerivation = false, enableExperimentalPublicKeyTypes = false, publicKeyFormat = 'JsonWebKey2020' } = options;
|
|
347
|
+
/**
|
|
348
|
+
* 1. Initialize document to an empty object.
|
|
349
|
+
*/
|
|
350
|
+
const didDocument = { id: '' };
|
|
351
|
+
/**
|
|
352
|
+
* 2. Using a colon (:) as the delimiter, split the identifier into its
|
|
353
|
+
* components: a scheme, a method, a version, and a multibaseValue.
|
|
354
|
+
* If there are only three components set the version to the string
|
|
355
|
+
* value 1 and use the last value as the multibaseValue.
|
|
356
|
+
*/
|
|
357
|
+
const parsedDid = Did.parse(didUri);
|
|
358
|
+
if (!parsedDid) {
|
|
359
|
+
throw new DidError(DidErrorCode.InvalidDid, `Invalid DID URI: ${didUri}`);
|
|
360
|
+
}
|
|
361
|
+
const multibaseValue = parsedDid.id;
|
|
362
|
+
/**
|
|
363
|
+
* 3. Check the validity of the input identifier.
|
|
364
|
+
* The scheme MUST be the value did. The method MUST be the value key.
|
|
365
|
+
* The version MUST be convertible to a positive integer value. The
|
|
366
|
+
* multibaseValue MUST be a string and begin with the letter z. If any
|
|
367
|
+
* of these requirements fail, an invalidDid error MUST be raised.
|
|
368
|
+
*/
|
|
369
|
+
if (parsedDid.method !== DidKey.methodName) {
|
|
370
|
+
throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported: ${parsedDid.method}`);
|
|
371
|
+
}
|
|
372
|
+
if (!DidKey.validateIdentifier(parsedDid)) {
|
|
373
|
+
throw new DidError(DidErrorCode.InvalidDid, `Invalid DID URI: ${didUri}`);
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* 4. Initialize the signatureVerificationMethod to the result of passing
|
|
377
|
+
* identifier, multibaseValue, and options to a
|
|
378
|
+
* {@link https://w3c-ccg.github.io/did-method-key/#signature-method-creation-algorithm | Signature Method Creation Algorithm}.
|
|
379
|
+
*/
|
|
380
|
+
const signatureVerificationMethod = yield DidKey.createSignatureMethod({
|
|
381
|
+
didUri,
|
|
382
|
+
multibaseValue,
|
|
383
|
+
options: { enableExperimentalPublicKeyTypes, publicKeyFormat }
|
|
384
|
+
});
|
|
385
|
+
/**
|
|
386
|
+
* 5. Set document.id to identifier. If document.id is not a valid DID,
|
|
387
|
+
* an invalidDid error MUST be raised.
|
|
388
|
+
*
|
|
389
|
+
* Note: Identifier was already confirmed to be valid in Step 3, so
|
|
390
|
+
* skipping the redundant validation.
|
|
391
|
+
*/
|
|
392
|
+
didDocument.id = parsedDid.uri;
|
|
393
|
+
/**
|
|
394
|
+
* 6. Initialize the verificationMethod property in document to an array
|
|
395
|
+
* where the first value is the signatureVerificationMethod.
|
|
396
|
+
*/
|
|
397
|
+
didDocument.verificationMethod = [signatureVerificationMethod];
|
|
398
|
+
/**
|
|
399
|
+
* 7. Initialize the authentication, assertionMethod, capabilityInvocation,
|
|
400
|
+
* and the capabilityDelegation properties in document to an array where
|
|
401
|
+
* the first item is the value of the id property in
|
|
402
|
+
* signatureVerificationMethod.
|
|
403
|
+
*/
|
|
404
|
+
didDocument.authentication = [signatureVerificationMethod.id];
|
|
405
|
+
didDocument.assertionMethod = [signatureVerificationMethod.id];
|
|
406
|
+
didDocument.capabilityInvocation = [signatureVerificationMethod.id];
|
|
407
|
+
didDocument.capabilityDelegation = [signatureVerificationMethod.id];
|
|
408
|
+
/**
|
|
409
|
+
* 8. If options.enableEncryptionKeyDerivation is set to true:
|
|
410
|
+
* Add the encryptionVerificationMethod value to the verificationMethod
|
|
411
|
+
* array. Initialize the keyAgreement property in document to an array
|
|
412
|
+
* where the first item is the value of the id property in
|
|
413
|
+
* encryptionVerificationMethod.
|
|
414
|
+
*/
|
|
415
|
+
if (enableEncryptionKeyDerivation === true) {
|
|
416
|
+
/**
|
|
417
|
+
* Although not covered by the did:key method specification, a sensible
|
|
418
|
+
* default will be taken to use the 'X25519KeyAgreementKey2020'
|
|
419
|
+
* verification method type if the given publicKeyFormat is
|
|
420
|
+
* 'Ed25519VerificationKey2020' and 'JsonWebKey2020' otherwise.
|
|
421
|
+
*/
|
|
422
|
+
const encryptionPublicKeyFormat = (publicKeyFormat === 'Ed25519VerificationKey2020')
|
|
423
|
+
? 'X25519KeyAgreementKey2020'
|
|
424
|
+
: 'JsonWebKey2020';
|
|
425
|
+
/**
|
|
426
|
+
* 8.1 Initialize the encryptionVerificationMethod to the result of
|
|
427
|
+
* passing identifier, multibaseValue, and options to an
|
|
428
|
+
* {@link https://w3c-ccg.github.io/did-method-key/#encryption-method-creation-algorithm | Encryption Method Creation Algorithm}.
|
|
429
|
+
*/
|
|
430
|
+
const encryptionVerificationMethod = yield this.createEncryptionMethod({
|
|
431
|
+
didUri,
|
|
432
|
+
multibaseValue,
|
|
433
|
+
options: { enableExperimentalPublicKeyTypes, publicKeyFormat: encryptionPublicKeyFormat }
|
|
434
|
+
});
|
|
435
|
+
/**
|
|
436
|
+
* 8.2 Add the encryptionVerificationMethod value to the
|
|
437
|
+
* verificationMethod array.
|
|
438
|
+
*/
|
|
439
|
+
didDocument.verificationMethod.push(encryptionVerificationMethod);
|
|
440
|
+
/**
|
|
441
|
+
* 8.3. Initialize the keyAgreement property in document to an array
|
|
442
|
+
* where the first item is the value of the id property in
|
|
443
|
+
* encryptionVerificationMethod.
|
|
444
|
+
*/
|
|
445
|
+
didDocument.keyAgreement = [encryptionVerificationMethod.id];
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* 9. Initialize the @context property in document to the result of passing document and options to the Context
|
|
449
|
+
* Creation algorithm.
|
|
450
|
+
*/
|
|
451
|
+
// Set contextArray to an array that is initialized to options.defaultContext.
|
|
452
|
+
const contextArray = [defaultContext];
|
|
453
|
+
// For every object in every verification relationship listed in document,
|
|
454
|
+
// add a string value to the contextArray based on the object type value,
|
|
455
|
+
// if it doesn't already exist, according to the following table:
|
|
456
|
+
// {@link https://w3c-ccg.github.io/did-method-key/#context-creation-algorithm | Context Type URL}
|
|
457
|
+
const verificationMethodTypes = getVerificationMethodTypes({ didDocument });
|
|
458
|
+
verificationMethodTypes.forEach((typeName) => {
|
|
459
|
+
const typeUrl = DidKeyVerificationMethodType[typeName];
|
|
460
|
+
contextArray.push(typeUrl);
|
|
461
|
+
});
|
|
462
|
+
didDocument['@context'] = contextArray;
|
|
463
|
+
/**
|
|
464
|
+
* 10. Return document.
|
|
465
|
+
*/
|
|
466
|
+
return didDocument;
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Decoding a multibase-encoded multicodec value into a verification method
|
|
471
|
+
* that is suitable for verifying that encrypted information will be
|
|
472
|
+
* received by the intended recipient.
|
|
473
|
+
*/
|
|
474
|
+
static createEncryptionMethod(_a) {
|
|
475
|
+
return __awaiter(this, arguments, void 0, function* ({ didUri, multibaseValue, options }) {
|
|
476
|
+
const { enableExperimentalPublicKeyTypes, publicKeyFormat } = options;
|
|
477
|
+
/**
|
|
478
|
+
* 1. Initialize verificationMethod to an empty object.
|
|
479
|
+
*/
|
|
480
|
+
const verificationMethod = { id: '', type: '', controller: '' };
|
|
481
|
+
/**
|
|
482
|
+
* 2. Set multicodecValue and raw publicKeyBytes to the result of passing multibaseValue and
|
|
483
|
+
* options to a Derive Encryption Key algorithm.
|
|
484
|
+
*/
|
|
485
|
+
const { keyBytes: publicKeyBytes, multicodecCode: multicodecValue, } = yield DidKey.deriveEncryptionKey({ multibaseValue });
|
|
486
|
+
/**
|
|
487
|
+
* 3. Ensure the proper key length of raw publicKeyBytes based on the multicodecValue table
|
|
488
|
+
* provided below:
|
|
489
|
+
*
|
|
490
|
+
* Multicodec hexadecimal value: 0xec
|
|
491
|
+
*
|
|
492
|
+
* If the byte length of raw publicKeyBytes does not match the expected public key length for
|
|
493
|
+
* the associated multicodecValue, an invalidPublicKeyLength error MUST be raised.
|
|
494
|
+
*/
|
|
495
|
+
const actualLength = publicKeyBytes.byteLength;
|
|
496
|
+
const expectedLength = DidKeyUtils.MULTICODEC_PUBLIC_KEY_LENGTH[multicodecValue];
|
|
497
|
+
if (actualLength !== expectedLength) {
|
|
498
|
+
throw new DidError(DidErrorCode.InvalidPublicKeyLength, `Expected ${actualLength} bytes. Actual: ${expectedLength}`);
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* 4. Create the multibaseValue by concatenating the letter 'z' and the
|
|
502
|
+
* base58-btc encoding of the concatenation of the multicodecValue and
|
|
503
|
+
* the raw publicKeyBytes.
|
|
504
|
+
*/
|
|
505
|
+
const kemMultibaseValue = keyBytesToMultibaseId({
|
|
506
|
+
keyBytes: publicKeyBytes,
|
|
507
|
+
multicodecCode: multicodecValue
|
|
508
|
+
});
|
|
509
|
+
/**
|
|
510
|
+
* 5. Set the verificationMethod.id value by concatenating identifier,
|
|
511
|
+
* a hash character (#), and the multibaseValue. If verificationMethod.id
|
|
512
|
+
* is not a valid DID URL, an invalidDidUrl error MUST be raised.
|
|
513
|
+
*/
|
|
514
|
+
verificationMethod.id = `${didUri}#${kemMultibaseValue}`;
|
|
515
|
+
try {
|
|
516
|
+
new URL(verificationMethod.id);
|
|
517
|
+
}
|
|
518
|
+
catch (error) {
|
|
519
|
+
throw new DidError(DidErrorCode.InvalidDidUrl, 'Verification Method ID is not a valid DID URL.');
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* 6. Set the publicKeyFormat value to the options.publicKeyFormat value.
|
|
523
|
+
* 7. If publicKeyFormat is not known to the implementation, an
|
|
524
|
+
* unsupportedPublicKeyType error MUST be raised.
|
|
525
|
+
*/
|
|
526
|
+
if (!(publicKeyFormat in DidKeyVerificationMethodType)) {
|
|
527
|
+
throw new DidError(DidErrorCode.UnsupportedPublicKeyType, `Unsupported format: ${publicKeyFormat}`);
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* 8. If options.enableExperimentalPublicKeyTypes is set to false and publicKeyFormat is not
|
|
531
|
+
* Multikey, JsonWebKey2020, or X25519KeyAgreementKey2020, an invalidPublicKeyType error MUST be
|
|
532
|
+
* raised.
|
|
533
|
+
*/
|
|
534
|
+
const StandardPublicKeyTypes = ['Multikey', 'JsonWebKey2020', 'X25519KeyAgreementKey2020'];
|
|
535
|
+
if (enableExperimentalPublicKeyTypes === false
|
|
536
|
+
&& !(StandardPublicKeyTypes.includes(publicKeyFormat))) {
|
|
537
|
+
throw new DidError(DidErrorCode.InvalidPublicKeyType, `Specified '${publicKeyFormat}' without setting enableExperimentalPublicKeyTypes to true.`);
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* 9. Set verificationMethod.type to the publicKeyFormat value.
|
|
541
|
+
*/
|
|
542
|
+
verificationMethod.type = publicKeyFormat;
|
|
543
|
+
/**
|
|
544
|
+
* 10. Set verificationMethod.controller to the identifier value.
|
|
545
|
+
*/
|
|
546
|
+
verificationMethod.controller = didUri;
|
|
547
|
+
/**
|
|
548
|
+
* 11. If publicKeyFormat is Multikey or X25519KeyAgreementKey2020, set the verificationMethod.publicKeyMultibase
|
|
549
|
+
* value to multibaseValue.
|
|
550
|
+
*
|
|
551
|
+
* Note: This implementation does not currently support the Multikey
|
|
552
|
+
* format.
|
|
553
|
+
*/
|
|
554
|
+
if (publicKeyFormat === 'X25519KeyAgreementKey2020') {
|
|
555
|
+
verificationMethod.publicKeyMultibase = kemMultibaseValue;
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* 12. If publicKeyFormat is JsonWebKey2020, set the verificationMethod.publicKeyJwk value to
|
|
559
|
+
* the result of passing multicodecValue and rawPublicKeyBytes to a JWK encoding algorithm.
|
|
560
|
+
*/
|
|
561
|
+
if (publicKeyFormat === 'JsonWebKey2020') {
|
|
562
|
+
const { crv } = yield DidKeyUtils.multicodecToJwk({ code: multicodecValue });
|
|
563
|
+
verificationMethod.publicKeyJwk = yield DidKeyUtils.keyConverter(crv).bytesToPublicKey({ publicKeyBytes });
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* 13. Return verificationMethod.
|
|
567
|
+
*/
|
|
568
|
+
return verificationMethod;
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Decodes a multibase-encoded multicodec value into a verification method
|
|
573
|
+
* that is suitable for verifying digital signatures.
|
|
574
|
+
* @param options - Signature method creation algorithm inputs.
|
|
575
|
+
* @returns - A verification method.
|
|
576
|
+
*/
|
|
577
|
+
static createSignatureMethod(_a) {
|
|
578
|
+
return __awaiter(this, arguments, void 0, function* ({ didUri, multibaseValue, options }) {
|
|
579
|
+
const { enableExperimentalPublicKeyTypes, publicKeyFormat } = options;
|
|
580
|
+
/**
|
|
581
|
+
* 1. Initialize verificationMethod to an empty object.
|
|
582
|
+
*/
|
|
583
|
+
const verificationMethod = { id: '', type: '', controller: '' };
|
|
584
|
+
/**
|
|
585
|
+
* 2. Set multicodecValue and publicKeyBytes to the result of passing
|
|
586
|
+
* multibaseValue and options to a Decode Public Key algorithm.
|
|
587
|
+
*/
|
|
588
|
+
const { keyBytes: publicKeyBytes, multicodecCode: multicodecValue, multicodecName } = multibaseIdToKeyBytes({ multibaseKeyId: multibaseValue });
|
|
589
|
+
/**
|
|
590
|
+
* 3. Ensure the proper key length of publicKeyBytes based on the multicodecValue
|
|
591
|
+
* {@link https://w3c-ccg.github.io/did-method-key/#signature-method-creation-algorithm | table provided}.
|
|
592
|
+
* If the byte length of rawPublicKeyBytes does not match the expected public key length for the
|
|
593
|
+
* associated multicodecValue, an invalidPublicKeyLength error MUST be raised.
|
|
594
|
+
*/
|
|
595
|
+
const actualLength = publicKeyBytes.byteLength;
|
|
596
|
+
const expectedLength = DidKeyUtils.MULTICODEC_PUBLIC_KEY_LENGTH[multicodecValue];
|
|
597
|
+
if (actualLength !== expectedLength) {
|
|
598
|
+
throw new DidError(DidErrorCode.InvalidPublicKeyLength, `Expected ${actualLength} bytes. Actual: ${expectedLength}`);
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* 4. Ensure the publicKeyBytes are a proper encoding of the public key type as specified by
|
|
602
|
+
* the multicodecValue. If an invalid public key value is detected, an invalidPublicKey error
|
|
603
|
+
* MUST be raised.
|
|
604
|
+
*/
|
|
605
|
+
let isValid = false;
|
|
606
|
+
switch (multicodecName) {
|
|
607
|
+
case 'secp256k1-pub':
|
|
608
|
+
isValid = yield Secp256k1.validatePublicKey({ publicKeyBytes });
|
|
609
|
+
break;
|
|
610
|
+
case 'ed25519-pub':
|
|
611
|
+
isValid = yield Ed25519.validatePublicKey({ publicKeyBytes });
|
|
612
|
+
break;
|
|
613
|
+
case 'x25519-pub':
|
|
614
|
+
// TODO: Validate key once/if X25519.validatePublicKey() is implemented.
|
|
615
|
+
// isValid = X25519.validatePublicKey({ key: rawPublicKeyBytes})
|
|
616
|
+
isValid = true;
|
|
617
|
+
break;
|
|
618
|
+
}
|
|
619
|
+
if (!isValid) {
|
|
620
|
+
throw new DidError(DidErrorCode.InvalidPublicKey, 'Invalid public key detected.');
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* 5. Set the verificationMethod.id value by concatenating identifier, a hash character (#), and
|
|
624
|
+
* the multibaseValue. If verificationMethod.id is not a valid DID URL, an invalidDidUrl error
|
|
625
|
+
* MUST be raised.
|
|
626
|
+
*/
|
|
627
|
+
verificationMethod.id = `${didUri}#${multibaseValue}`;
|
|
628
|
+
try {
|
|
629
|
+
new URL(verificationMethod.id);
|
|
630
|
+
}
|
|
631
|
+
catch (error) {
|
|
632
|
+
throw new DidError(DidErrorCode.InvalidDidUrl, 'Verification Method ID is not a valid DID URL.');
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* 6. Set the publicKeyFormat value to the options.publicKeyFormat value.
|
|
636
|
+
* 7. If publicKeyFormat is not known to the implementation, an unsupportedPublicKeyType error
|
|
637
|
+
* MUST be raised.
|
|
638
|
+
*/
|
|
639
|
+
if (!(publicKeyFormat in DidKeyVerificationMethodType)) {
|
|
640
|
+
throw new DidError(DidErrorCode.UnsupportedPublicKeyType, `Unsupported format: ${publicKeyFormat}`);
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* 8. If options.enableExperimentalPublicKeyTypes is set to false and publicKeyFormat is not
|
|
644
|
+
* Multikey, JsonWebKey2020, or Ed25519VerificationKey2020, an invalidPublicKeyType error MUST
|
|
645
|
+
* be raised.
|
|
646
|
+
*/
|
|
647
|
+
const StandardPublicKeyTypes = ['Multikey', 'JsonWebKey2020', 'Ed25519VerificationKey2020'];
|
|
648
|
+
if (enableExperimentalPublicKeyTypes === false
|
|
649
|
+
&& !(StandardPublicKeyTypes.includes(publicKeyFormat))) {
|
|
650
|
+
throw new DidError(DidErrorCode.InvalidPublicKeyType, `Specified '${publicKeyFormat}' without setting enableExperimentalPublicKeyTypes to true.`);
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* 9. Set verificationMethod.type to the publicKeyFormat value.
|
|
654
|
+
*/
|
|
655
|
+
verificationMethod.type = publicKeyFormat;
|
|
656
|
+
/**
|
|
657
|
+
* 10. Set verificationMethod.controller to the identifier value.
|
|
658
|
+
*/
|
|
659
|
+
verificationMethod.controller = didUri;
|
|
660
|
+
/**
|
|
661
|
+
* 11. If publicKeyFormat is Multikey or Ed25519VerificationKey2020,
|
|
662
|
+
* set the verificationMethod.publicKeyMultibase value to multibaseValue.
|
|
663
|
+
*
|
|
664
|
+
* Note: This implementation does not currently support the Multikey
|
|
665
|
+
* format.
|
|
666
|
+
*/
|
|
667
|
+
if (publicKeyFormat === 'Ed25519VerificationKey2020') {
|
|
668
|
+
verificationMethod.publicKeyMultibase = multibaseValue;
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* 12. If publicKeyFormat is JsonWebKey2020, set the verificationMethod.publicKeyJwk value to
|
|
672
|
+
* the result of passing multicodecValue and rawPublicKeyBytes to a JWK encoding algorithm.
|
|
673
|
+
*/
|
|
674
|
+
if (publicKeyFormat === 'JsonWebKey2020') {
|
|
675
|
+
const { crv } = yield DidKeyUtils.multicodecToJwk({ code: multicodecValue });
|
|
676
|
+
verificationMethod.publicKeyJwk = yield DidKeyUtils.keyConverter(crv).bytesToPublicKey({ publicKeyBytes });
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* 13. Return verificationMethod.
|
|
680
|
+
*/
|
|
681
|
+
return verificationMethod;
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* Transform a multibase-encoded multicodec value to public encryption key
|
|
686
|
+
* components that are suitable for encrypting messages to a receiver. A
|
|
687
|
+
* mathematical proof elaborating on the safety of performing this operation
|
|
688
|
+
* is available in:
|
|
689
|
+
* {@link https://eprint.iacr.org/2021/509.pdf | On using the same key pair for Ed25519 and an X25519 based KEM}
|
|
690
|
+
*/
|
|
691
|
+
static deriveEncryptionKey(_a) {
|
|
692
|
+
return __awaiter(this, arguments, void 0, function* ({ multibaseValue }) {
|
|
693
|
+
/**
|
|
694
|
+
* 1. Set publicEncryptionKey to an empty object.
|
|
695
|
+
*/
|
|
696
|
+
let publicEncryptionKey = {
|
|
697
|
+
keyBytes: new Uint8Array(),
|
|
698
|
+
multicodecCode: 0
|
|
699
|
+
};
|
|
700
|
+
/**
|
|
701
|
+
* 2. Decode multibaseValue using the base58-btc multibase alphabet and
|
|
702
|
+
* set multicodecValue to the multicodec header for the decoded value.
|
|
703
|
+
* Implementers are cautioned to ensure that the multicodecValue is set
|
|
704
|
+
* to the result after performing varint decoding.
|
|
705
|
+
*
|
|
706
|
+
* 3. Set the rawPublicKeyBytes to the bytes remaining after the multicodec
|
|
707
|
+
* header.
|
|
708
|
+
*/
|
|
709
|
+
const { keyBytes: publicKeyBytes, multicodecCode: multicodecValue } = multibaseIdToKeyBytes({ multibaseKeyId: multibaseValue });
|
|
710
|
+
/**
|
|
711
|
+
* 4. If the multicodecValue is 0xed (Ed25519 public key), derive a public X25519 encryption key
|
|
712
|
+
* by using the raw publicKeyBytes and the algorithm defined in
|
|
713
|
+
* {@link https://datatracker.ietf.org/doc/html/draft-ietf-core-oscore-groupcomm | Group OSCORE - Secure Group Communication for CoAP}
|
|
714
|
+
* for Curve25519 in Section 2.4.2: ECDH with Montgomery Coordinates and set
|
|
715
|
+
* generatedPublicEncryptionKeyBytes to the result.
|
|
716
|
+
*/
|
|
717
|
+
if (multicodecValue === 0xed) {
|
|
718
|
+
const ed25519PublicKey = yield DidKeyUtils.keyConverter('Ed25519').bytesToPublicKey({
|
|
719
|
+
publicKeyBytes
|
|
720
|
+
});
|
|
721
|
+
const generatedPublicEncryptionKey = yield Ed25519.convertPublicKeyToX25519({
|
|
722
|
+
publicKey: ed25519PublicKey
|
|
723
|
+
});
|
|
724
|
+
const generatedPublicEncryptionKeyBytes = yield DidKeyUtils.keyConverter('Ed25519').publicKeyToBytes({
|
|
725
|
+
publicKey: generatedPublicEncryptionKey
|
|
726
|
+
});
|
|
727
|
+
/**
|
|
728
|
+
* 5. Set multicodecValue to 0xec.
|
|
729
|
+
* 6. Set raw public keyBytes to generatedPublicEncryptionKeyBytes.
|
|
730
|
+
*/
|
|
731
|
+
publicEncryptionKey = {
|
|
732
|
+
keyBytes: generatedPublicEncryptionKeyBytes,
|
|
733
|
+
multicodecCode: 0xec
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
/**
|
|
737
|
+
* 7. Return publicEncryptionKey.
|
|
738
|
+
*/
|
|
739
|
+
return publicEncryptionKey;
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
/**
|
|
743
|
+
* Validates the structure and components of a DID URI against the `did:key` method specification.
|
|
744
|
+
*
|
|
745
|
+
* @param parsedDid - An object representing the parsed components of a DID URI, including the
|
|
746
|
+
* scheme, method, and method-specific identifier.
|
|
747
|
+
* @returns `true` if the DID URI meets the `did:key` method's structural requirements, `false` otherwise.
|
|
748
|
+
*
|
|
749
|
+
*/
|
|
750
|
+
static validateIdentifier(parsedDid) {
|
|
751
|
+
const { method, id: multibaseValue } = parsedDid;
|
|
752
|
+
const [scheme] = parsedDid.uri.split(':', 1);
|
|
753
|
+
/**
|
|
754
|
+
* Note: The W3C DID specification makes no mention of a version value being part of the DID
|
|
755
|
+
* syntax. Additionally, there does not appear to be any real-world usage of the version
|
|
756
|
+
* number. Consequently, this implementation will ignore the version related guidance in
|
|
757
|
+
* the did:key specification.
|
|
758
|
+
*/
|
|
759
|
+
const version = '1';
|
|
760
|
+
return (scheme === 'did' &&
|
|
761
|
+
method === 'key' &&
|
|
762
|
+
Number(version) > 0 &&
|
|
763
|
+
universalTypeOf(multibaseValue) === 'String' &&
|
|
764
|
+
multibaseValue.startsWith('z'));
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Name of the DID method, as defined in the DID Key specification.
|
|
769
|
+
*/
|
|
770
|
+
DidKey.methodName = 'key';
|
|
771
|
+
/**
|
|
772
|
+
* The `DidKeyUtils` class provides utility functions to support operations in the DID Key method.
|
|
773
|
+
*/
|
|
774
|
+
export class DidKeyUtils {
|
|
775
|
+
/**
|
|
776
|
+
* Converts a JWK (JSON Web Key) to a Multicodec code and name.
|
|
777
|
+
*
|
|
778
|
+
* @example
|
|
779
|
+
* ```ts
|
|
780
|
+
* const jwk: Jwk = { crv: 'Ed25519', kty: 'OKP', x: '...' };
|
|
781
|
+
* const { code, name } = await DidKeyUtils.jwkToMulticodec({ jwk });
|
|
782
|
+
* ```
|
|
783
|
+
*
|
|
784
|
+
* @param params - The parameters for the conversion.
|
|
785
|
+
* @param params.jwk - The JSON Web Key to be converted.
|
|
786
|
+
* @returns A promise that resolves to a Multicodec definition.
|
|
787
|
+
*/
|
|
788
|
+
static jwkToMulticodec(_a) {
|
|
789
|
+
return __awaiter(this, arguments, void 0, function* ({ jwk }) {
|
|
790
|
+
const params = [];
|
|
791
|
+
if (jwk.crv) {
|
|
792
|
+
params.push(jwk.crv);
|
|
793
|
+
if (jwk.d) {
|
|
794
|
+
params.push('private');
|
|
795
|
+
}
|
|
796
|
+
else {
|
|
797
|
+
params.push('public');
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
const lookupKey = params.join(':');
|
|
801
|
+
const name = DidKeyUtils.JWK_TO_MULTICODEC[lookupKey];
|
|
802
|
+
if (name === undefined) {
|
|
803
|
+
throw new Error(`Unsupported JWK to Multicodec conversion: '${lookupKey}'`);
|
|
804
|
+
}
|
|
805
|
+
const code = Multicodec.getCodeFromName({ name });
|
|
806
|
+
return { code, name };
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* Returns the appropriate public key compressor for the specified cryptographic curve.
|
|
811
|
+
*
|
|
812
|
+
* @param curve - The cryptographic curve to use for the key conversion.
|
|
813
|
+
* @returns A public key compressor for the specified curve.
|
|
814
|
+
*/
|
|
815
|
+
static keyCompressor(curve) {
|
|
816
|
+
// ): ({ publicKeyBytes }: { publicKeyBytes: Uint8Array }) => Promise<Uint8Array> {
|
|
817
|
+
const compressors = {
|
|
818
|
+
'P-256': Secp256r1.compressPublicKey,
|
|
819
|
+
'secp256k1': Secp256k1.compressPublicKey
|
|
820
|
+
};
|
|
821
|
+
const compressor = compressors[curve];
|
|
822
|
+
if (!compressor)
|
|
823
|
+
throw new DidError(DidErrorCode.InvalidPublicKeyType, `Unsupported curve: ${curve}`);
|
|
824
|
+
return compressor;
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* Returns the appropriate key converter for the specified cryptographic curve.
|
|
828
|
+
*
|
|
829
|
+
* @param curve - The cryptographic curve to use for the key conversion.
|
|
830
|
+
* @returns An `AsymmetricKeyConverter` for the specified curve.
|
|
831
|
+
*/
|
|
832
|
+
static keyConverter(curve) {
|
|
833
|
+
const converters = {
|
|
834
|
+
'Ed25519': Ed25519,
|
|
835
|
+
'P-256': Secp256r1,
|
|
836
|
+
'secp256k1': Secp256k1,
|
|
837
|
+
'X25519': X25519
|
|
838
|
+
};
|
|
839
|
+
const converter = converters[curve];
|
|
840
|
+
if (!converter)
|
|
841
|
+
throw new DidError(DidErrorCode.InvalidPublicKeyType, `Unsupported curve: ${curve}`);
|
|
842
|
+
return converter;
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
845
|
+
* Converts a Multicodec code or name to parial JWK (JSON Web Key).
|
|
846
|
+
*
|
|
847
|
+
* @example
|
|
848
|
+
* ```ts
|
|
849
|
+
* const partialJwk = await DidKeyUtils.multicodecToJwk({ name: 'ed25519-pub' });
|
|
850
|
+
* ```
|
|
851
|
+
*
|
|
852
|
+
* @param params - The parameters for the conversion.
|
|
853
|
+
* @param params.code - Optional Multicodec code to convert.
|
|
854
|
+
* @param params.name - Optional Multicodec name to convert.
|
|
855
|
+
* @returns A promise that resolves to a JOSE format key.
|
|
856
|
+
*/
|
|
857
|
+
static multicodecToJwk(_a) {
|
|
858
|
+
return __awaiter(this, arguments, void 0, function* ({ code, name }) {
|
|
859
|
+
// Either code or name must be specified, but not both.
|
|
860
|
+
if (!(name ? !code : code)) {
|
|
861
|
+
throw new Error(`Either 'name' or 'code' must be defined, but not both.`);
|
|
862
|
+
}
|
|
863
|
+
// If name is undefined, lookup by code.
|
|
864
|
+
name = (name === undefined) ? Multicodec.getNameFromCode({ code: code }) : name;
|
|
865
|
+
const lookupKey = name;
|
|
866
|
+
const jose = DidKeyUtils.MULTICODEC_TO_JWK[lookupKey];
|
|
867
|
+
if (jose === undefined) {
|
|
868
|
+
throw new Error(`Unsupported Multicodec to JWK conversion`);
|
|
869
|
+
}
|
|
870
|
+
return Object.assign({}, jose);
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* Converts a public key in JWK (JSON Web Key) format to a multibase identifier.
|
|
875
|
+
*
|
|
876
|
+
* @remarks
|
|
877
|
+
* Note: All secp public keys are converted to compressed point encoding
|
|
878
|
+
* before the multibase identifier is computed.
|
|
879
|
+
*
|
|
880
|
+
* Per {@link https://github.com/multiformats/multicodec/blob/master/table.csv | Multicodec table}:
|
|
881
|
+
* Public keys for Elliptic Curve cryptography algorithms (e.g., secp256k1,
|
|
882
|
+
* secp256k1r1, secp384r1, etc.) are always represented with compressed point
|
|
883
|
+
* encoding (e.g., secp256k1-pub, p256-pub, p384-pub, etc.).
|
|
884
|
+
*
|
|
885
|
+
* Per {@link https://datatracker.ietf.org/doc/html/rfc8812#name-jose-and-cose-secp256k1-cur | RFC 8812}:
|
|
886
|
+
* "As a compressed point encoding representation is not defined for JWK
|
|
887
|
+
* elliptic curve points, the uncompressed point encoding defined there
|
|
888
|
+
* MUST be used. The x and y values represented MUST both be exactly
|
|
889
|
+
* 256 bits, with any leading zeros preserved."
|
|
890
|
+
*
|
|
891
|
+
* @example
|
|
892
|
+
* ```ts
|
|
893
|
+
* const publicKey = { crv: 'Ed25519', kty: 'OKP', x: '...' };
|
|
894
|
+
* const multibaseId = await DidKeyUtils.publicKeyToMultibaseId({ publicKey });
|
|
895
|
+
* ```
|
|
896
|
+
*
|
|
897
|
+
* @param params - The parameters for the conversion.
|
|
898
|
+
* @param params.publicKey - The public key in JWK format.
|
|
899
|
+
* @returns A promise that resolves to the multibase identifier.
|
|
900
|
+
*/
|
|
901
|
+
static publicKeyToMultibaseId(_a) {
|
|
902
|
+
return __awaiter(this, arguments, void 0, function* ({ publicKey }) {
|
|
903
|
+
var _b;
|
|
904
|
+
if (!((publicKey === null || publicKey === void 0 ? void 0 : publicKey.crv) && publicKey.crv in AlgorithmToKeyTypeMap)) {
|
|
905
|
+
throw new DidError(DidErrorCode.InvalidPublicKeyType, `Public key contains an unsupported key type: ${(_b = publicKey === null || publicKey === void 0 ? void 0 : publicKey.crv) !== null && _b !== void 0 ? _b : 'undefined'}`);
|
|
906
|
+
}
|
|
907
|
+
// Convert the public key from JWK format to a byte array.
|
|
908
|
+
let publicKeyBytes = yield DidKeyUtils.keyConverter(publicKey.crv).publicKeyToBytes({ publicKey });
|
|
909
|
+
// Compress the public key if it is an elliptic curve key.
|
|
910
|
+
if (/^(secp256k1|P-256|P-384|P-521)$/.test(publicKey.crv)) {
|
|
911
|
+
publicKeyBytes = yield DidKeyUtils.keyCompressor(publicKey.crv)({ publicKeyBytes });
|
|
912
|
+
}
|
|
913
|
+
// Convert the JSON Web Key (JWK) parameters to a Multicodec name.
|
|
914
|
+
const { name: multicodecName } = yield DidKeyUtils.jwkToMulticodec({ jwk: publicKey });
|
|
915
|
+
// Compute the multibase identifier based on the provided key.
|
|
916
|
+
const multibaseId = keyBytesToMultibaseId({
|
|
917
|
+
keyBytes: publicKeyBytes,
|
|
918
|
+
multicodecName
|
|
919
|
+
});
|
|
920
|
+
return multibaseId;
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* A mapping from JSON Web Key (JWK) property descriptors to multicodec names.
|
|
926
|
+
*
|
|
927
|
+
* This mapping is used to convert keys in JWK (JSON Web Key) format to multicodec format.
|
|
928
|
+
*
|
|
929
|
+
* @remarks
|
|
930
|
+
* The keys of this object are strings that describe the JOSE key type and usage,
|
|
931
|
+
* such as 'Ed25519:public', 'Ed25519:private', etc. The values are the corresponding multicodec
|
|
932
|
+
* names used to represent these key types.
|
|
933
|
+
*
|
|
934
|
+
* @example
|
|
935
|
+
* ```ts
|
|
936
|
+
* const multicodecName = JWK_TO_MULTICODEC['Ed25519:public'];
|
|
937
|
+
* // Returns 'ed25519-pub', the multicodec name for an Ed25519 public key
|
|
938
|
+
* ```
|
|
939
|
+
*/
|
|
940
|
+
DidKeyUtils.JWK_TO_MULTICODEC = {
|
|
941
|
+
'Ed25519:public': 'ed25519-pub',
|
|
942
|
+
'Ed25519:private': 'ed25519-priv',
|
|
943
|
+
'secp256k1:public': 'secp256k1-pub',
|
|
944
|
+
'secp256k1:private': 'secp256k1-priv',
|
|
945
|
+
'X25519:public': 'x25519-pub',
|
|
946
|
+
'X25519:private': 'x25519-priv',
|
|
947
|
+
};
|
|
948
|
+
/**
|
|
949
|
+
* Defines the expected byte lengths for public keys associated with different cryptographic
|
|
950
|
+
* algorithms, indexed by their multicodec code values.
|
|
951
|
+
*/
|
|
952
|
+
DidKeyUtils.MULTICODEC_PUBLIC_KEY_LENGTH = {
|
|
953
|
+
// secp256k1-pub - Secp256k1 public key (compressed) - 33 bytes
|
|
954
|
+
0xe7: 33,
|
|
955
|
+
// x25519-pub - Curve25519 public key - 32 bytes
|
|
956
|
+
0xec: 32,
|
|
957
|
+
// ed25519-pub - Ed25519 public key - 32 bytes
|
|
958
|
+
0xed: 32
|
|
959
|
+
};
|
|
960
|
+
/**
|
|
961
|
+
* A mapping from multicodec names to their corresponding JOSE (JSON Object Signing and Encryption)
|
|
962
|
+
* representations. This mapping facilitates the conversion of multicodec key formats to
|
|
963
|
+
* JWK (JSON Web Key) formats.
|
|
964
|
+
*
|
|
965
|
+
* @remarks
|
|
966
|
+
* The keys of this object are multicodec names, such as 'ed25519-pub', 'ed25519-priv', etc.
|
|
967
|
+
* The values are objects representing the corresponding JWK properties for that key type.
|
|
968
|
+
*
|
|
969
|
+
* @example
|
|
970
|
+
* ```ts
|
|
971
|
+
* const joseKey = MULTICODEC_TO_JWK['ed25519-pub'];
|
|
972
|
+
* // Returns a partial JWK for an Ed25519 public key
|
|
973
|
+
* ```
|
|
974
|
+
*/
|
|
975
|
+
DidKeyUtils.MULTICODEC_TO_JWK = {
|
|
976
|
+
'ed25519-pub': { crv: 'Ed25519', kty: 'OKP', x: '' },
|
|
977
|
+
'ed25519-priv': { crv: 'Ed25519', kty: 'OKP', x: '', d: '' },
|
|
978
|
+
'secp256k1-pub': { crv: 'secp256k1', kty: 'EC', x: '', y: '' },
|
|
979
|
+
'secp256k1-priv': { crv: 'secp256k1', kty: 'EC', x: '', y: '', d: '' },
|
|
980
|
+
'x25519-pub': { crv: 'X25519', kty: 'OKP', x: '' },
|
|
981
|
+
'x25519-priv': { crv: 'X25519', kty: 'OKP', x: '', d: '' },
|
|
982
|
+
};
|
|
983
|
+
//# sourceMappingURL=did-key.js.map
|