@noy-db/shamir 0.8.0-pre.0
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 +202 -0
- package/NOTICE +1 -0
- package/README.md +35 -0
- package/dist/index.d.ts +139 -0
- package/dist/index.js +252 -0
- package/dist/index.js.map +1 -0
- package/package.json +53 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 vLannaAi
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
noy-db — Copyright 2026 vLannaAi
|
package/README.md
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# @noy-db/shamir
|
|
2
|
+
|
|
3
|
+
Shamir Secret Sharing over GF(2^8), byte-wise, plus the share codecs. **Pure math, zero
|
|
4
|
+
dependencies, no hub contract.**
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
import { splitSecret, combineSecret, encodeShareBase32, decodeShareBase32 } from '@noy-db/shamir'
|
|
8
|
+
|
|
9
|
+
const secret = crypto.getRandomValues(new Uint8Array(32))
|
|
10
|
+
const shares = splitSecret(secret, 2, 3).map(encodeShareBase32) // any 2 of 3 recombine
|
|
11
|
+
const back = combineSecret([decodeShareBase32(shares[0]!), decodeShareBase32(shares[2]!)])
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Where this sits
|
|
15
|
+
|
|
16
|
+
This is the primitive. The **unlock method** built on it — `shamirRecoveryProvider()` for
|
|
17
|
+
`createNoydb({ shamirRecovery })`, and `splitKEK` / `combineKEK` over a `CryptoKey` — is
|
|
18
|
+
`@noy-db/on-shamir`, in the `on-*` family. If you are enrolling Shamir recovery on a vault, install
|
|
19
|
+
that; if you are composing threshold sharing into something else, install this.
|
|
20
|
+
|
|
21
|
+
The split exists so hub's own recovery tests can exercise the real math without depending on a
|
|
22
|
+
package that implements hub's contract (a build cycle), and so `on-shamir` can import that contract
|
|
23
|
+
instead of mirroring it. Same posture as `@noy-db/attestation`.
|
|
24
|
+
|
|
25
|
+
## Threat model
|
|
26
|
+
|
|
27
|
+
Protects against up to K−1 colluding share holders (mathematically — fewer than K shares reveal
|
|
28
|
+
zero bits) and loss of up to N−K shares. Does not protect against K colluding holders (the
|
|
29
|
+
threshold contract) or compromise of the machine combining the shares.
|
|
30
|
+
|
|
31
|
+
## Share format
|
|
32
|
+
|
|
33
|
+
Base32 string: `SHAMIR_S<x>_K<k>N<n>__<base32 groups>`. Binary: 6-byte header (magic, x, k, n,
|
|
34
|
+
y-length) + y-bytes. JSON: `{ x, y: base64, k, n }`. All three round-trip; `decode*` throws on
|
|
35
|
+
malformed, truncated, or mismatched input.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Arithmetic in the Galois field GF(2^8), represented as bytes 0..255.
|
|
3
|
+
*
|
|
4
|
+
* Used by Shamir Secret Sharing for byte-wise polynomial operations.
|
|
5
|
+
* Addition is XOR; multiplication uses precomputed log/exp tables
|
|
6
|
+
* against the primitive element 0x03 with irreducible polynomial
|
|
7
|
+
* 0x11b (x^8 + x^4 + x^3 + x + 1 — the AES polynomial).
|
|
8
|
+
*
|
|
9
|
+
* Constant-time is NOT a goal here — for secret sharing, the threat
|
|
10
|
+
* model assumes the combining device is trusted during
|
|
11
|
+
* reconstruction. If that assumption is wrong, no library-level
|
|
12
|
+
* constant-time hedge protects the plaintext anyway.
|
|
13
|
+
*/
|
|
14
|
+
/** Addition in GF(2^8) is XOR. */
|
|
15
|
+
declare function gfAdd(a: number, b: number): number;
|
|
16
|
+
/** Multiplication in GF(2^8). Returns 0 if either operand is 0. */
|
|
17
|
+
declare function gfMul(a: number, b: number): number;
|
|
18
|
+
/** Multiplicative inverse in GF(2^8). Throws on 0 (no inverse exists). */
|
|
19
|
+
declare function gfInv(a: number): number;
|
|
20
|
+
/** Division in GF(2^8). Throws on divide-by-zero. */
|
|
21
|
+
declare function gfDiv(a: number, b: number): number;
|
|
22
|
+
/**
|
|
23
|
+
* Evaluate a polynomial with coefficients `coeffs[0] + coeffs[1]*x + ...`
|
|
24
|
+
* at point `x` in GF(2^8) via Horner's method.
|
|
25
|
+
*/
|
|
26
|
+
declare function gfPolyEval(coeffs: readonly number[], x: number): number;
|
|
27
|
+
/**
|
|
28
|
+
* Lagrange interpolation at x=0, given k distinct points `(xi, yi)`.
|
|
29
|
+
*
|
|
30
|
+
* Returns the constant term of the unique degree-(k-1) polynomial
|
|
31
|
+
* through those points — equal to the original secret byte for
|
|
32
|
+
* Shamir's construction.
|
|
33
|
+
*/
|
|
34
|
+
declare function lagrangeInterpolateAtZero(points: readonly [number, number][]): number;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Shamir Secret Sharing over GF(2^8), byte-wise.
|
|
38
|
+
*
|
|
39
|
+
* For each byte of the secret, construct a random polynomial of
|
|
40
|
+
* degree k-1 whose constant term is the byte. Each share is a value
|
|
41
|
+
* of that polynomial at a distinct x-coordinate in 1..255. Any K of
|
|
42
|
+
* the N shares recombines the original bytes via Lagrange interpolation
|
|
43
|
+
* at x=0.
|
|
44
|
+
*
|
|
45
|
+
* x=0 is reserved (it would directly reveal the secret). x-coordinates
|
|
46
|
+
* are chosen from 1..255 ensuring distinctness.
|
|
47
|
+
*/
|
|
48
|
+
/**
|
|
49
|
+
* Split a secret into N shares. Any K of them reconstructs the secret;
|
|
50
|
+
* fewer than K leaks zero bits.
|
|
51
|
+
*
|
|
52
|
+
* @param secret - The bytes to share (e.g., a 32-byte KEK).
|
|
53
|
+
* @param k - Threshold (min shares needed to reconstruct). Must be >= 2.
|
|
54
|
+
* @param n - Total shares to produce. Must be >= k and <= 255.
|
|
55
|
+
* @param randomBytes - RNG function returning N random bytes. Defaults to
|
|
56
|
+
* `crypto.getRandomValues`. Injectable for deterministic tests.
|
|
57
|
+
* @returns An array of `n` shares. Each share has an x-coordinate + y-bytes
|
|
58
|
+
* parallel to the secret bytes.
|
|
59
|
+
*/
|
|
60
|
+
declare function splitSecret(secret: Uint8Array, k: number, n: number, randomBytes?: (count: number) => Uint8Array): RawShare[];
|
|
61
|
+
/**
|
|
62
|
+
* Reconstruct a secret from K or more shares.
|
|
63
|
+
*
|
|
64
|
+
* Uses the first K shares provided; additional shares are ignored.
|
|
65
|
+
* Shares must agree on secret length and x-coordinates must be
|
|
66
|
+
* distinct (checked; throws on mismatch).
|
|
67
|
+
*/
|
|
68
|
+
declare function combineSecret(shares: readonly RawShare[]): Uint8Array;
|
|
69
|
+
/** A raw Shamir share before serialisation. */
|
|
70
|
+
interface RawShare {
|
|
71
|
+
/** x-coordinate in GF(2^8), 1..255. Zero is disallowed (it would reveal the secret). */
|
|
72
|
+
readonly x: number;
|
|
73
|
+
/** y-bytes — one per byte of the secret. */
|
|
74
|
+
readonly y: Uint8Array;
|
|
75
|
+
/** Threshold used at split time. */
|
|
76
|
+
readonly k: number;
|
|
77
|
+
/** Total shares at split time. */
|
|
78
|
+
readonly n: number;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Share serialisation — raw bytes, Base32 for printing, and JSON for
|
|
83
|
+
* structured transport (e.g. storing inside another on-* keyring).
|
|
84
|
+
*
|
|
85
|
+
* Binary layout (fixed header + secret-length y-bytes):
|
|
86
|
+
*
|
|
87
|
+
* ```
|
|
88
|
+
* offset size field
|
|
89
|
+
* 0 1 version (= 1)
|
|
90
|
+
* 1 1 x-coordinate (1..255)
|
|
91
|
+
* 2 1 k (threshold)
|
|
92
|
+
* 3 1 n (total)
|
|
93
|
+
* 4 2 byteLength (big-endian uint16) — should equal y-length
|
|
94
|
+
* 6+ L y-bytes (L = byteLength)
|
|
95
|
+
* ```
|
|
96
|
+
*
|
|
97
|
+
* Base32 adds a 26-character ULID `shareId` prefix + version/k/n
|
|
98
|
+
* metadata for human-readable diagnostics.
|
|
99
|
+
*/
|
|
100
|
+
|
|
101
|
+
/** Serialise a raw share into its canonical binary form. */
|
|
102
|
+
declare function encodeShareBytes(share: RawShare): Uint8Array;
|
|
103
|
+
/** Parse binary share bytes back into a structured share. */
|
|
104
|
+
declare function decodeShareBytes(bytes: Uint8Array): RawShare;
|
|
105
|
+
/**
|
|
106
|
+
* Encode a share as a Base32 string with hyphenated groups of 4.
|
|
107
|
+
*
|
|
108
|
+
* Output format: `SHAMIR_S{x}_K{k}N{n}__<base32-groups-of-4>`
|
|
109
|
+
*
|
|
110
|
+
* The prefix is not fed into the decoder — it's for eye-readability at a
|
|
111
|
+
* glance (share-number / threshold / total). The `SHAMIR` tag + `_`
|
|
112
|
+
* separators are non-Base32 characters (Base32 alphabet is A-Z2-7
|
|
113
|
+
* only), so the decoder can strip everything up to and including the
|
|
114
|
+
* last `_` before the payload. The metadata is also encoded in the
|
|
115
|
+
* share bytes themselves; the prefix is redundant-but-useful.
|
|
116
|
+
*/
|
|
117
|
+
declare function encodeShareBase32(share: RawShare): string;
|
|
118
|
+
/**
|
|
119
|
+
* Parse a Base32 share string back into a structured share. Tolerates
|
|
120
|
+
* hyphens, whitespace, lowercase, and the optional prefix produced by
|
|
121
|
+
* `encodeShareBase32`. The metadata prefix is informational; actual
|
|
122
|
+
* share data comes from the binary bytes after the last `_`.
|
|
123
|
+
*/
|
|
124
|
+
declare function decodeShareBase32(input: string): RawShare;
|
|
125
|
+
/**
|
|
126
|
+
* JSON-friendly form for structured storage (e.g. stash inside another
|
|
127
|
+
* on-* keyring entry, or pass over `postMessage`).
|
|
128
|
+
*/
|
|
129
|
+
interface ShareJSON {
|
|
130
|
+
readonly v: 1;
|
|
131
|
+
readonly x: number;
|
|
132
|
+
readonly k: number;
|
|
133
|
+
readonly n: number;
|
|
134
|
+
readonly y: string;
|
|
135
|
+
}
|
|
136
|
+
declare function encodeShareJSON(share: RawShare): ShareJSON;
|
|
137
|
+
declare function decodeShareJSON(json: ShareJSON): RawShare;
|
|
138
|
+
|
|
139
|
+
export { type RawShare, type ShareJSON, combineSecret, decodeShareBase32, decodeShareBytes, decodeShareJSON, encodeShareBase32, encodeShareBytes, encodeShareJSON, gfAdd, gfDiv, gfInv, gfMul, gfPolyEval, lagrangeInterpolateAtZero, splitSecret };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
// src/gf256.ts
|
|
2
|
+
var LOG = new Uint8Array(256);
|
|
3
|
+
var EXP = new Uint8Array(256);
|
|
4
|
+
{
|
|
5
|
+
let x = 1;
|
|
6
|
+
for (let i = 0; i < 255; i++) {
|
|
7
|
+
EXP[i] = x;
|
|
8
|
+
LOG[x] = i;
|
|
9
|
+
let doubled = x << 1;
|
|
10
|
+
if (doubled & 256) doubled ^= 283;
|
|
11
|
+
x = (doubled ^ x) & 255;
|
|
12
|
+
}
|
|
13
|
+
EXP[255] = EXP[0];
|
|
14
|
+
}
|
|
15
|
+
function gfAdd(a, b) {
|
|
16
|
+
return (a ^ b) & 255;
|
|
17
|
+
}
|
|
18
|
+
function gfMul(a, b) {
|
|
19
|
+
if (a === 0 || b === 0) return 0;
|
|
20
|
+
const s = (LOG[a] + LOG[b]) % 255;
|
|
21
|
+
return EXP[s];
|
|
22
|
+
}
|
|
23
|
+
function gfInv(a) {
|
|
24
|
+
if (a === 0) throw new Error("gf256: no inverse for 0");
|
|
25
|
+
return EXP[(255 - LOG[a]) % 255];
|
|
26
|
+
}
|
|
27
|
+
function gfDiv(a, b) {
|
|
28
|
+
if (b === 0) throw new Error("gf256: division by zero");
|
|
29
|
+
if (a === 0) return 0;
|
|
30
|
+
const s = (LOG[a] + 255 - LOG[b]) % 255;
|
|
31
|
+
return EXP[s];
|
|
32
|
+
}
|
|
33
|
+
function gfPolyEval(coeffs, x) {
|
|
34
|
+
let y = 0;
|
|
35
|
+
for (let i = coeffs.length - 1; i >= 0; i--) {
|
|
36
|
+
y = gfAdd(gfMul(y, x), coeffs[i]);
|
|
37
|
+
}
|
|
38
|
+
return y;
|
|
39
|
+
}
|
|
40
|
+
function lagrangeInterpolateAtZero(points) {
|
|
41
|
+
let result = 0;
|
|
42
|
+
for (let i = 0; i < points.length; i++) {
|
|
43
|
+
const [xi, yi] = points[i];
|
|
44
|
+
let numerator = 1;
|
|
45
|
+
let denominator = 1;
|
|
46
|
+
for (let j = 0; j < points.length; j++) {
|
|
47
|
+
if (i === j) continue;
|
|
48
|
+
const [xj] = points[j];
|
|
49
|
+
numerator = gfMul(numerator, xj);
|
|
50
|
+
denominator = gfMul(denominator, gfAdd(xi, xj));
|
|
51
|
+
}
|
|
52
|
+
const basis = gfDiv(numerator, denominator);
|
|
53
|
+
result = gfAdd(result, gfMul(yi, basis));
|
|
54
|
+
}
|
|
55
|
+
return result;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// src/shamir.ts
|
|
59
|
+
function splitSecret(secret, k, n, randomBytes = defaultRandomBytes) {
|
|
60
|
+
assertSplitArgs(k, n, secret.length);
|
|
61
|
+
const xCoords = pickXCoords(n);
|
|
62
|
+
const shares = xCoords.map((x) => ({
|
|
63
|
+
x,
|
|
64
|
+
y: new Uint8Array(secret.length),
|
|
65
|
+
k,
|
|
66
|
+
n
|
|
67
|
+
}));
|
|
68
|
+
for (let byteIdx = 0; byteIdx < secret.length; byteIdx++) {
|
|
69
|
+
const coeffs = [secret[byteIdx]];
|
|
70
|
+
const rand = randomBytes(k - 1);
|
|
71
|
+
for (let j = 0; j < k - 1; j++) {
|
|
72
|
+
coeffs.push(rand[j]);
|
|
73
|
+
}
|
|
74
|
+
for (let shareIdx = 0; shareIdx < n; shareIdx++) {
|
|
75
|
+
shares[shareIdx].y[byteIdx] = gfPolyEval(coeffs, xCoords[shareIdx]);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return shares;
|
|
79
|
+
}
|
|
80
|
+
function combineSecret(shares) {
|
|
81
|
+
if (shares.length === 0) {
|
|
82
|
+
throw new Error("shamir: no shares provided");
|
|
83
|
+
}
|
|
84
|
+
const k = shares[0].k;
|
|
85
|
+
if (shares.length < k) {
|
|
86
|
+
throw new Error(`shamir: insufficient shares \u2014 need ${k}, got ${shares.length}`);
|
|
87
|
+
}
|
|
88
|
+
const byteLength = shares[0].y.length;
|
|
89
|
+
for (const s of shares) {
|
|
90
|
+
if (s.y.length !== byteLength) {
|
|
91
|
+
throw new Error("shamir: share lengths disagree \u2014 incompatible enrollment");
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const selected = shares.slice(0, k);
|
|
95
|
+
const xs = selected.map((s) => s.x);
|
|
96
|
+
if (new Set(xs).size !== xs.length) {
|
|
97
|
+
throw new Error("shamir: duplicate x-coordinates among provided shares");
|
|
98
|
+
}
|
|
99
|
+
const secret = new Uint8Array(byteLength);
|
|
100
|
+
for (let byteIdx = 0; byteIdx < byteLength; byteIdx++) {
|
|
101
|
+
const points = selected.map((s) => [s.x, s.y[byteIdx]]);
|
|
102
|
+
secret[byteIdx] = lagrangeInterpolateAtZero(points);
|
|
103
|
+
}
|
|
104
|
+
return secret;
|
|
105
|
+
}
|
|
106
|
+
function assertSplitArgs(k, n, secretLen) {
|
|
107
|
+
if (!Number.isInteger(k) || k < 2) {
|
|
108
|
+
throw new Error(`shamir: k must be an integer >= 2 (got ${k})`);
|
|
109
|
+
}
|
|
110
|
+
if (!Number.isInteger(n) || n < k || n > 255) {
|
|
111
|
+
throw new Error(`shamir: n must satisfy k <= n <= 255 (got k=${k} n=${n})`);
|
|
112
|
+
}
|
|
113
|
+
if (!Number.isInteger(secretLen) || secretLen < 1) {
|
|
114
|
+
throw new Error(`shamir: secret must be at least 1 byte`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function pickXCoords(n) {
|
|
118
|
+
const result = [];
|
|
119
|
+
for (let i = 1; i <= n; i++) result.push(i);
|
|
120
|
+
return result;
|
|
121
|
+
}
|
|
122
|
+
function defaultRandomBytes(count) {
|
|
123
|
+
return crypto.getRandomValues(new Uint8Array(count));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// src/share-format.ts
|
|
127
|
+
var SHARE_VERSION = 1;
|
|
128
|
+
var HEADER_LEN = 6;
|
|
129
|
+
var BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
130
|
+
function encodeShareBytes(share) {
|
|
131
|
+
const bytes = new Uint8Array(HEADER_LEN + share.y.length);
|
|
132
|
+
bytes[0] = SHARE_VERSION;
|
|
133
|
+
bytes[1] = share.x;
|
|
134
|
+
bytes[2] = share.k;
|
|
135
|
+
bytes[3] = share.n;
|
|
136
|
+
bytes[4] = share.y.length >>> 8 & 255;
|
|
137
|
+
bytes[5] = share.y.length & 255;
|
|
138
|
+
bytes.set(share.y, HEADER_LEN);
|
|
139
|
+
return bytes;
|
|
140
|
+
}
|
|
141
|
+
function decodeShareBytes(bytes) {
|
|
142
|
+
if (bytes.length < HEADER_LEN) {
|
|
143
|
+
throw new Error(`shamir: share bytes too short (${bytes.length} < ${HEADER_LEN})`);
|
|
144
|
+
}
|
|
145
|
+
const version = bytes[0];
|
|
146
|
+
if (version !== SHARE_VERSION) {
|
|
147
|
+
throw new Error(`shamir: unsupported share version ${version} (expected ${SHARE_VERSION})`);
|
|
148
|
+
}
|
|
149
|
+
const x = bytes[1];
|
|
150
|
+
const k = bytes[2];
|
|
151
|
+
const n = bytes[3];
|
|
152
|
+
const byteLength = bytes[4] << 8 | bytes[5];
|
|
153
|
+
if (bytes.length !== HEADER_LEN + byteLength) {
|
|
154
|
+
throw new Error(`shamir: share length mismatch \u2014 header says ${byteLength}, got ${bytes.length - HEADER_LEN}`);
|
|
155
|
+
}
|
|
156
|
+
if (x === 0) {
|
|
157
|
+
throw new Error("shamir: share has x=0 \u2014 malformed");
|
|
158
|
+
}
|
|
159
|
+
return { x, k, n, y: bytes.slice(HEADER_LEN) };
|
|
160
|
+
}
|
|
161
|
+
function encodeShareBase32(share) {
|
|
162
|
+
const bytes = encodeShareBytes(share);
|
|
163
|
+
const chunks = base32Encode(bytes);
|
|
164
|
+
const grouped = chunks.match(/.{1,4}/g)?.join("-") ?? chunks;
|
|
165
|
+
return `SHAMIR_S${share.x}_K${share.k}N${share.n}__${grouped}`;
|
|
166
|
+
}
|
|
167
|
+
function decodeShareBase32(input) {
|
|
168
|
+
const normalised = input.toUpperCase().replace(/[\s-]/g, "");
|
|
169
|
+
const lastDoubleUnderscore = normalised.lastIndexOf("__");
|
|
170
|
+
const payload = lastDoubleUnderscore >= 0 ? normalised.slice(lastDoubleUnderscore + 2) : normalised;
|
|
171
|
+
const stripped = payload.replace(/[^A-Z2-7]/g, "");
|
|
172
|
+
const bytes = base32Decode(stripped);
|
|
173
|
+
return decodeShareBytes(bytes);
|
|
174
|
+
}
|
|
175
|
+
function encodeShareJSON(share) {
|
|
176
|
+
return {
|
|
177
|
+
v: SHARE_VERSION,
|
|
178
|
+
x: share.x,
|
|
179
|
+
k: share.k,
|
|
180
|
+
n: share.n,
|
|
181
|
+
y: base64Encode(share.y)
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
function decodeShareJSON(json) {
|
|
185
|
+
if (json.v !== SHARE_VERSION) {
|
|
186
|
+
throw new Error(`shamir: unsupported share version ${String(json.v)}`);
|
|
187
|
+
}
|
|
188
|
+
return { x: json.x, k: json.k, n: json.n, y: base64Decode(json.y) };
|
|
189
|
+
}
|
|
190
|
+
function base32Encode(bytes) {
|
|
191
|
+
let bits = 0;
|
|
192
|
+
let value = 0;
|
|
193
|
+
let out = "";
|
|
194
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
195
|
+
value = value << 8 | bytes[i];
|
|
196
|
+
bits += 8;
|
|
197
|
+
while (bits >= 5) {
|
|
198
|
+
bits -= 5;
|
|
199
|
+
out += BASE32_ALPHABET[value >>> bits & 31];
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
if (bits > 0) {
|
|
203
|
+
out += BASE32_ALPHABET[value << 5 - bits & 31];
|
|
204
|
+
}
|
|
205
|
+
return out;
|
|
206
|
+
}
|
|
207
|
+
function base32Decode(input) {
|
|
208
|
+
let bits = 0;
|
|
209
|
+
let value = 0;
|
|
210
|
+
const out = [];
|
|
211
|
+
for (const ch of input) {
|
|
212
|
+
const idx = BASE32_ALPHABET.indexOf(ch);
|
|
213
|
+
if (idx < 0) {
|
|
214
|
+
throw new Error(`shamir: invalid Base32 character "${ch}"`);
|
|
215
|
+
}
|
|
216
|
+
value = value << 5 | idx;
|
|
217
|
+
bits += 5;
|
|
218
|
+
if (bits >= 8) {
|
|
219
|
+
bits -= 8;
|
|
220
|
+
out.push(value >>> bits & 255);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return new Uint8Array(out);
|
|
224
|
+
}
|
|
225
|
+
function base64Encode(bytes) {
|
|
226
|
+
let s = "";
|
|
227
|
+
for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
|
|
228
|
+
return btoa(s);
|
|
229
|
+
}
|
|
230
|
+
function base64Decode(str) {
|
|
231
|
+
const s = atob(str);
|
|
232
|
+
const out = new Uint8Array(s.length);
|
|
233
|
+
for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
|
|
234
|
+
return out;
|
|
235
|
+
}
|
|
236
|
+
export {
|
|
237
|
+
combineSecret,
|
|
238
|
+
decodeShareBase32,
|
|
239
|
+
decodeShareBytes,
|
|
240
|
+
decodeShareJSON,
|
|
241
|
+
encodeShareBase32,
|
|
242
|
+
encodeShareBytes,
|
|
243
|
+
encodeShareJSON,
|
|
244
|
+
gfAdd,
|
|
245
|
+
gfDiv,
|
|
246
|
+
gfInv,
|
|
247
|
+
gfMul,
|
|
248
|
+
gfPolyEval,
|
|
249
|
+
lagrangeInterpolateAtZero,
|
|
250
|
+
splitSecret
|
|
251
|
+
};
|
|
252
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/gf256.ts","../src/shamir.ts","../src/share-format.ts"],"sourcesContent":["/**\n * Arithmetic in the Galois field GF(2^8), represented as bytes 0..255.\n *\n * Used by Shamir Secret Sharing for byte-wise polynomial operations.\n * Addition is XOR; multiplication uses precomputed log/exp tables\n * against the primitive element 0x03 with irreducible polynomial\n * 0x11b (x^8 + x^4 + x^3 + x + 1 — the AES polynomial).\n *\n * Constant-time is NOT a goal here — for secret sharing, the threat\n * model assumes the combining device is trusted during\n * reconstruction. If that assumption is wrong, no library-level\n * constant-time hedge protects the plaintext anyway.\n */\n\nconst LOG = new Uint8Array(256)\nconst EXP = new Uint8Array(256)\n\n// Build log/exp tables. Primitive element 0x03; reduction polynomial 0x11b.\n// Multiplication by 3 in GF(2^8) is (x << 1) ^ x, with polynomial reduction\n// when the shift carries bit 8.\n{\n let x = 1\n for (let i = 0; i < 255; i++) {\n EXP[i] = x\n LOG[x] = i\n // x <- x * 3 in GF(2^8)\n let doubled = x << 1\n if (doubled & 0x100) doubled ^= 0x11b\n x = (doubled ^ x) & 0xff\n }\n // EXP cycles with period 255 — EXP[255] = EXP[0] simplifies modulo math.\n EXP[255] = EXP[0]!\n // LOG[0] is undefined (log of 0 doesn't exist) — guarded at call sites.\n}\n\n/** Addition in GF(2^8) is XOR. */\nexport function gfAdd(a: number, b: number): number {\n return (a ^ b) & 0xff\n}\n\n/** Multiplication in GF(2^8). Returns 0 if either operand is 0. */\nexport function gfMul(a: number, b: number): number {\n if (a === 0 || b === 0) return 0\n const s = (LOG[a]! + LOG[b]!) % 255\n return EXP[s]!\n}\n\n/** Multiplicative inverse in GF(2^8). Throws on 0 (no inverse exists). */\nexport function gfInv(a: number): number {\n if (a === 0) throw new Error('gf256: no inverse for 0')\n return EXP[(255 - LOG[a]!) % 255]!\n}\n\n/** Division in GF(2^8). Throws on divide-by-zero. */\nexport function gfDiv(a: number, b: number): number {\n if (b === 0) throw new Error('gf256: division by zero')\n if (a === 0) return 0\n const s = (LOG[a]! + 255 - LOG[b]!) % 255\n return EXP[s]!\n}\n\n/**\n * Evaluate a polynomial with coefficients `coeffs[0] + coeffs[1]*x + ...`\n * at point `x` in GF(2^8) via Horner's method.\n */\nexport function gfPolyEval(coeffs: readonly number[], x: number): number {\n let y = 0\n for (let i = coeffs.length - 1; i >= 0; i--) {\n y = gfAdd(gfMul(y, x), coeffs[i]!)\n }\n return y\n}\n\n/**\n * Lagrange interpolation at x=0, given k distinct points `(xi, yi)`.\n *\n * Returns the constant term of the unique degree-(k-1) polynomial\n * through those points — equal to the original secret byte for\n * Shamir's construction.\n */\nexport function lagrangeInterpolateAtZero(points: readonly [number, number][]): number {\n let result = 0\n for (let i = 0; i < points.length; i++) {\n const [xi, yi] = points[i]!\n // Li(0) = ∏_{j≠i} xj / (xi XOR xj) (in GF(2^8), -x == x)\n let numerator = 1\n let denominator = 1\n for (let j = 0; j < points.length; j++) {\n if (i === j) continue\n const [xj] = points[j]!\n numerator = gfMul(numerator, xj)\n denominator = gfMul(denominator, gfAdd(xi, xj))\n }\n const basis = gfDiv(numerator, denominator)\n result = gfAdd(result, gfMul(yi, basis))\n }\n return result\n}\n","/**\n * Shamir Secret Sharing over GF(2^8), byte-wise.\n *\n * For each byte of the secret, construct a random polynomial of\n * degree k-1 whose constant term is the byte. Each share is a value\n * of that polynomial at a distinct x-coordinate in 1..255. Any K of\n * the N shares recombines the original bytes via Lagrange interpolation\n * at x=0.\n *\n * x=0 is reserved (it would directly reveal the secret). x-coordinates\n * are chosen from 1..255 ensuring distinctness.\n */\n\nimport { gfPolyEval, lagrangeInterpolateAtZero } from './gf256.js'\n\n/**\n * Split a secret into N shares. Any K of them reconstructs the secret;\n * fewer than K leaks zero bits.\n *\n * @param secret - The bytes to share (e.g., a 32-byte KEK).\n * @param k - Threshold (min shares needed to reconstruct). Must be >= 2.\n * @param n - Total shares to produce. Must be >= k and <= 255.\n * @param randomBytes - RNG function returning N random bytes. Defaults to\n * `crypto.getRandomValues`. Injectable for deterministic tests.\n * @returns An array of `n` shares. Each share has an x-coordinate + y-bytes\n * parallel to the secret bytes.\n */\nexport function splitSecret(\n secret: Uint8Array,\n k: number,\n n: number,\n randomBytes: (count: number) => Uint8Array = defaultRandomBytes,\n): RawShare[] {\n assertSplitArgs(k, n, secret.length)\n\n // Choose n distinct x-coordinates in 1..255.\n const xCoords = pickXCoords(n)\n\n // For each byte of the secret, build a polynomial of degree k-1 with\n // the byte as the constant term and random coefficients for x^1..x^(k-1).\n // Evaluate at each xCoord to get the share's y-byte for that position.\n const shares: RawShare[] = xCoords.map(x => ({\n x,\n y: new Uint8Array(secret.length),\n k,\n n,\n }))\n\n for (let byteIdx = 0; byteIdx < secret.length; byteIdx++) {\n const coeffs: number[] = [secret[byteIdx]!]\n const rand = randomBytes(k - 1)\n for (let j = 0; j < k - 1; j++) {\n coeffs.push(rand[j]!)\n }\n for (let shareIdx = 0; shareIdx < n; shareIdx++) {\n shares[shareIdx]!.y[byteIdx] = gfPolyEval(coeffs, xCoords[shareIdx]!)\n }\n }\n\n return shares\n}\n\n/**\n * Reconstruct a secret from K or more shares.\n *\n * Uses the first K shares provided; additional shares are ignored.\n * Shares must agree on secret length and x-coordinates must be\n * distinct (checked; throws on mismatch).\n */\nexport function combineSecret(shares: readonly RawShare[]): Uint8Array {\n if (shares.length === 0) {\n throw new Error('shamir: no shares provided')\n }\n const k = shares[0]!.k\n if (shares.length < k) {\n throw new Error(`shamir: insufficient shares — need ${k}, got ${shares.length}`)\n }\n const byteLength = shares[0]!.y.length\n for (const s of shares) {\n if (s.y.length !== byteLength) {\n throw new Error('shamir: share lengths disagree — incompatible enrollment')\n }\n }\n const selected = shares.slice(0, k)\n const xs = selected.map(s => s.x)\n if (new Set(xs).size !== xs.length) {\n throw new Error('shamir: duplicate x-coordinates among provided shares')\n }\n\n const secret = new Uint8Array(byteLength)\n for (let byteIdx = 0; byteIdx < byteLength; byteIdx++) {\n const points: [number, number][] = selected.map(s => [s.x, s.y[byteIdx]!])\n secret[byteIdx] = lagrangeInterpolateAtZero(points)\n }\n return secret\n}\n\n/** A raw Shamir share before serialisation. */\nexport interface RawShare {\n /** x-coordinate in GF(2^8), 1..255. Zero is disallowed (it would reveal the secret). */\n readonly x: number\n /** y-bytes — one per byte of the secret. */\n readonly y: Uint8Array\n /** Threshold used at split time. */\n readonly k: number\n /** Total shares at split time. */\n readonly n: number\n}\n\n// ── internals ──────────────────────────────────────────────────────────\n\nfunction assertSplitArgs(k: number, n: number, secretLen: number): void {\n if (!Number.isInteger(k) || k < 2) {\n throw new Error(`shamir: k must be an integer >= 2 (got ${k})`)\n }\n if (!Number.isInteger(n) || n < k || n > 255) {\n throw new Error(`shamir: n must satisfy k <= n <= 255 (got k=${k} n=${n})`)\n }\n if (!Number.isInteger(secretLen) || secretLen < 1) {\n throw new Error(`shamir: secret must be at least 1 byte`)\n }\n}\n\nfunction pickXCoords(n: number): number[] {\n // Use 1..n as x-coordinates. Simple, deterministic, well-distributed.\n // (For applications where share-position anonymity matters, shuffle at\n // serialisation time; the crypto doesn't care about the labels.)\n const result: number[] = []\n for (let i = 1; i <= n; i++) result.push(i)\n return result\n}\n\nfunction defaultRandomBytes(count: number): Uint8Array {\n return crypto.getRandomValues(new Uint8Array(count))\n}\n","/**\n * Share serialisation — raw bytes, Base32 for printing, and JSON for\n * structured transport (e.g. storing inside another on-* keyring).\n *\n * Binary layout (fixed header + secret-length y-bytes):\n *\n * ```\n * offset size field\n * 0 1 version (= 1)\n * 1 1 x-coordinate (1..255)\n * 2 1 k (threshold)\n * 3 1 n (total)\n * 4 2 byteLength (big-endian uint16) — should equal y-length\n * 6+ L y-bytes (L = byteLength)\n * ```\n *\n * Base32 adds a 26-character ULID `shareId` prefix + version/k/n\n * metadata for human-readable diagnostics.\n */\n\nimport type { RawShare } from './shamir.js'\n\nconst SHARE_VERSION = 1\nconst HEADER_LEN = 6\n\n// RFC 4648 Base32 alphabet — no confusing 0/1/8/O/I/L/B pairs.\nconst BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\n\n/** Serialise a raw share into its canonical binary form. */\nexport function encodeShareBytes(share: RawShare): Uint8Array {\n const bytes = new Uint8Array(HEADER_LEN + share.y.length)\n bytes[0] = SHARE_VERSION\n bytes[1] = share.x\n bytes[2] = share.k\n bytes[3] = share.n\n bytes[4] = (share.y.length >>> 8) & 0xff\n bytes[5] = share.y.length & 0xff\n bytes.set(share.y, HEADER_LEN)\n return bytes\n}\n\n/** Parse binary share bytes back into a structured share. */\nexport function decodeShareBytes(bytes: Uint8Array): RawShare {\n if (bytes.length < HEADER_LEN) {\n throw new Error(`shamir: share bytes too short (${bytes.length} < ${HEADER_LEN})`)\n }\n const version = bytes[0]!\n if (version !== SHARE_VERSION) {\n throw new Error(`shamir: unsupported share version ${version} (expected ${SHARE_VERSION})`)\n }\n const x = bytes[1]!\n const k = bytes[2]!\n const n = bytes[3]!\n const byteLength = (bytes[4]! << 8) | bytes[5]!\n if (bytes.length !== HEADER_LEN + byteLength) {\n throw new Error(`shamir: share length mismatch — header says ${byteLength}, got ${bytes.length - HEADER_LEN}`)\n }\n if (x === 0) {\n throw new Error('shamir: share has x=0 — malformed')\n }\n return { x, k, n, y: bytes.slice(HEADER_LEN) }\n}\n\n/**\n * Encode a share as a Base32 string with hyphenated groups of 4.\n *\n * Output format: `SHAMIR_S{x}_K{k}N{n}__<base32-groups-of-4>`\n *\n * The prefix is not fed into the decoder — it's for eye-readability at a\n * glance (share-number / threshold / total). The `SHAMIR` tag + `_`\n * separators are non-Base32 characters (Base32 alphabet is A-Z2-7\n * only), so the decoder can strip everything up to and including the\n * last `_` before the payload. The metadata is also encoded in the\n * share bytes themselves; the prefix is redundant-but-useful.\n */\nexport function encodeShareBase32(share: RawShare): string {\n const bytes = encodeShareBytes(share)\n const chunks = base32Encode(bytes)\n const grouped = chunks.match(/.{1,4}/g)?.join('-') ?? chunks\n return `SHAMIR_S${share.x}_K${share.k}N${share.n}__${grouped}`\n}\n\n/**\n * Parse a Base32 share string back into a structured share. Tolerates\n * hyphens, whitespace, lowercase, and the optional prefix produced by\n * `encodeShareBase32`. The metadata prefix is informational; actual\n * share data comes from the binary bytes after the last `_`.\n */\nexport function decodeShareBase32(input: string): RawShare {\n // Normalise first: uppercase + remove whitespace/hyphens. Keep `_`\n // and digits so we can locate the prefix separator.\n const normalised = input.toUpperCase().replace(/[\\s-]/g, '')\n\n // If an optional SHAMIR_..._ prefix is present, strip up to the last `__`.\n const lastDoubleUnderscore = normalised.lastIndexOf('__')\n const payload = lastDoubleUnderscore >= 0 ? normalised.slice(lastDoubleUnderscore + 2) : normalised\n\n // Remove any remaining non-Base32 characters (defensive — also handles\n // cases where prefix metadata leaked into the payload somehow).\n const stripped = payload.replace(/[^A-Z2-7]/g, '')\n const bytes = base32Decode(stripped)\n return decodeShareBytes(bytes)\n}\n\n/**\n * JSON-friendly form for structured storage (e.g. stash inside another\n * on-* keyring entry, or pass over `postMessage`).\n */\nexport interface ShareJSON {\n readonly v: 1\n readonly x: number\n readonly k: number\n readonly n: number\n readonly y: string // Base64\n}\n\nexport function encodeShareJSON(share: RawShare): ShareJSON {\n return {\n v: SHARE_VERSION,\n x: share.x,\n k: share.k,\n n: share.n,\n y: base64Encode(share.y),\n }\n}\n\nexport function decodeShareJSON(json: ShareJSON): RawShare {\n if (json.v !== SHARE_VERSION) {\n throw new Error(`shamir: unsupported share version ${String(json.v)}`)\n }\n return { x: json.x, k: json.k, n: json.n, y: base64Decode(json.y) }\n}\n\n// ── Base32 ─────────────────────────────────────────────────────────────\n\nfunction base32Encode(bytes: Uint8Array): string {\n let bits = 0\n let value = 0\n let out = ''\n for (let i = 0; i < bytes.length; i++) {\n value = (value << 8) | bytes[i]!\n bits += 8\n while (bits >= 5) {\n bits -= 5\n out += BASE32_ALPHABET[(value >>> bits) & 0x1f]\n }\n }\n if (bits > 0) {\n out += BASE32_ALPHABET[(value << (5 - bits)) & 0x1f]\n }\n return out\n}\n\nfunction base32Decode(input: string): Uint8Array {\n let bits = 0\n let value = 0\n const out: number[] = []\n for (const ch of input) {\n const idx = BASE32_ALPHABET.indexOf(ch)\n if (idx < 0) {\n throw new Error(`shamir: invalid Base32 character \"${ch}\"`)\n }\n value = (value << 5) | idx\n bits += 5\n if (bits >= 8) {\n bits -= 8\n out.push((value >>> bits) & 0xff)\n }\n }\n return new Uint8Array(out)\n}\n\n// ── Base64 ─────────────────────────────────────────────────────────────\n\nfunction base64Encode(bytes: Uint8Array): string {\n let s = ''\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]!)\n return btoa(s)\n}\n\nfunction base64Decode(str: string): Uint8Array {\n const s = atob(str)\n const out = new Uint8Array(s.length)\n for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i)\n return out\n}\n"],"mappings":";AAcA,IAAM,MAAM,IAAI,WAAW,GAAG;AAC9B,IAAM,MAAM,IAAI,WAAW,GAAG;AAK9B;AACE,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,KAAK,KAAK;AAC5B,QAAI,CAAC,IAAI;AACT,QAAI,CAAC,IAAI;AAET,QAAI,UAAU,KAAK;AACnB,QAAI,UAAU,IAAO,YAAW;AAChC,SAAK,UAAU,KAAK;AAAA,EACtB;AAEA,MAAI,GAAG,IAAI,IAAI,CAAC;AAElB;AAGO,SAAS,MAAM,GAAW,GAAmB;AAClD,UAAQ,IAAI,KAAK;AACnB;AAGO,SAAS,MAAM,GAAW,GAAmB;AAClD,MAAI,MAAM,KAAK,MAAM,EAAG,QAAO;AAC/B,QAAM,KAAK,IAAI,CAAC,IAAK,IAAI,CAAC,KAAM;AAChC,SAAO,IAAI,CAAC;AACd;AAGO,SAAS,MAAM,GAAmB;AACvC,MAAI,MAAM,EAAG,OAAM,IAAI,MAAM,yBAAyB;AACtD,SAAO,KAAK,MAAM,IAAI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ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@noy-db/shamir",
|
|
3
|
+
"version": "0.8.0-pre.0",
|
|
4
|
+
"description": "Shamir Secret Sharing over GF(2^8), byte-wise, plus the share codecs (bytes / base32 / JSON). Pure math, zero dependencies, no hub contract — the primitive @noy-db/on-shamir builds its unlock method on.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "vLannaAi <vicio@lanna.ai>",
|
|
7
|
+
"homepage": "https://github.com/noy-db/core/tree/main/packages/shamir#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/noy-db/core.git",
|
|
11
|
+
"directory": "packages/shamir"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/noy-db/core/issues"
|
|
15
|
+
},
|
|
16
|
+
"type": "module",
|
|
17
|
+
"sideEffects": false,
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"default": "./dist/index.js"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"module": "./dist/index.js",
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"files": [
|
|
27
|
+
"dist",
|
|
28
|
+
"README.md",
|
|
29
|
+
"LICENSE",
|
|
30
|
+
"NOTICE"
|
|
31
|
+
],
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=22.0.0"
|
|
34
|
+
},
|
|
35
|
+
"keywords": [
|
|
36
|
+
"noy-db",
|
|
37
|
+
"shamir",
|
|
38
|
+
"secret-sharing",
|
|
39
|
+
"k-of-n",
|
|
40
|
+
"threshold",
|
|
41
|
+
"gf256"
|
|
42
|
+
],
|
|
43
|
+
"publishConfig": {
|
|
44
|
+
"access": "public",
|
|
45
|
+
"tag": "latest"
|
|
46
|
+
},
|
|
47
|
+
"scripts": {
|
|
48
|
+
"build": "tsup",
|
|
49
|
+
"test": "vitest run",
|
|
50
|
+
"lint": "eslint src/",
|
|
51
|
+
"typecheck": "tsc --noEmit"
|
|
52
|
+
}
|
|
53
|
+
}
|