@frequency-chain/recovery-sdk 0.0.0-fe548b

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.
@@ -0,0 +1,7 @@
1
+ # CONTRIBUTING
2
+
3
+ For contributing guidelines see the [Project Liberty Contributing Guidelines](https://github.com/LibertyDSNP/meta/blob/main/CONTRIBUTING.md).
4
+
5
+ ## Running Tests
6
+ - `js/recovery-sdk` folder
7
+ - `npm run tests`
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 document.
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 2024 Frequency Network Foundation
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,80 @@
1
+ # Recovery SDK package
2
+
3
+ <!-- PROJECT SHIELDS -->
4
+ <!--
5
+ *** I'm using markdown "reference style" links for readability.
6
+ *** Reference links are enclosed in brackets [ ] instead of parentheses ( ).
7
+ *** See the bottom of this document for the declaration of the reference variables
8
+ *** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use.
9
+ *** https://www.markdownguide.org/basic-syntax/#reference-style-links
10
+ -->
11
+
12
+ [![Contributors][contributors-shield]][contributors-url]
13
+ [![Forks][forks-shield]][forks-url]
14
+ [![Stargazers][stars-shield]][stars-url]
15
+ [![Issues][issues-shield]][issues-url]
16
+ [![MIT License][license-shield]][license-url]
17
+ [![NPM @latest][npm-shield]][npm-url]
18
+ [![NPM @next][npm-next-shield]][npm-next-url]
19
+
20
+ # Recovery SDK for Frequency Recovery System
21
+
22
+ Support for generating and validating the hashes needed to use the Recovery System on Frequency.
23
+
24
+ <!-- GETTING STARTED -->
25
+
26
+ ## Getting Started
27
+
28
+ - `npm install @frequency-chain/recovery-sdk`
29
+
30
+ ### React Native
31
+
32
+ To use this with React Native, you will need to shim `crypto.getRandomValues`.
33
+ [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values) is suggested.
34
+
35
+ ## Usage
36
+
37
+ | Method | Description |
38
+ | --- | --- |
39
+ | `generateRecoverySecret` | Generates a new Recovery Secret, formatted for users |
40
+ | `getRecoveryCommitment` | Gets the Recovery Commitment for the given Recovery Secret and contact |
41
+ | `getIntermediaryHashes` | Gets the Intermediary Recovery Hashes for the Recovery Provider to use to recover |
42
+ | `getRecoveryCommitmentFromIntermediary` | Gets the Recovery Commitment from the Intermediary Recovery Hashes |
43
+
44
+ ## Upgrades and Matching Versions
45
+
46
+ `@frequency-chain/recovery-sdk` is versioned with Frequency and should work against any release version of a Frequency node that has a compatible recovery system.
47
+ If you are working against a development node that has changes in the recovery system, you should match the package version against the commit hash using `v0.0.0-[First 6 of the commit hash]`.
48
+
49
+ Changelog is maintained in the [releases for Frequency](https://github.com/frequency-chain/frequency/releases).
50
+
51
+
52
+ <!-- CONTRIBUTING -->
53
+
54
+ ## Contributing
55
+
56
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for more information.
57
+
58
+ <!-- LICENSE -->
59
+
60
+ ## License
61
+
62
+ Distributed under the Apache 2.0 License. See `LICENSE` for more information.
63
+
64
+ <!-- MARKDOWN LINKS & IMAGES -->
65
+ <!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
66
+
67
+ [contributors-shield]: https://img.shields.io/github/contributors/frequency-chain/frequency.svg?style=for-the-badge
68
+ [contributors-url]: https://github.com/frequency-chain/frequency/graphs/contributors
69
+ [forks-shield]: https://img.shields.io/github/forks/frequency-chain/frequency.svg?style=for-the-badge
70
+ [forks-url]: https://github.com/frequency-chain/frequency/network/members
71
+ [stars-shield]: https://img.shields.io/github/stars/frequency-chain/frequency.svg?style=for-the-badge
72
+ [stars-url]: https://github.com/frequency-chain/frequency/stargazers
73
+ [issues-shield]: https://img.shields.io/github/issues/frequency-chain/frequency.svg?style=for-the-badge
74
+ [issues-url]: https://github.com/frequency-chain/frequency/issues
75
+ [license-shield]: https://img.shields.io/github/license/frequency-chain/frequency.svg?style=for-the-badge
76
+ [license-url]: https://github.com/frequency-chain/frequency/blob/master/LICENSE
77
+ [npm-shield]: https://img.shields.io/npm/v/@frequency-chain/recovery-sdk?label=npm%20%40latest&style=for-the-badge
78
+ [npm-url]: https://www.npmjs.com/package/@frequency-chain/recovery-sdk
79
+ [npm-next-shield]: https://img.shields.io/npm/v/@frequency-chain/recovery-sdk/next?label=npm%20%40next&style=for-the-badge
80
+ [npm-next-url]: https://www.npmjs.com/package/@frequency-chain/recovery-sdk
package/cjs/index.js ADDED
@@ -0,0 +1,83 @@
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
+ exports.generateRecoverySecret = generateRecoverySecret;
18
+ exports.getIntermediaryHashes = getIntermediaryHashes;
19
+ exports.getRecoveryCommitment = getRecoveryCommitment;
20
+ exports.getRecoveryCommitmentFromIntermediary = getRecoveryCommitmentFromIntermediary;
21
+ const sha3_1 = require("@noble/hashes/sha3");
22
+ const utils_1 = require("@noble/hashes/utils");
23
+ const standardize_js_1 = require("./standardize.js");
24
+ __exportStar(require("./types.js"), exports);
25
+ /**
26
+ * Generates a new Recovery Secret for a user
27
+ *
28
+ * @returns A new recovery secret string formatted for user consumption
29
+ */
30
+ function generateRecoverySecret() {
31
+ const unformatted = (0, utils_1.bytesToHex)((0, utils_1.randomBytes)(32)).split('');
32
+ return [...Array(64 / 4)]
33
+ .map((_a) => unformatted.splice(0, 4).join(''))
34
+ .join('-')
35
+ .toUpperCase();
36
+ }
37
+ /**
38
+ * Gets the Intermediary Hashes `a` and `b` used to do the Recovery
39
+ *
40
+ * @param recoverySecret The string form of the Recovery Secret
41
+ * @param contactType Email = "0x00", Phone = "0x01"
42
+ * @param contact The raw contact string
43
+ * @returns { a: Hex String of H(s), b: H(s + sc) }
44
+ */
45
+ function getIntermediaryHashes(recoverySecret, contactType, contact) {
46
+ const { a, b } = getIntermediaryHashesAsUint8Array(recoverySecret, contactType, contact);
47
+ return {
48
+ a: `0x${(0, utils_1.bytesToHex)(a)}`,
49
+ b: `0x${(0, utils_1.bytesToHex)(b)}`,
50
+ };
51
+ }
52
+ function getIntermediaryHashesAsUint8Array(recoverySecret, contactType, contact) {
53
+ const s = (0, utils_1.hexToBytes)(recoverySecret.replaceAll('-', ''));
54
+ const contactStandard = (0, standardize_js_1.standardizeContact)(contactType, contact);
55
+ return {
56
+ a: (0, sha3_1.keccak_256)(s),
57
+ b: (0, sha3_1.keccak_256)((0, utils_1.concatBytes)(s, (0, utils_1.hexToBytes)(contactType.replace('0x', '')), (0, utils_1.utf8ToBytes)(contactStandard))),
58
+ };
59
+ }
60
+ /**
61
+ * Gets the Recovery Commitment that is stored on chain for the validation at time of recovery
62
+ *
63
+ * @param recoverySecret The string form of the Recovery Secret
64
+ * @param contactType Email = "0x00", Phone = "0x01"
65
+ * @param contact The raw contact string
66
+ * @returns the hex string of the Recovery Commitment
67
+ */
68
+ function getRecoveryCommitment(recoverySecret, contactType, contact) {
69
+ const { a, b } = getIntermediaryHashesAsUint8Array(recoverySecret, contactType, contact);
70
+ return `0x${(0, utils_1.bytesToHex)((0, sha3_1.keccak_256)((0, utils_1.concatBytes)(a, b)))}`;
71
+ }
72
+ /**
73
+ * Gets the Recovery Commitment that is stored on chain for the validation at time of recovery from the Intermediary Hashes
74
+ *
75
+ * @param aHash A hash, H(s)
76
+ * @param bHash B hash, H(s + c)
77
+ * @returns the hex string of the Recovery Commitment
78
+ */
79
+ function getRecoveryCommitmentFromIntermediary(aHash, bHash) {
80
+ const a = (0, utils_1.hexToBytes)(aHash.replace('0x', ''));
81
+ const b = (0, utils_1.hexToBytes)(bHash.replace('0x', ''));
82
+ return `0x${(0, utils_1.bytesToHex)((0, sha3_1.keccak_256)((0, utils_1.concatBytes)(a, b)))}`;
83
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.standardizeContact = standardizeContact;
4
+ const min_1 = require("libphonenumber-js/min");
5
+ const types_js_1 = require("./types.js");
6
+ // Via https://shramko.dev/snippets/is-email-valid-regex
7
+ function isValidEmail(email) {
8
+ // [RFC 5321] https://datatracker.ietf.org/doc/html/rfc5321
9
+ const MAX_EMAIL_LENGTH = 254;
10
+ const isInvalidInput = !email || email.length === 0 || email.length > MAX_EMAIL_LENGTH;
11
+ if (isInvalidInput)
12
+ return false;
13
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
14
+ return emailRegex.test(email);
15
+ }
16
+ /**
17
+ * Cleans up the email by lowercasing and removing periods in the username
18
+ * Does NOT validate the email
19
+ *
20
+ * @param email Raw email
21
+ * @returns standardized email string
22
+ */
23
+ function standardizeEmail(email) {
24
+ const cleanEmail = email.toLowerCase().trim();
25
+ if (!isValidEmail(cleanEmail))
26
+ throw new Error('Unable to parse email contact method');
27
+ return cleanEmail;
28
+ }
29
+ /**
30
+ * Parses and standardizes the phone number to the E.164 Standard
31
+ *
32
+ * @param phone Raw phone number. Assumed to be a US phone number if not complete
33
+ * @returns
34
+ */
35
+ function standardizePhone(phone) {
36
+ const parsed = (0, min_1.parsePhoneNumberFromString)(phone, 'US');
37
+ if (!parsed)
38
+ throw new Error('Unable to parse phone contact method');
39
+ return parsed.format('E.164');
40
+ }
41
+ /**
42
+ * Converts the contact into the standard form for hashing
43
+ *
44
+ * @param contactType Email = "0x00", Phone = "0x01"
45
+ * @param contact The raw contact string
46
+ * @returns The standardized string ready for conversion to utf8 bytes and hashed
47
+ */
48
+ function standardizeContact(contactType, contact) {
49
+ switch (contactType) {
50
+ case types_js_1.ContactType.EMAIL:
51
+ return standardizeEmail(contact);
52
+ case types_js_1.ContactType.PHONE:
53
+ return standardizePhone(contact);
54
+ }
55
+ }
package/cjs/types.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ContactType = void 0;
4
+ /**
5
+ * The contact types supported
6
+ */
7
+ var ContactType;
8
+ (function (ContactType) {
9
+ /**
10
+ * Email is standardized and utf8 encoded and appended after the type
11
+ */
12
+ ContactType["EMAIL"] = "0x00";
13
+ /**
14
+ * Phone is standardized as E.164 and utf8 encoded and appended after the type
15
+ */
16
+ ContactType["PHONE"] = "0x01";
17
+ })(ContactType || (exports.ContactType = ContactType = {}));
package/esm/index.js ADDED
@@ -0,0 +1,63 @@
1
+ import { keccak_256 } from '@noble/hashes/sha3';
2
+ import { bytesToHex, randomBytes, concatBytes, hexToBytes, utf8ToBytes } from '@noble/hashes/utils';
3
+ import { standardizeContact } from './standardize.js';
4
+ export * from './types.js';
5
+ /**
6
+ * Generates a new Recovery Secret for a user
7
+ *
8
+ * @returns A new recovery secret string formatted for user consumption
9
+ */
10
+ export function generateRecoverySecret() {
11
+ const unformatted = bytesToHex(randomBytes(32)).split('');
12
+ return [...Array(64 / 4)]
13
+ .map((_a) => unformatted.splice(0, 4).join(''))
14
+ .join('-')
15
+ .toUpperCase();
16
+ }
17
+ /**
18
+ * Gets the Intermediary Hashes `a` and `b` used to do the Recovery
19
+ *
20
+ * @param recoverySecret The string form of the Recovery Secret
21
+ * @param contactType Email = "0x00", Phone = "0x01"
22
+ * @param contact The raw contact string
23
+ * @returns { a: Hex String of H(s), b: H(s + sc) }
24
+ */
25
+ export function getIntermediaryHashes(recoverySecret, contactType, contact) {
26
+ const { a, b } = getIntermediaryHashesAsUint8Array(recoverySecret, contactType, contact);
27
+ return {
28
+ a: `0x${bytesToHex(a)}`,
29
+ b: `0x${bytesToHex(b)}`,
30
+ };
31
+ }
32
+ function getIntermediaryHashesAsUint8Array(recoverySecret, contactType, contact) {
33
+ const s = hexToBytes(recoverySecret.replaceAll('-', ''));
34
+ const contactStandard = standardizeContact(contactType, contact);
35
+ return {
36
+ a: keccak_256(s),
37
+ b: keccak_256(concatBytes(s, hexToBytes(contactType.replace('0x', '')), utf8ToBytes(contactStandard))),
38
+ };
39
+ }
40
+ /**
41
+ * Gets the Recovery Commitment that is stored on chain for the validation at time of recovery
42
+ *
43
+ * @param recoverySecret The string form of the Recovery Secret
44
+ * @param contactType Email = "0x00", Phone = "0x01"
45
+ * @param contact The raw contact string
46
+ * @returns the hex string of the Recovery Commitment
47
+ */
48
+ export function getRecoveryCommitment(recoverySecret, contactType, contact) {
49
+ const { a, b } = getIntermediaryHashesAsUint8Array(recoverySecret, contactType, contact);
50
+ return `0x${bytesToHex(keccak_256(concatBytes(a, b)))}`;
51
+ }
52
+ /**
53
+ * Gets the Recovery Commitment that is stored on chain for the validation at time of recovery from the Intermediary Hashes
54
+ *
55
+ * @param aHash A hash, H(s)
56
+ * @param bHash B hash, H(s + c)
57
+ * @returns the hex string of the Recovery Commitment
58
+ */
59
+ export function getRecoveryCommitmentFromIntermediary(aHash, bHash) {
60
+ const a = hexToBytes(aHash.replace('0x', ''));
61
+ const b = hexToBytes(bHash.replace('0x', ''));
62
+ return `0x${bytesToHex(keccak_256(concatBytes(a, b)))}`;
63
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,52 @@
1
+ import { parsePhoneNumberFromString } from 'libphonenumber-js/min';
2
+ import { ContactType } from './types.js';
3
+ // Via https://shramko.dev/snippets/is-email-valid-regex
4
+ function isValidEmail(email) {
5
+ // [RFC 5321] https://datatracker.ietf.org/doc/html/rfc5321
6
+ const MAX_EMAIL_LENGTH = 254;
7
+ const isInvalidInput = !email || email.length === 0 || email.length > MAX_EMAIL_LENGTH;
8
+ if (isInvalidInput)
9
+ return false;
10
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
11
+ return emailRegex.test(email);
12
+ }
13
+ /**
14
+ * Cleans up the email by lowercasing and removing periods in the username
15
+ * Does NOT validate the email
16
+ *
17
+ * @param email Raw email
18
+ * @returns standardized email string
19
+ */
20
+ function standardizeEmail(email) {
21
+ const cleanEmail = email.toLowerCase().trim();
22
+ if (!isValidEmail(cleanEmail))
23
+ throw new Error('Unable to parse email contact method');
24
+ return cleanEmail;
25
+ }
26
+ /**
27
+ * Parses and standardizes the phone number to the E.164 Standard
28
+ *
29
+ * @param phone Raw phone number. Assumed to be a US phone number if not complete
30
+ * @returns
31
+ */
32
+ function standardizePhone(phone) {
33
+ const parsed = parsePhoneNumberFromString(phone, 'US');
34
+ if (!parsed)
35
+ throw new Error('Unable to parse phone contact method');
36
+ return parsed.format('E.164');
37
+ }
38
+ /**
39
+ * Converts the contact into the standard form for hashing
40
+ *
41
+ * @param contactType Email = "0x00", Phone = "0x01"
42
+ * @param contact The raw contact string
43
+ * @returns The standardized string ready for conversion to utf8 bytes and hashed
44
+ */
45
+ export function standardizeContact(contactType, contact) {
46
+ switch (contactType) {
47
+ case ContactType.EMAIL:
48
+ return standardizeEmail(contact);
49
+ case ContactType.PHONE:
50
+ return standardizePhone(contact);
51
+ }
52
+ }
package/esm/types.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The contact types supported
3
+ */
4
+ export var ContactType;
5
+ (function (ContactType) {
6
+ /**
7
+ * Email is standardized and utf8 encoded and appended after the type
8
+ */
9
+ ContactType["EMAIL"] = "0x00";
10
+ /**
11
+ * Phone is standardized as E.164 and utf8 encoded and appended after the type
12
+ */
13
+ ContactType["PHONE"] = "0x01";
14
+ })(ContactType || (ContactType = {}));
package/index.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { ContactType, HexString } from './types.js';
2
+ export * from './types.js';
3
+ /**
4
+ * Generates a new Recovery Secret for a user
5
+ *
6
+ * @returns A new recovery secret string formatted for user consumption
7
+ */
8
+ export declare function generateRecoverySecret(): string;
9
+ /**
10
+ * Gets the Intermediary Hashes `a` and `b` used to do the Recovery
11
+ *
12
+ * @param recoverySecret The string form of the Recovery Secret
13
+ * @param contactType Email = "0x00", Phone = "0x01"
14
+ * @param contact The raw contact string
15
+ * @returns { a: Hex String of H(s), b: H(s + sc) }
16
+ */
17
+ export declare function getIntermediaryHashes(recoverySecret: string, contactType: ContactType, contact: string): {
18
+ a: HexString;
19
+ b: HexString;
20
+ };
21
+ /**
22
+ * Gets the Recovery Commitment that is stored on chain for the validation at time of recovery
23
+ *
24
+ * @param recoverySecret The string form of the Recovery Secret
25
+ * @param contactType Email = "0x00", Phone = "0x01"
26
+ * @param contact The raw contact string
27
+ * @returns the hex string of the Recovery Commitment
28
+ */
29
+ export declare function getRecoveryCommitment(recoverySecret: string, contactType: ContactType, contact: string): HexString;
30
+ /**
31
+ * Gets the Recovery Commitment that is stored on chain for the validation at time of recovery from the Intermediary Hashes
32
+ *
33
+ * @param aHash A hash, H(s)
34
+ * @param bHash B hash, H(s + c)
35
+ * @returns the hex string of the Recovery Commitment
36
+ */
37
+ export declare function getRecoveryCommitmentFromIntermediary(aHash: string, bHash: string): HexString;
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@frequency-chain/recovery-sdk",
3
+ "version": "0.0.0-fe548b",
4
+ "bugs": {
5
+ "url": "https://github.com/frequency-chain/frequency/issues"
6
+ },
7
+ "description": "Provides utilties for interacting with the Frequency Recovery System",
8
+ "main": "./cjs/index.js",
9
+ "type": "module",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/frequency-chain/frequency.git",
13
+ "directory": "js/recovery-sdk"
14
+ },
15
+ "author": "frequency-chain",
16
+ "license": "Apache-2.0",
17
+ "dependencies": {
18
+ "@noble/hashes": "^1.8.0",
19
+ "libphonenumber-js": "^1.12.9"
20
+ },
21
+ "module": "./esm/index.js",
22
+ "types": "index.d.ts",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./index.d.ts",
26
+ "require": "./cjs/index.js",
27
+ "import": "./esm/index.js",
28
+ "default": "./esm/index.js"
29
+ }
30
+ }
31
+ }
@@ -0,0 +1,9 @@
1
+ import { ContactType } from './types.js';
2
+ /**
3
+ * Converts the contact into the standard form for hashing
4
+ *
5
+ * @param contactType Email = "0x00", Phone = "0x01"
6
+ * @param contact The raw contact string
7
+ * @returns The standardized string ready for conversion to utf8 bytes and hashed
8
+ */
9
+ export declare function standardizeContact(contactType: ContactType, contact: string): string;
package/types.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The contact types supported
3
+ */
4
+ export declare enum ContactType {
5
+ /**
6
+ * Email is standardized and utf8 encoded and appended after the type
7
+ */
8
+ EMAIL = "0x00",
9
+ /**
10
+ * Phone is standardized as E.164 and utf8 encoded and appended after the type
11
+ */
12
+ PHONE = "0x01"
13
+ }
14
+ /**
15
+ * Identifies a 0x-prefixed base16 string
16
+ */
17
+ export type HexString = `0x${string}`;