@sphereon/ssi-sdk-ext.did-utils 0.10.2-next.20

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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this fragment.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2021] [Sphereon BV]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,43 @@
1
+ <!--suppress HtmlDeprecatedAttribute -->
2
+ <h1 align="center">
3
+ <br>
4
+ <a href="https://www.sphereon.com"><img src="https://sphereon.com/content/themes/sphereon/assets/img/logo.svg" alt="Sphereon" width="400"></a>
5
+ <br>SSI SDK DID Utils
6
+ <br>
7
+ </h1>
8
+
9
+ # did-utils
10
+
11
+ A SSI SDK plugin with different DID functions
12
+
13
+ ### Installation
14
+
15
+ ```shell
16
+ yarn add @sphereon/ssi-sdk-ext.did-utils
17
+ ```
18
+
19
+ ### Build
20
+
21
+ ```shell
22
+ yarn build
23
+ ```
24
+
25
+ ### Test
26
+
27
+ The test command runs:
28
+
29
+ - `prettier`
30
+ - `jest`
31
+ - `coverage`
32
+
33
+ You can also run only a single section of these tests, using for example `yarn test:unit`.
34
+
35
+ ```shell
36
+ yarn test
37
+ ```
38
+
39
+ ### Utility scripts
40
+
41
+ There are other utility scripts that help with development.
42
+
43
+ - `yarn fix` - runs `eslint --fix` as well as `prettier` to fix code style.
@@ -0,0 +1,58 @@
1
+ import { DIDDocument, DIDDocumentSection, DIDResolutionResult, IAgentContext, IDIDManager, IIdentifier, IKey, IResolver } from '@veramo/core';
2
+ import { _ExtendedIKey, _ExtendedVerificationMethod, _NormalizedVerificationMethod } from '@veramo/utils';
3
+ import { DIDResolutionOptions, Resolvable } from 'did-resolver';
4
+ import { IDIDOptions, IIdentifierOpts } from './types';
5
+ export declare const getFirstKeyWithRelation: (identifier: IIdentifier, context: IAgentContext<IResolver>, vmRelationship?: DIDDocumentSection, errorOnNotFound?: boolean) => Promise<_ExtendedIKey | undefined>;
6
+ /**
7
+ * Dereferences keys from DID document and normalizes them for easy comparison.
8
+ *
9
+ * When dereferencing keyAgreement keys, only Ed25519 and X25519 curves are supported.
10
+ * Other key types are omitted from the result and Ed25519 keys are converted to X25519
11
+ *
12
+ * @returns a Promise that resolves to the list of dereferenced keys.
13
+ *
14
+ * @beta This API may change without a BREAKING CHANGE notice.
15
+ */
16
+ export declare function dereferenceDidKeysWithJwkSupport(didDocument: DIDDocument, section: DIDDocumentSection | undefined, context: IAgentContext<IResolver>): Promise<_NormalizedVerificationMethod[]>;
17
+ /**
18
+ * Converts the publicKey of a VerificationMethod to hex encoding (publicKeyHex)
19
+ *
20
+ * @param pk - the VerificationMethod to be converted
21
+ * @param convert - when this flag is set to true, Ed25519 keys are converted to their X25519 pairs
22
+ * @returns the hex encoding of the public key
23
+ *
24
+ * @beta This API may change without a BREAKING CHANGE notice.
25
+ */
26
+ export declare function extractPublicKeyHexWithJwkSupport(pk: _ExtendedVerificationMethod, convert?: boolean): string;
27
+ /**
28
+ * Maps the keys of a locally managed {@link @veramo/core#IIdentifier | IIdentifier} to the corresponding
29
+ * {@link did-resolver#VerificationMethod | VerificationMethod} entries from the DID document.
30
+ *
31
+ * @param identifier - the identifier to be mapped
32
+ * @param section - the section of the DID document to be mapped (see
33
+ * {@link https://www.w3.org/TR/did-core/#verification-relationships | verification relationships}), but can also be
34
+ * `verificationMethod` to map all the keys.
35
+ * @param context - the veramo agent context, which must contain a {@link @veramo/core#IResolver | IResolver}
36
+ * implementation that can resolve the DID document of the identifier.
37
+ *
38
+ * @returns an array of mapped keys. The corresponding verification method is added to the `meta.verificationMethod`
39
+ * property of the key.
40
+ *
41
+ * @beta This API may change without a BREAKING CHANGE notice.
42
+ */
43
+ export declare function mapIdentifierKeysToDocWithJwkSupport(identifier: IIdentifier, section: DIDDocumentSection | undefined, context: IAgentContext<IResolver>, didDocument?: DIDDocument): Promise<_ExtendedIKey[]>;
44
+ export declare function getAgentDIDMethods(context: IAgentContext<IDIDManager>): Promise<string[]>;
45
+ export declare function getIdentifier(identifierOpts: IIdentifierOpts, context: IAgentContext<IDIDManager>): Promise<IIdentifier>;
46
+ export declare function getDID(identifierOpts: IIdentifierOpts): string;
47
+ export declare function toDID(identifier: string | IIdentifier | Partial<IIdentifier>): string;
48
+ export declare function toDIDs(identifiers?: (string | IIdentifier | Partial<IIdentifier>)[]): string[];
49
+ export declare function getKey(identifier: IIdentifier, verificationMethodSection: DIDDocumentSection | undefined, context: IAgentContext<IResolver>, keyId?: string): Promise<IKey>;
50
+ export declare function determineKid(key: IKey, idOpts: IIdentifierOpts): string;
51
+ export declare function getSupportedDIDMethods(didOpts: IDIDOptions, context: IAgentContext<IDIDManager>): Promise<string[]>;
52
+ export declare class AgentDIDResolver implements Resolvable {
53
+ private readonly context;
54
+ private readonly uniresolverFallback;
55
+ constructor(context: IAgentContext<IResolver>, uniresolverFallback?: boolean);
56
+ resolve(didUrl: string, options?: DIDResolutionOptions): Promise<DIDResolutionResult>;
57
+ }
58
+ //# sourceMappingURL=did-functions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"did-functions.d.ts","sourceRoot":"","sources":["../src/did-functions.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,aAAa,EAAE,WAAW,EAAE,WAAW,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AAC7I,OAAO,EACL,aAAa,EACb,2BAA2B,EAC3B,6BAA6B,EAK9B,MAAM,eAAe,CAAA;AACtB,OAAO,EAAE,oBAAoB,EAAE,UAAU,EAAsB,MAAM,cAAc,CAAA;AAInF,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAGtD,eAAO,MAAM,uBAAuB,eACtB,WAAW,WACd,cAAc,SAAS,CAAC,mBAChB,kBAAkB,oBACjB,OAAO,KACxB,QAAQ,aAAa,GAAG,SAAS,CAUnC,CAAA;AAGD;;;;;;;;;GASG;AACH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ED,wBAAsB,sBAAsB,CAAC,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,aAAa,CAAC,WAAW,CAAC,qBAErG;AAED,qBAAa,gBAAiB,YAAW,UAAU;IACjD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA0B;IAClD,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAS;gBAEjC,OAAO,EAAE,aAAa,CAAC,SAAS,CAAC,EAAE,mBAAmB,CAAC,EAAE,OAAO;IAKtE,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,mBAAmB,CAAC;CAU5F"}
@@ -0,0 +1,282 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __rest = (this && this.__rest) || function (s, e) {
35
+ var t = {};
36
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
37
+ t[p] = s[p];
38
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
39
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
40
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
41
+ t[p[i]] = s[p[i]];
42
+ }
43
+ return t;
44
+ };
45
+ var __importDefault = (this && this.__importDefault) || function (mod) {
46
+ return (mod && mod.__esModule) ? mod : { "default": mod };
47
+ };
48
+ Object.defineProperty(exports, "__esModule", { value: true });
49
+ exports.AgentDIDResolver = exports.getSupportedDIDMethods = exports.determineKid = exports.getKey = exports.toDIDs = exports.toDID = exports.getDID = exports.getIdentifier = exports.getAgentDIDMethods = exports.mapIdentifierKeysToDocWithJwkSupport = exports.extractPublicKeyHexWithJwkSupport = exports.dereferenceDidKeysWithJwkSupport = exports.getFirstKeyWithRelation = void 0;
50
+ const did_uni_client_1 = require("@sphereon/did-uni-client");
51
+ const utils_1 = require("@veramo/utils");
52
+ // @ts-ignore
53
+ const elliptic_1 = __importDefault(require("elliptic"));
54
+ const u8a = __importStar(require("uint8arrays"));
55
+ const ssi_sdk_ext_key_utils_1 = require("@sphereon/ssi-sdk-ext.key-utils");
56
+ const getFirstKeyWithRelation = (identifier, context, vmRelationship, errorOnNotFound) => __awaiter(void 0, void 0, void 0, function* () {
57
+ const section = vmRelationship || 'verificationMethod'; // search all VMs in case no relationship is provided
58
+ const matchedKeys = yield mapIdentifierKeysToDocWithJwkSupport(identifier, section, context);
59
+ if (Array.isArray(matchedKeys) && matchedKeys.length > 0) {
60
+ return matchedKeys[0];
61
+ }
62
+ if (errorOnNotFound === true) {
63
+ throw new Error(`Could not find key with relationship ${section} in DID document for ${identifier.did}`);
64
+ }
65
+ return undefined;
66
+ });
67
+ exports.getFirstKeyWithRelation = getFirstKeyWithRelation;
68
+ //TODO: Move to ssi-sdk/core and create PR upstream
69
+ /**
70
+ * Dereferences keys from DID document and normalizes them for easy comparison.
71
+ *
72
+ * When dereferencing keyAgreement keys, only Ed25519 and X25519 curves are supported.
73
+ * Other key types are omitted from the result and Ed25519 keys are converted to X25519
74
+ *
75
+ * @returns a Promise that resolves to the list of dereferenced keys.
76
+ *
77
+ * @beta This API may change without a BREAKING CHANGE notice.
78
+ */
79
+ function dereferenceDidKeysWithJwkSupport(didDocument, section = 'keyAgreement', context) {
80
+ return __awaiter(this, void 0, void 0, function* () {
81
+ const convert = section === 'keyAgreement';
82
+ if (section === 'service') {
83
+ return [];
84
+ }
85
+ return (yield Promise.all((didDocument[section] || []).map((key) => __awaiter(this, void 0, void 0, function* () {
86
+ if (typeof key === 'string') {
87
+ try {
88
+ return (yield context.agent.getDIDComponentById({
89
+ didDocument,
90
+ didUrl: key,
91
+ section,
92
+ }));
93
+ }
94
+ catch (e) {
95
+ return null;
96
+ }
97
+ }
98
+ else {
99
+ return key;
100
+ }
101
+ }))))
102
+ .filter(utils_1.isDefined)
103
+ .map((key) => {
104
+ const hexKey = extractPublicKeyHexWithJwkSupport(key, convert);
105
+ const { publicKeyHex, publicKeyBase58, publicKeyBase64, publicKeyJwk } = key, keyProps = __rest(key, ["publicKeyHex", "publicKeyBase58", "publicKeyBase64", "publicKeyJwk"]);
106
+ const newKey = Object.assign(Object.assign({}, keyProps), { publicKeyHex: hexKey });
107
+ if (convert && 'Ed25519VerificationKey2018' === newKey.type) {
108
+ newKey.type = 'X25519KeyAgreementKey2019';
109
+ }
110
+ return newKey;
111
+ });
112
+ });
113
+ }
114
+ exports.dereferenceDidKeysWithJwkSupport = dereferenceDidKeysWithJwkSupport;
115
+ /**
116
+ * Converts the publicKey of a VerificationMethod to hex encoding (publicKeyHex)
117
+ *
118
+ * @param pk - the VerificationMethod to be converted
119
+ * @param convert - when this flag is set to true, Ed25519 keys are converted to their X25519 pairs
120
+ * @returns the hex encoding of the public key
121
+ *
122
+ * @beta This API may change without a BREAKING CHANGE notice.
123
+ */
124
+ function extractPublicKeyHexWithJwkSupport(pk, convert = false) {
125
+ if (pk.publicKeyJwk) {
126
+ if (pk.publicKeyJwk.kty === 'EC') {
127
+ const secp256 = new elliptic_1.default.ec(pk.publicKeyJwk.crv === 'secp256k1' ? 'secp256k1' : 'p256');
128
+ const prefix = pk.publicKeyJwk.crv === 'secp256k1' ? '04' : '03';
129
+ const x = u8a.fromString(pk.publicKeyJwk.x, 'base64url');
130
+ const y = u8a.fromString(pk.publicKeyJwk.y, 'base64url');
131
+ const hex = `${prefix}${u8a.toString(x, 'base16')}${u8a.toString(y, 'base16')}`;
132
+ // We return directly as we don't want to convert the result back into Uint8Array and then convert again to hex as the elliptic lib already returns hex strings
133
+ return secp256.keyFromPublic(hex, 'hex').getPublic(true, 'hex');
134
+ }
135
+ else if (pk.publicKeyJwk.crv === 'Ed25519') {
136
+ return u8a.toString(u8a.fromString(pk.publicKeyJwk.x, 'base64url'), 'base16');
137
+ }
138
+ else if (pk.publicKeyJwk.kty === 'RSA') {
139
+ return (0, ssi_sdk_ext_key_utils_1.hexKeyFromPEMBasedJwk)(pk.publicKeyJwk, 'public');
140
+ }
141
+ }
142
+ // delegate the other types to the original Veramo function
143
+ return (0, utils_1.extractPublicKeyHex)(pk, convert);
144
+ }
145
+ exports.extractPublicKeyHexWithJwkSupport = extractPublicKeyHexWithJwkSupport;
146
+ /**
147
+ * Maps the keys of a locally managed {@link @veramo/core#IIdentifier | IIdentifier} to the corresponding
148
+ * {@link did-resolver#VerificationMethod | VerificationMethod} entries from the DID document.
149
+ *
150
+ * @param identifier - the identifier to be mapped
151
+ * @param section - the section of the DID document to be mapped (see
152
+ * {@link https://www.w3.org/TR/did-core/#verification-relationships | verification relationships}), but can also be
153
+ * `verificationMethod` to map all the keys.
154
+ * @param context - the veramo agent context, which must contain a {@link @veramo/core#IResolver | IResolver}
155
+ * implementation that can resolve the DID document of the identifier.
156
+ *
157
+ * @returns an array of mapped keys. The corresponding verification method is added to the `meta.verificationMethod`
158
+ * property of the key.
159
+ *
160
+ * @beta This API may change without a BREAKING CHANGE notice.
161
+ */
162
+ function mapIdentifierKeysToDocWithJwkSupport(identifier, section = 'keyAgreement', context, didDocument) {
163
+ return __awaiter(this, void 0, void 0, function* () {
164
+ const rsaDidWeb = identifier.keys && identifier.keys.length > 0 && identifier.keys[0].type === 'RSA' && didDocument;
165
+ // We skip mapping in case the identifier is RSA and a did document is supplied.
166
+ const keys = rsaDidWeb ? [] : yield (0, utils_1.mapIdentifierKeysToDoc)(identifier, section, context);
167
+ const didDoc = didDocument ? didDocument : yield (0, utils_1.resolveDidOrThrow)(identifier.did, context);
168
+ // dereference all key agreement keys from DID document and normalize
169
+ const documentKeys = yield dereferenceDidKeysWithJwkSupport(didDoc, section, context);
170
+ const localKeys = identifier.keys.filter(utils_1.isDefined);
171
+ // finally map the didDocument keys to the identifier keys by comparing `publicKeyHex`
172
+ const extendedKeys = documentKeys
173
+ .map((verificationMethod) => {
174
+ /*if (verificationMethod.type !== 'JsonWebKey2020') {
175
+ return null
176
+ }*/
177
+ const localKey = localKeys.find((localKey) => localKey.publicKeyHex === verificationMethod.publicKeyHex);
178
+ if (localKey) {
179
+ const { meta } = localKey, localProps = __rest(localKey, ["meta"]);
180
+ return Object.assign(Object.assign({}, localProps), { meta: Object.assign(Object.assign({}, meta), { verificationMethod }) });
181
+ }
182
+ else {
183
+ return null;
184
+ }
185
+ })
186
+ .filter(utils_1.isDefined);
187
+ return keys.concat(extendedKeys);
188
+ });
189
+ }
190
+ exports.mapIdentifierKeysToDocWithJwkSupport = mapIdentifierKeysToDocWithJwkSupport;
191
+ function getAgentDIDMethods(context) {
192
+ return __awaiter(this, void 0, void 0, function* () {
193
+ return (yield context.agent.didManagerGetProviders()).map((provider) => provider.toLowerCase().replace('did:', ''));
194
+ });
195
+ }
196
+ exports.getAgentDIDMethods = getAgentDIDMethods;
197
+ function getIdentifier(identifierOpts, context) {
198
+ return __awaiter(this, void 0, void 0, function* () {
199
+ if (typeof identifierOpts.identifier === 'string') {
200
+ return context.agent.didManagerGet({ did: identifierOpts.identifier });
201
+ }
202
+ else if (typeof identifierOpts.identifier === 'object') {
203
+ return identifierOpts.identifier;
204
+ }
205
+ throw Error(`Cannot get agent identifier value from options`);
206
+ });
207
+ }
208
+ exports.getIdentifier = getIdentifier;
209
+ function getDID(identifierOpts) {
210
+ if (typeof identifierOpts.identifier === 'string') {
211
+ return identifierOpts.identifier;
212
+ }
213
+ else if (typeof identifierOpts.identifier === 'object') {
214
+ return identifierOpts.identifier.did;
215
+ }
216
+ throw Error(`Cannot get DID from identifier value`);
217
+ }
218
+ exports.getDID = getDID;
219
+ function toDID(identifier) {
220
+ if (typeof identifier === 'string') {
221
+ return identifier;
222
+ }
223
+ if (identifier.did) {
224
+ return identifier.did;
225
+ }
226
+ throw Error(`No DID value present in identifier`);
227
+ }
228
+ exports.toDID = toDID;
229
+ function toDIDs(identifiers) {
230
+ if (!identifiers) {
231
+ return [];
232
+ }
233
+ return identifiers.map(toDID);
234
+ }
235
+ exports.toDIDs = toDIDs;
236
+ function getKey(identifier, verificationMethodSection = 'authentication', context, keyId) {
237
+ return __awaiter(this, void 0, void 0, function* () {
238
+ const keys = yield mapIdentifierKeysToDocWithJwkSupport(identifier, verificationMethodSection, context);
239
+ if (!keys || keys.length === 0) {
240
+ throw new Error(`No keys found for verificationMethodSection: ${verificationMethodSection} and did ${identifier.did}`);
241
+ }
242
+ const identifierKey = keyId ? keys.find((key) => key.kid === keyId || key.meta.verificationMethod.id === keyId) : keys[0];
243
+ if (!identifierKey) {
244
+ throw new Error(`No matching verificationMethodSection key found for keyId: ${keyId}`);
245
+ }
246
+ return identifierKey;
247
+ });
248
+ }
249
+ exports.getKey = getKey;
250
+ function determineKid(key, idOpts) {
251
+ var _a, _b, _c;
252
+ return (_c = (_b = (_a = key.meta) === null || _a === void 0 ? void 0 : _a.verificationMethod.id) !== null && _b !== void 0 ? _b : idOpts.kid) !== null && _c !== void 0 ? _c : key.kid;
253
+ }
254
+ exports.determineKid = determineKid;
255
+ function getSupportedDIDMethods(didOpts, context) {
256
+ var _a;
257
+ return __awaiter(this, void 0, void 0, function* () {
258
+ return (_a = didOpts.supportedDIDMethods) !== null && _a !== void 0 ? _a : (yield getAgentDIDMethods(context));
259
+ });
260
+ }
261
+ exports.getSupportedDIDMethods = getSupportedDIDMethods;
262
+ class AgentDIDResolver {
263
+ constructor(context, uniresolverFallback) {
264
+ this.context = context;
265
+ this.uniresolverFallback = uniresolverFallback === true;
266
+ }
267
+ resolve(didUrl, options) {
268
+ return __awaiter(this, void 0, void 0, function* () {
269
+ try {
270
+ return this.context.agent.resolveDid({ didUrl, options });
271
+ }
272
+ catch (error) {
273
+ if (this.uniresolverFallback) {
274
+ return new did_uni_client_1.UniResolver().resolve(didUrl, options);
275
+ }
276
+ throw error;
277
+ }
278
+ });
279
+ }
280
+ }
281
+ exports.AgentDIDResolver = AgentDIDResolver;
282
+ //# sourceMappingURL=did-functions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"did-functions.js","sourceRoot":"","sources":["../src/did-functions.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,6DAAsD;AAEtD,yCAQsB;AAEtB,aAAa;AACb,wDAA+B;AAC/B,iDAAkC;AAElC,2EAAuE;AAEhE,MAAM,uBAAuB,GAAG,CACrC,UAAuB,EACvB,OAAiC,EACjC,cAAmC,EACnC,eAAyB,EACW,EAAE;IACtC,MAAM,OAAO,GAAG,cAAc,IAAI,oBAAoB,CAAA,CAAC,qDAAqD;IAC5G,MAAM,WAAW,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AAM,KAAK,CAAA;aACZ;QACH,CAAC;KAAA;CACF;AAnBD,4CAmBC"}
@@ -0,0 +1,3 @@
1
+ export * from './did-functions';
2
+ export * from './types';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAA;AAC/B,cAAc,SAAS,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./did-functions"), exports);
18
+ __exportStar(require("./types"), exports);
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,kDAA+B;AAC/B,0CAAuB"}
@@ -0,0 +1,22 @@
1
+ import { JWTVerifyOptions } from 'did-jwt';
2
+ import { Resolvable } from 'did-resolver';
3
+ import { DIDDocumentSection, IIdentifier } from '@veramo/core';
4
+ export interface ResolveOpts {
5
+ jwtVerifyOpts?: JWTVerifyOptions;
6
+ resolver?: Resolvable;
7
+ resolveUrl?: string;
8
+ noUniversalResolverFallback?: boolean;
9
+ subjectSyntaxTypesSupported?: string[];
10
+ }
11
+ export interface IDIDOptions {
12
+ resolveOpts?: ResolveOpts;
13
+ identifierOpts: IIdentifierOpts;
14
+ supportedDIDMethods?: string[];
15
+ }
16
+ export interface IIdentifierOpts {
17
+ identifier: IIdentifier | string;
18
+ verificationMethodSection?: DIDDocumentSection;
19
+ kid?: string;
20
+ }
21
+ export declare const DID_PREFIX = "did:";
22
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AACzC,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAE9D,MAAM,WAAW,WAAW;IAC1B,aAAa,CAAC,EAAE,gBAAgB,CAAA;IAChC,QAAQ,CAAC,EAAE,UAAU,CAAA;IACrB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,2BAA2B,CAAC,EAAE,OAAO,CAAA;IACrC,2BAA2B,CAAC,EAAE,MAAM,EAAE,CAAA;CACvC;AAED,MAAM,WAAW,WAAW;IAC1B,WAAW,CAAC,EAAE,WAAW,CAAA;IACzB,cAAc,EAAE,eAAe,CAAA;IAC/B,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAA;CAC/B;AAED,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,WAAW,GAAG,MAAM,CAAA;IAChC,yBAAyB,CAAC,EAAE,kBAAkB,CAAA;IAC9C,GAAG,CAAC,EAAE,MAAM,CAAA;CACb;AAED,eAAO,MAAM,UAAU,SAAS,CAAA"}
package/dist/types.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DID_PREFIX = void 0;
4
+ exports.DID_PREFIX = 'did:';
5
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAwBa,QAAA,UAAU,GAAG,MAAM,CAAA"}
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@sphereon/ssi-sdk-ext.did-utils",
3
+ "description": "DID Utils",
4
+ "version": "0.10.2-next.20+fe74ec5",
5
+ "source": "src/index.ts",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsc --build",
10
+ "build:clean": "tsc --build --clean && tsc --build"
11
+ },
12
+ "dependencies": {
13
+ "@sphereon/did-uni-client": "^0.6.0",
14
+ "@sphereon/ssi-sdk-ext.key-utils": "0.10.2-next.20+fe74ec5",
15
+ "@veramo/core": "4.2.0",
16
+ "@veramo/utils": "4.2.0",
17
+ "did-jwt": "^6.11.6",
18
+ "did-resolver": "^4.1.0",
19
+ "elliptic": "^6.5.4",
20
+ "uint8arrays": "^3.1.1"
21
+ },
22
+ "files": [
23
+ "dist/**/*",
24
+ "src/**/*",
25
+ "plugin.schema.json",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "private": false,
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "repository": "git@github.com:Sphereon-OpenSource/ssi-sdk-crypto-extensions.git",
34
+ "author": "Sphereon <dev@sphereon.com>",
35
+ "license": "Apache-2.0",
36
+ "keywords": [],
37
+ "gitHead": "fe74ec598881102070db75141155719cc9df9812"
38
+ }
@@ -0,0 +1,250 @@
1
+ import { UniResolver } from '@sphereon/did-uni-client'
2
+ import { DIDDocument, DIDDocumentSection, DIDResolutionResult, IAgentContext, IDIDManager, IIdentifier, IKey, IResolver } from '@veramo/core'
3
+ import {
4
+ _ExtendedIKey,
5
+ _ExtendedVerificationMethod,
6
+ _NormalizedVerificationMethod,
7
+ extractPublicKeyHex,
8
+ isDefined,
9
+ mapIdentifierKeysToDoc,
10
+ resolveDidOrThrow,
11
+ } from '@veramo/utils'
12
+ import { DIDResolutionOptions, Resolvable, VerificationMethod } from 'did-resolver'
13
+ // @ts-ignore
14
+ import elliptic from 'elliptic'
15
+ import * as u8a from 'uint8arrays'
16
+ import { IDIDOptions, IIdentifierOpts } from './types'
17
+ import { hexKeyFromPEMBasedJwk } from '@sphereon/ssi-sdk-ext.key-utils'
18
+
19
+ export const getFirstKeyWithRelation = async (
20
+ identifier: IIdentifier,
21
+ context: IAgentContext<IResolver>,
22
+ vmRelationship?: DIDDocumentSection,
23
+ errorOnNotFound?: boolean
24
+ ): Promise<_ExtendedIKey | undefined> => {
25
+ const section = vmRelationship || 'verificationMethod' // search all VMs in case no relationship is provided
26
+ const matchedKeys = await mapIdentifierKeysToDocWithJwkSupport(identifier, section, context)
27
+ if (Array.isArray(matchedKeys) && matchedKeys.length > 0) {
28
+ return matchedKeys[0]
29
+ }
30
+ if (errorOnNotFound === true) {
31
+ throw new Error(`Could not find key with relationship ${section} in DID document for ${identifier.did}`)
32
+ }
33
+ return undefined
34
+ }
35
+
36
+ //TODO: Move to ssi-sdk/core and create PR upstream
37
+ /**
38
+ * Dereferences keys from DID document and normalizes them for easy comparison.
39
+ *
40
+ * When dereferencing keyAgreement keys, only Ed25519 and X25519 curves are supported.
41
+ * Other key types are omitted from the result and Ed25519 keys are converted to X25519
42
+ *
43
+ * @returns a Promise that resolves to the list of dereferenced keys.
44
+ *
45
+ * @beta This API may change without a BREAKING CHANGE notice.
46
+ */
47
+ export async function dereferenceDidKeysWithJwkSupport(
48
+ didDocument: DIDDocument,
49
+ section: DIDDocumentSection = 'keyAgreement',
50
+ context: IAgentContext<IResolver>
51
+ ): Promise<_NormalizedVerificationMethod[]> {
52
+ const convert = section === 'keyAgreement'
53
+ if (section === 'service') {
54
+ return []
55
+ }
56
+ return (
57
+ await Promise.all(
58
+ (didDocument[section] || []).map(async (key: string | VerificationMethod) => {
59
+ if (typeof key === 'string') {
60
+ try {
61
+ return (await context.agent.getDIDComponentById({
62
+ didDocument,
63
+ didUrl: key,
64
+ section,
65
+ })) as _ExtendedVerificationMethod
66
+ } catch (e) {
67
+ return null
68
+ }
69
+ } else {
70
+ return key as _ExtendedVerificationMethod
71
+ }
72
+ })
73
+ )
74
+ )
75
+ .filter(isDefined)
76
+ .map((key) => {
77
+ const hexKey = extractPublicKeyHexWithJwkSupport(key, convert)
78
+ const { publicKeyHex, publicKeyBase58, publicKeyBase64, publicKeyJwk, ...keyProps } = key
79
+ const newKey = { ...keyProps, publicKeyHex: hexKey }
80
+ if (convert && 'Ed25519VerificationKey2018' === newKey.type) {
81
+ newKey.type = 'X25519KeyAgreementKey2019'
82
+ }
83
+ return newKey
84
+ })
85
+ }
86
+
87
+ /**
88
+ * Converts the publicKey of a VerificationMethod to hex encoding (publicKeyHex)
89
+ *
90
+ * @param pk - the VerificationMethod to be converted
91
+ * @param convert - when this flag is set to true, Ed25519 keys are converted to their X25519 pairs
92
+ * @returns the hex encoding of the public key
93
+ *
94
+ * @beta This API may change without a BREAKING CHANGE notice.
95
+ */
96
+ export function extractPublicKeyHexWithJwkSupport(pk: _ExtendedVerificationMethod, convert = false): string {
97
+ if (pk.publicKeyJwk) {
98
+ if (pk.publicKeyJwk.kty === 'EC') {
99
+ const secp256 = new elliptic.ec(pk.publicKeyJwk.crv === 'secp256k1' ? 'secp256k1' : 'p256')
100
+ const prefix = pk.publicKeyJwk.crv === 'secp256k1' ? '04' : '03'
101
+ const x = u8a.fromString(pk.publicKeyJwk.x!, 'base64url')
102
+ const y = u8a.fromString(pk.publicKeyJwk.y!, 'base64url')
103
+ const hex = `${prefix}${u8a.toString(x, 'base16')}${u8a.toString(y, 'base16')}`
104
+ // We return directly as we don't want to convert the result back into Uint8Array and then convert again to hex as the elliptic lib already returns hex strings
105
+ return secp256.keyFromPublic(hex, 'hex').getPublic(true, 'hex')
106
+ } else if (pk.publicKeyJwk.crv === 'Ed25519') {
107
+ return u8a.toString(u8a.fromString(pk.publicKeyJwk.x!, 'base64url'), 'base16')
108
+ } else if (pk.publicKeyJwk.kty === 'RSA') {
109
+ return hexKeyFromPEMBasedJwk(pk.publicKeyJwk, 'public')
110
+ }
111
+ }
112
+ // delegate the other types to the original Veramo function
113
+ return extractPublicKeyHex(pk, convert)
114
+ }
115
+
116
+ /**
117
+ * Maps the keys of a locally managed {@link @veramo/core#IIdentifier | IIdentifier} to the corresponding
118
+ * {@link did-resolver#VerificationMethod | VerificationMethod} entries from the DID document.
119
+ *
120
+ * @param identifier - the identifier to be mapped
121
+ * @param section - the section of the DID document to be mapped (see
122
+ * {@link https://www.w3.org/TR/did-core/#verification-relationships | verification relationships}), but can also be
123
+ * `verificationMethod` to map all the keys.
124
+ * @param context - the veramo agent context, which must contain a {@link @veramo/core#IResolver | IResolver}
125
+ * implementation that can resolve the DID document of the identifier.
126
+ *
127
+ * @returns an array of mapped keys. The corresponding verification method is added to the `meta.verificationMethod`
128
+ * property of the key.
129
+ *
130
+ * @beta This API may change without a BREAKING CHANGE notice.
131
+ */
132
+ export async function mapIdentifierKeysToDocWithJwkSupport(
133
+ identifier: IIdentifier,
134
+ section: DIDDocumentSection = 'keyAgreement',
135
+ context: IAgentContext<IResolver>,
136
+ didDocument?: DIDDocument
137
+ ): Promise<_ExtendedIKey[]> {
138
+ const rsaDidWeb = identifier.keys && identifier.keys.length > 0 && identifier.keys[0].type === 'RSA' && didDocument
139
+ // We skip mapping in case the identifier is RSA and a did document is supplied.
140
+ const keys = rsaDidWeb ? [] : await mapIdentifierKeysToDoc(identifier, section, context)
141
+ const didDoc = didDocument ? didDocument : await resolveDidOrThrow(identifier.did, context)
142
+ // dereference all key agreement keys from DID document and normalize
143
+ const documentKeys: VerificationMethod[] = await dereferenceDidKeysWithJwkSupport(didDoc, section, context)
144
+
145
+ const localKeys = identifier.keys.filter(isDefined)
146
+ // finally map the didDocument keys to the identifier keys by comparing `publicKeyHex`
147
+ const extendedKeys: _ExtendedIKey[] = documentKeys
148
+ .map((verificationMethod) => {
149
+ /*if (verificationMethod.type !== 'JsonWebKey2020') {
150
+ return null
151
+ }*/
152
+ const localKey = localKeys.find((localKey) => localKey.publicKeyHex === verificationMethod.publicKeyHex)
153
+ if (localKey) {
154
+ const { meta, ...localProps } = localKey
155
+ return { ...localProps, meta: { ...meta, verificationMethod } }
156
+ } else {
157
+ return null
158
+ }
159
+ })
160
+ .filter(isDefined)
161
+
162
+ return keys.concat(extendedKeys)
163
+ }
164
+
165
+ export async function getAgentDIDMethods(context: IAgentContext<IDIDManager>) {
166
+ return (await context.agent.didManagerGetProviders()).map((provider) => provider.toLowerCase().replace('did:', ''))
167
+ }
168
+
169
+ export async function getIdentifier(identifierOpts: IIdentifierOpts, context: IAgentContext<IDIDManager>): Promise<IIdentifier> {
170
+ if (typeof identifierOpts.identifier === 'string') {
171
+ return context.agent.didManagerGet({ did: identifierOpts.identifier })
172
+ } else if (typeof identifierOpts.identifier === 'object') {
173
+ return identifierOpts.identifier
174
+ }
175
+ throw Error(`Cannot get agent identifier value from options`)
176
+ }
177
+
178
+ export function getDID(identifierOpts: IIdentifierOpts): string {
179
+ if (typeof identifierOpts.identifier === 'string') {
180
+ return identifierOpts.identifier
181
+ } else if (typeof identifierOpts.identifier === 'object') {
182
+ return identifierOpts.identifier.did
183
+ }
184
+ throw Error(`Cannot get DID from identifier value`)
185
+ }
186
+
187
+ export function toDID(identifier: string | IIdentifier | Partial<IIdentifier>): string {
188
+ if (typeof identifier === 'string') {
189
+ return identifier
190
+ }
191
+ if (identifier.did) {
192
+ return identifier.did
193
+ }
194
+ throw Error(`No DID value present in identifier`)
195
+ }
196
+
197
+ export function toDIDs(identifiers?: (string | IIdentifier | Partial<IIdentifier>)[]): string[] {
198
+ if (!identifiers) {
199
+ return []
200
+ }
201
+ return identifiers.map(toDID)
202
+ }
203
+
204
+ export async function getKey(
205
+ identifier: IIdentifier,
206
+ verificationMethodSection: DIDDocumentSection = 'authentication',
207
+ context: IAgentContext<IResolver>,
208
+ keyId?: string
209
+ ): Promise<IKey> {
210
+ const keys = await mapIdentifierKeysToDocWithJwkSupport(identifier, verificationMethodSection, context)
211
+ if (!keys || keys.length === 0) {
212
+ throw new Error(`No keys found for verificationMethodSection: ${verificationMethodSection} and did ${identifier.did}`)
213
+ }
214
+
215
+ const identifierKey = keyId ? keys.find((key: _ExtendedIKey) => key.kid === keyId || key.meta.verificationMethod.id === keyId) : keys[0]
216
+ if (!identifierKey) {
217
+ throw new Error(`No matching verificationMethodSection key found for keyId: ${keyId}`)
218
+ }
219
+
220
+ return identifierKey
221
+ }
222
+
223
+ export function determineKid(key: IKey, idOpts: IIdentifierOpts): string {
224
+ return key.meta?.verificationMethod.id ?? idOpts.kid ?? key.kid
225
+ }
226
+
227
+ export async function getSupportedDIDMethods(didOpts: IDIDOptions, context: IAgentContext<IDIDManager>) {
228
+ return didOpts.supportedDIDMethods ?? (await getAgentDIDMethods(context))
229
+ }
230
+
231
+ export class AgentDIDResolver implements Resolvable {
232
+ private readonly context: IAgentContext<IResolver>
233
+ private readonly uniresolverFallback: boolean
234
+
235
+ constructor(context: IAgentContext<IResolver>, uniresolverFallback?: boolean) {
236
+ this.context = context
237
+ this.uniresolverFallback = uniresolverFallback === true
238
+ }
239
+
240
+ async resolve(didUrl: string, options?: DIDResolutionOptions): Promise<DIDResolutionResult> {
241
+ try {
242
+ return this.context.agent.resolveDid({ didUrl, options })
243
+ } catch (error: unknown) {
244
+ if (this.uniresolverFallback) {
245
+ return new UniResolver().resolve(didUrl, options)
246
+ }
247
+ throw error
248
+ }
249
+ }
250
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './did-functions'
2
+ export * from './types'
package/src/types.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { JWTVerifyOptions } from 'did-jwt'
2
+ import { Resolvable } from 'did-resolver'
3
+ import { DIDDocumentSection, IIdentifier } from '@veramo/core'
4
+
5
+ export interface ResolveOpts {
6
+ jwtVerifyOpts?: JWTVerifyOptions
7
+ resolver?: Resolvable
8
+ resolveUrl?: string
9
+ noUniversalResolverFallback?: boolean
10
+ subjectSyntaxTypesSupported?: string[]
11
+ }
12
+
13
+ export interface IDIDOptions {
14
+ resolveOpts?: ResolveOpts
15
+ identifierOpts: IIdentifierOpts
16
+ supportedDIDMethods?: string[]
17
+ }
18
+
19
+ export interface IIdentifierOpts {
20
+ identifier: IIdentifier | string
21
+ verificationMethodSection?: DIDDocumentSection
22
+ kid?: string
23
+ }
24
+
25
+ export const DID_PREFIX = 'did:'