@decryption/shamir 0.2.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 ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Constructive <developers@constructive.io>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,105 @@
1
+ # @decryption/shamir
2
+
3
+ Split a secret into `n` shares, any `t` of which reconstruct it. Fewer than `t` shares reveal
4
+ nothing but the secret's length.
5
+
6
+ ## Installation
7
+
8
+ ```bash
9
+ npm install @decryption/shamir
10
+ ```
11
+
12
+ ## Usage
13
+
14
+ ```typescript
15
+ import { splitToStrings, combineToString } from '@decryption/shamir';
16
+
17
+ const shares = splitToStrings(mnemonic, { shares: 5, threshold: 3 });
18
+ // [ "dcrypt-share.v1.RFNIUgEDAQ...", ... ]
19
+
20
+ const recovered = combineToString([shares[4], shares[0], shares[2]]); // any 3
21
+ ```
22
+
23
+ Binary API, for splitting arbitrary bytes:
24
+
25
+ ```typescript
26
+ import { split, combine, parseShare, verify } from '@decryption/shamir';
27
+
28
+ const shares = split(keyBytes, { shares: 3, threshold: 2 });
29
+ parseShare(shares[0]); // { version, threshold, index, group }
30
+ verify([shares[0], shares[1]]); // true
31
+ ```
32
+
33
+ ## Share format
34
+
35
+ ```text
36
+ | magic | ver | threshold | index | group id | digest | body |
37
+ | DSHR | 1 | u8 | u8 | 8 B | 8 B | n B |
38
+ ```
39
+
40
+ - **group id** — random per split. Combining shares from two different splits fails instead of
41
+ silently producing garbage.
42
+ - **digest** — truncated `SHA-256(group ‖ secret)`. The reconstructed secret is checked against it,
43
+ so a corrupted or forged share raises `ReconstructionError`. Because the group id is random and
44
+ independent of the secret, the digest tells an attacker holding fewer than `threshold` shares
45
+ nothing.
46
+ - **threshold** is recorded in the share, so `combine` can refuse to run with too few inputs
47
+ rather than returning plausible-looking nonsense.
48
+
49
+ ## Errors
50
+
51
+ | Error | Meaning |
52
+ |-------|---------|
53
+ | `InvalidShareError` | Malformed share, mixed groups, duplicate index, or too few shares |
54
+ | `ReconstructionError` | Enough shares, but the result failed its integrity check |
55
+ | `ShamirError` | Base class; invalid split parameters |
56
+
57
+ ## When to use it
58
+
59
+ Shamir is for **recovery**, not day-to-day sharing: use it to escrow a break-glass key across
60
+ several people or locations. For sharing team secrets that change membership, use
61
+ [`@decryption/secrets`](../secrets), which encrypts to each teammate's public key so recipients can
62
+ be added or removed without a new ceremony.
63
+
64
+ ## Note on timing
65
+
66
+ GF(256) multiplication uses log/exp tables, which are not constant time. Splitting and combining
67
+ run locally on data the caller already holds, never as a remote oracle, so this is not a
68
+ practical exposure.
69
+
70
+ ---
71
+
72
+ ## Development
73
+
74
+ ### Setup
75
+
76
+ 1. Clone the repository:
77
+
78
+ ```bash
79
+ git clone https://github.com/constructive-io/decryption.git
80
+ ```
81
+
82
+ 2. Install dependencies:
83
+
84
+ ```bash
85
+ cd decryption
86
+ pnpm install
87
+ pnpm build
88
+ ```
89
+
90
+ 3. Test the package of interest:
91
+
92
+ ```bash
93
+ cd packages/<packagename>
94
+ pnpm test:watch
95
+ ```
96
+
97
+ ## Credits
98
+
99
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
100
+
101
+ ## Disclaimer
102
+
103
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
104
+
105
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/esm/gf256.js ADDED
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Arithmetic in GF(2^8) with the AES reduction polynomial 0x11b, used for Shamir secret sharing.
3
+ *
4
+ * Multiplication goes through log/exp tables. Table lookups are not constant time; this is
5
+ * acceptable here because splitting and combining happen locally on data the caller already
6
+ * holds, never as a network-visible oracle.
7
+ */
8
+ const EXP = new Uint8Array(512);
9
+ const LOG = new Uint8Array(256);
10
+ {
11
+ let x = 1;
12
+ for (let i = 0; i < 255; i++) {
13
+ EXP[i] = x;
14
+ LOG[x] = i;
15
+ x ^= (x << 1) ^ (x & 0x80 ? 0x11b : 0);
16
+ x &= 0xff;
17
+ }
18
+ for (let i = 255; i < 512; i++)
19
+ EXP[i] = EXP[i - 255];
20
+ }
21
+ export const add = (a, b) => a ^ b;
22
+ export const mul = (a, b) => a === 0 || b === 0 ? 0 : EXP[LOG[a] + LOG[b]];
23
+ export const div = (a, b) => {
24
+ if (b === 0)
25
+ throw new Error('division by zero in GF(256)');
26
+ return a === 0 ? 0 : EXP[LOG[a] + 255 - LOG[b]];
27
+ };
28
+ /** Evaluates a polynomial (coefficients low-order first) at `x`, using Horner's method. */
29
+ export const evaluate = (coefficients, x) => {
30
+ let result = 0;
31
+ for (let i = coefficients.length - 1; i >= 0; i--)
32
+ result = add(mul(result, x), coefficients[i]);
33
+ return result;
34
+ };
35
+ /**
36
+ * Lagrange interpolation at x = 0 — recovers the constant term (the secret byte) from
37
+ * `(x, y)` pairs.
38
+ */
39
+ export const interpolateAtZero = (xs, ys) => {
40
+ let secret = 0;
41
+ for (let i = 0; i < xs.length; i++) {
42
+ let basis = 1;
43
+ for (let j = 0; j < xs.length; j++) {
44
+ if (i === j)
45
+ continue;
46
+ basis = mul(basis, div(xs[j], add(xs[i], xs[j])));
47
+ }
48
+ secret = add(secret, mul(ys[i], basis));
49
+ }
50
+ return secret;
51
+ };
package/esm/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './gf256';
2
+ export * from './shamir';
package/esm/shamir.js ADDED
@@ -0,0 +1,161 @@
1
+ import { base64 } from '@decryption/base';
2
+ import { sha256 } from '@decryption/hashes/sha2';
3
+ import { bytesToHex, concatBytes, randomBytes, utf8ToBytes } from '@decryption/hashes/utils';
4
+ import { evaluate, interpolateAtZero } from './gf256';
5
+ /** ASCII `DSHR`, the first four bytes of every share. */
6
+ export const MAGIC = utf8ToBytes('DSHR');
7
+ /** Share format version implemented by this package. */
8
+ export const VERSION = 1;
9
+ /** Prefix of the armored (text) share form. */
10
+ export const SHARE_PREFIX = 'dcrypt-share.v1.';
11
+ const GROUP_LENGTH = 8;
12
+ const DIGEST_LENGTH = 8;
13
+ const HEADER_LENGTH = MAGIC.length + 1 + 1 + 1 + GROUP_LENGTH + DIGEST_LENGTH;
14
+ export const MAX_SHARES = 255;
15
+ export class ShamirError extends Error {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = new.target.name;
19
+ }
20
+ }
21
+ /** A share is malformed, or does not belong to the group being combined. */
22
+ export class InvalidShareError extends ShamirError {
23
+ }
24
+ /** Enough shares were supplied, but the reconstructed secret failed its integrity check. */
25
+ export class ReconstructionError extends ShamirError {
26
+ }
27
+ /**
28
+ * Splits `secret` into `shares` pieces, any `threshold` of which reconstruct it. Fewer than
29
+ * `threshold` shares reveal nothing about the secret beyond its length.
30
+ *
31
+ * Every share carries a random group id and a keyed digest of the secret, so combining shares
32
+ * from different splits, or a corrupted share, fails loudly instead of returning garbage — the
33
+ * bug that made the old `secrets.js` flow dangerous.
34
+ */
35
+ export const split = (secret, options) => {
36
+ const bytes = typeof secret === 'string' ? utf8ToBytes(secret) : secret;
37
+ const { shares, threshold } = options;
38
+ if (!Number.isInteger(shares) || shares < 2 || shares > MAX_SHARES) {
39
+ throw new ShamirError(`shares must be an integer between 2 and ${MAX_SHARES}`);
40
+ }
41
+ if (!Number.isInteger(threshold) || threshold < 2 || threshold > shares) {
42
+ throw new ShamirError('threshold must be an integer between 2 and the number of shares');
43
+ }
44
+ if (bytes.length === 0)
45
+ throw new ShamirError('cannot split an empty secret');
46
+ const group = randomBytes(GROUP_LENGTH);
47
+ const digest = fingerprint(group, bytes);
48
+ const bodies = Array.from({ length: shares }, () => new Uint8Array(bytes.length));
49
+ const coefficients = new Uint8Array(threshold);
50
+ for (let byteIndex = 0; byteIndex < bytes.length; byteIndex++) {
51
+ coefficients.set(randomBytes(threshold - 1), 1);
52
+ coefficients[0] = bytes[byteIndex];
53
+ for (let shareIndex = 0; shareIndex < shares; shareIndex++) {
54
+ bodies[shareIndex][byteIndex] = evaluate(coefficients, shareIndex + 1);
55
+ }
56
+ }
57
+ coefficients.fill(0);
58
+ return bodies.map((body, i) => concatBytes(MAGIC, new Uint8Array([VERSION, threshold, i + 1]), group, digest, body));
59
+ };
60
+ /** Reads the non-secret metadata of a share. */
61
+ export const parseShare = (share) => {
62
+ if (share.length <= HEADER_LENGTH)
63
+ throw new InvalidShareError('share is truncated');
64
+ for (let i = 0; i < MAGIC.length; i++) {
65
+ if (share[i] !== MAGIC[i])
66
+ throw new InvalidShareError('not a dcrypt share');
67
+ }
68
+ const version = share[4];
69
+ if (version !== VERSION)
70
+ throw new InvalidShareError(`unsupported share version ${version}`);
71
+ const threshold = share[5];
72
+ const index = share[6];
73
+ if (threshold < 2)
74
+ throw new InvalidShareError('share declares an impossible threshold');
75
+ if (index < 1)
76
+ throw new InvalidShareError('share index must be 1-based');
77
+ return {
78
+ version,
79
+ threshold,
80
+ index,
81
+ group: share.slice(7, 7 + GROUP_LENGTH),
82
+ };
83
+ };
84
+ /**
85
+ * Reconstructs a secret from shares. Throws {@link InvalidShareError} when the shares are
86
+ * inconsistent (duplicates, mixed groups, too few) and {@link ReconstructionError} when the
87
+ * reconstructed bytes fail the integrity check.
88
+ */
89
+ export const combine = (shares) => {
90
+ const parsed = shares.map((share) => {
91
+ const bytes = typeof share === 'string' ? dearmorShare(share) : share;
92
+ return { info: parseShare(bytes), bytes };
93
+ });
94
+ if (parsed.length === 0)
95
+ throw new InvalidShareError('no shares supplied');
96
+ const [first] = parsed;
97
+ const group = first.info.group;
98
+ const bodyLength = first.bytes.length - HEADER_LENGTH;
99
+ for (const { info, bytes } of parsed) {
100
+ if (bytesToHex(info.group) !== bytesToHex(group)) {
101
+ throw new InvalidShareError('shares belong to different splits');
102
+ }
103
+ if (bytes.length - HEADER_LENGTH !== bodyLength) {
104
+ throw new InvalidShareError('shares have inconsistent lengths');
105
+ }
106
+ }
107
+ const indices = new Set(parsed.map((p) => p.info.index));
108
+ if (indices.size !== parsed.length)
109
+ throw new InvalidShareError('duplicate share supplied');
110
+ if (parsed.length < first.info.threshold) {
111
+ throw new InvalidShareError(`need at least ${first.info.threshold} shares, got ${parsed.length}`);
112
+ }
113
+ const xs = Uint8Array.from(parsed.map((p) => p.info.index));
114
+ const ys = new Uint8Array(parsed.length);
115
+ const secret = new Uint8Array(bodyLength);
116
+ for (let byteIndex = 0; byteIndex < bodyLength; byteIndex++) {
117
+ for (let i = 0; i < parsed.length; i++)
118
+ ys[i] = parsed[i].bytes[HEADER_LENGTH + byteIndex];
119
+ secret[byteIndex] = interpolateAtZero(xs, ys);
120
+ }
121
+ const expected = first.bytes.slice(7 + GROUP_LENGTH, HEADER_LENGTH);
122
+ if (bytesToHex(fingerprint(group, secret)) !== bytesToHex(expected)) {
123
+ throw new ReconstructionError('reconstructed secret failed its integrity check: one or more shares are corrupt');
124
+ }
125
+ return secret;
126
+ };
127
+ /** True when the shares reconstruct to a secret matching the fingerprint recorded at split time. */
128
+ export const verify = (shares) => {
129
+ try {
130
+ combine(shares);
131
+ return true;
132
+ }
133
+ catch {
134
+ return false;
135
+ }
136
+ };
137
+ /** Encodes a share as single-line text, safe to paste into a password manager. */
138
+ export const armorShare = (share) => SHARE_PREFIX + base64.encode(share);
139
+ /** Inverse of {@link armorShare}. */
140
+ export const dearmorShare = (text) => {
141
+ const trimmed = text.trim();
142
+ if (!trimmed.startsWith(SHARE_PREFIX)) {
143
+ throw new InvalidShareError(`armored share must start with "${SHARE_PREFIX}"`);
144
+ }
145
+ try {
146
+ return base64.decode(trimmed.slice(SHARE_PREFIX.length));
147
+ }
148
+ catch {
149
+ throw new InvalidShareError('armored share is not valid base64');
150
+ }
151
+ };
152
+ /** {@link split}, returning armored text shares. */
153
+ export const splitToStrings = (secret, options) => split(secret, options).map(armorShare);
154
+ /** {@link combine}, returning the secret as a UTF-8 string. */
155
+ export const combineToString = (shares) => new TextDecoder().decode(combine(shares));
156
+ /**
157
+ * Truncated SHA-256 over the random group id and the secret. Because the group id is random and
158
+ * never derived from the secret, the fingerprint is useless to anyone who does not already hold
159
+ * a share.
160
+ */
161
+ const fingerprint = (group, secret) => sha256(concatBytes(group, secret)).slice(0, DIGEST_LENGTH);
package/gf256.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Arithmetic in GF(2^8) with the AES reduction polynomial 0x11b, used for Shamir secret sharing.
3
+ *
4
+ * Multiplication goes through log/exp tables. Table lookups are not constant time; this is
5
+ * acceptable here because splitting and combining happen locally on data the caller already
6
+ * holds, never as a network-visible oracle.
7
+ */
8
+ export declare const add: (a: number, b: number) => number;
9
+ export declare const mul: (a: number, b: number) => number;
10
+ export declare const div: (a: number, b: number) => number;
11
+ /** Evaluates a polynomial (coefficients low-order first) at `x`, using Horner's method. */
12
+ export declare const evaluate: (coefficients: Uint8Array, x: number) => number;
13
+ /**
14
+ * Lagrange interpolation at x = 0 — recovers the constant term (the secret byte) from
15
+ * `(x, y)` pairs.
16
+ */
17
+ export declare const interpolateAtZero: (xs: Uint8Array, ys: Uint8Array) => number;
package/gf256.js ADDED
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ /**
3
+ * Arithmetic in GF(2^8) with the AES reduction polynomial 0x11b, used for Shamir secret sharing.
4
+ *
5
+ * Multiplication goes through log/exp tables. Table lookups are not constant time; this is
6
+ * acceptable here because splitting and combining happen locally on data the caller already
7
+ * holds, never as a network-visible oracle.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.interpolateAtZero = exports.evaluate = exports.div = exports.mul = exports.add = void 0;
11
+ const EXP = new Uint8Array(512);
12
+ const LOG = new Uint8Array(256);
13
+ {
14
+ let x = 1;
15
+ for (let i = 0; i < 255; i++) {
16
+ EXP[i] = x;
17
+ LOG[x] = i;
18
+ x ^= (x << 1) ^ (x & 0x80 ? 0x11b : 0);
19
+ x &= 0xff;
20
+ }
21
+ for (let i = 255; i < 512; i++)
22
+ EXP[i] = EXP[i - 255];
23
+ }
24
+ const add = (a, b) => a ^ b;
25
+ exports.add = add;
26
+ const mul = (a, b) => a === 0 || b === 0 ? 0 : EXP[LOG[a] + LOG[b]];
27
+ exports.mul = mul;
28
+ const div = (a, b) => {
29
+ if (b === 0)
30
+ throw new Error('division by zero in GF(256)');
31
+ return a === 0 ? 0 : EXP[LOG[a] + 255 - LOG[b]];
32
+ };
33
+ exports.div = div;
34
+ /** Evaluates a polynomial (coefficients low-order first) at `x`, using Horner's method. */
35
+ const evaluate = (coefficients, x) => {
36
+ let result = 0;
37
+ for (let i = coefficients.length - 1; i >= 0; i--)
38
+ result = (0, exports.add)((0, exports.mul)(result, x), coefficients[i]);
39
+ return result;
40
+ };
41
+ exports.evaluate = evaluate;
42
+ /**
43
+ * Lagrange interpolation at x = 0 — recovers the constant term (the secret byte) from
44
+ * `(x, y)` pairs.
45
+ */
46
+ const interpolateAtZero = (xs, ys) => {
47
+ let secret = 0;
48
+ for (let i = 0; i < xs.length; i++) {
49
+ let basis = 1;
50
+ for (let j = 0; j < xs.length; j++) {
51
+ if (i === j)
52
+ continue;
53
+ basis = (0, exports.mul)(basis, (0, exports.div)(xs[j], (0, exports.add)(xs[i], xs[j])));
54
+ }
55
+ secret = (0, exports.add)(secret, (0, exports.mul)(ys[i], basis));
56
+ }
57
+ return secret;
58
+ };
59
+ exports.interpolateAtZero = interpolateAtZero;
package/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './gf256';
2
+ export * from './shamir';
package/index.js ADDED
@@ -0,0 +1,18 @@
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("./gf256"), exports);
18
+ __exportStar(require("./shamir"), exports);
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@decryption/shamir",
3
+ "version": "0.2.0",
4
+ "description": "Shamir secret sharing over GF(256) with authenticated, versioned shares",
5
+ "author": "Constructive <developers@constructive.io>",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/constructive-io/decryption",
10
+ "license": "MIT",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/constructive-io/decryption"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/constructive-io/decryption/issues"
21
+ },
22
+ "scripts": {
23
+ "copy": "makage assets",
24
+ "clean": "makage clean",
25
+ "prepublishOnly": "npm run build",
26
+ "build": "makage build",
27
+ "lint": "eslint . --fix",
28
+ "test": "jest",
29
+ "test:watch": "jest --watch"
30
+ },
31
+ "keywords": [
32
+ "shamir",
33
+ "sss",
34
+ "secret-sharing",
35
+ "recovery",
36
+ "backup"
37
+ ],
38
+ "dependencies": {
39
+ "@decryption/base": "0.2.0",
40
+ "@decryption/hashes": "0.2.0"
41
+ },
42
+ "devDependencies": {
43
+ "makage": "0.3.0"
44
+ },
45
+ "gitHead": "8d85fbfdbb1d57da93e99904a03e6e8d8531d281"
46
+ }
package/shamir.d.ts ADDED
@@ -0,0 +1,58 @@
1
+ /** ASCII `DSHR`, the first four bytes of every share. */
2
+ export declare const MAGIC: Uint8Array<ArrayBufferLike> & Uint8Array<ArrayBuffer>;
3
+ /** Share format version implemented by this package. */
4
+ export declare const VERSION = 1;
5
+ /** Prefix of the armored (text) share form. */
6
+ export declare const SHARE_PREFIX = "dcrypt-share.v1.";
7
+ export declare const MAX_SHARES = 255;
8
+ export declare class ShamirError extends Error {
9
+ constructor(message: string);
10
+ }
11
+ /** A share is malformed, or does not belong to the group being combined. */
12
+ export declare class InvalidShareError extends ShamirError {
13
+ }
14
+ /** Enough shares were supplied, but the reconstructed secret failed its integrity check. */
15
+ export declare class ReconstructionError extends ShamirError {
16
+ }
17
+ export interface SplitOptions {
18
+ /** Total number of shares to produce (2–255). */
19
+ shares: number;
20
+ /** How many shares are required to reconstruct (2–`shares`). */
21
+ threshold: number;
22
+ }
23
+ /** Parsed metadata of a share — everything except the share body. */
24
+ export interface ShareInfo {
25
+ version: number;
26
+ threshold: number;
27
+ /** 1-based x-coordinate of this share. */
28
+ index: number;
29
+ /** Random per-split identifier; shares only combine with others from the same group. */
30
+ group: Uint8Array;
31
+ }
32
+ /**
33
+ * Splits `secret` into `shares` pieces, any `threshold` of which reconstruct it. Fewer than
34
+ * `threshold` shares reveal nothing about the secret beyond its length.
35
+ *
36
+ * Every share carries a random group id and a keyed digest of the secret, so combining shares
37
+ * from different splits, or a corrupted share, fails loudly instead of returning garbage — the
38
+ * bug that made the old `secrets.js` flow dangerous.
39
+ */
40
+ export declare const split: (secret: Uint8Array | string, options: SplitOptions) => Uint8Array[];
41
+ /** Reads the non-secret metadata of a share. */
42
+ export declare const parseShare: (share: Uint8Array) => ShareInfo;
43
+ /**
44
+ * Reconstructs a secret from shares. Throws {@link InvalidShareError} when the shares are
45
+ * inconsistent (duplicates, mixed groups, too few) and {@link ReconstructionError} when the
46
+ * reconstructed bytes fail the integrity check.
47
+ */
48
+ export declare const combine: (shares: (Uint8Array | string)[]) => Uint8Array;
49
+ /** True when the shares reconstruct to a secret matching the fingerprint recorded at split time. */
50
+ export declare const verify: (shares: (Uint8Array | string)[]) => boolean;
51
+ /** Encodes a share as single-line text, safe to paste into a password manager. */
52
+ export declare const armorShare: (share: Uint8Array) => string;
53
+ /** Inverse of {@link armorShare}. */
54
+ export declare const dearmorShare: (text: string) => Uint8Array;
55
+ /** {@link split}, returning armored text shares. */
56
+ export declare const splitToStrings: (secret: Uint8Array | string, options: SplitOptions) => string[];
57
+ /** {@link combine}, returning the secret as a UTF-8 string. */
58
+ export declare const combineToString: (shares: (Uint8Array | string)[]) => string;
package/shamir.js ADDED
@@ -0,0 +1,175 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.combineToString = exports.splitToStrings = exports.dearmorShare = exports.armorShare = exports.verify = exports.combine = exports.parseShare = exports.split = exports.ReconstructionError = exports.InvalidShareError = exports.ShamirError = exports.MAX_SHARES = exports.SHARE_PREFIX = exports.VERSION = exports.MAGIC = void 0;
4
+ const base_1 = require("@decryption/base");
5
+ const sha2_1 = require("@decryption/hashes/sha2");
6
+ const utils_1 = require("@decryption/hashes/utils");
7
+ const gf256_1 = require("./gf256");
8
+ /** ASCII `DSHR`, the first four bytes of every share. */
9
+ exports.MAGIC = (0, utils_1.utf8ToBytes)('DSHR');
10
+ /** Share format version implemented by this package. */
11
+ exports.VERSION = 1;
12
+ /** Prefix of the armored (text) share form. */
13
+ exports.SHARE_PREFIX = 'dcrypt-share.v1.';
14
+ const GROUP_LENGTH = 8;
15
+ const DIGEST_LENGTH = 8;
16
+ const HEADER_LENGTH = exports.MAGIC.length + 1 + 1 + 1 + GROUP_LENGTH + DIGEST_LENGTH;
17
+ exports.MAX_SHARES = 255;
18
+ class ShamirError extends Error {
19
+ constructor(message) {
20
+ super(message);
21
+ this.name = new.target.name;
22
+ }
23
+ }
24
+ exports.ShamirError = ShamirError;
25
+ /** A share is malformed, or does not belong to the group being combined. */
26
+ class InvalidShareError extends ShamirError {
27
+ }
28
+ exports.InvalidShareError = InvalidShareError;
29
+ /** Enough shares were supplied, but the reconstructed secret failed its integrity check. */
30
+ class ReconstructionError extends ShamirError {
31
+ }
32
+ exports.ReconstructionError = ReconstructionError;
33
+ /**
34
+ * Splits `secret` into `shares` pieces, any `threshold` of which reconstruct it. Fewer than
35
+ * `threshold` shares reveal nothing about the secret beyond its length.
36
+ *
37
+ * Every share carries a random group id and a keyed digest of the secret, so combining shares
38
+ * from different splits, or a corrupted share, fails loudly instead of returning garbage — the
39
+ * bug that made the old `secrets.js` flow dangerous.
40
+ */
41
+ const split = (secret, options) => {
42
+ const bytes = typeof secret === 'string' ? (0, utils_1.utf8ToBytes)(secret) : secret;
43
+ const { shares, threshold } = options;
44
+ if (!Number.isInteger(shares) || shares < 2 || shares > exports.MAX_SHARES) {
45
+ throw new ShamirError(`shares must be an integer between 2 and ${exports.MAX_SHARES}`);
46
+ }
47
+ if (!Number.isInteger(threshold) || threshold < 2 || threshold > shares) {
48
+ throw new ShamirError('threshold must be an integer between 2 and the number of shares');
49
+ }
50
+ if (bytes.length === 0)
51
+ throw new ShamirError('cannot split an empty secret');
52
+ const group = (0, utils_1.randomBytes)(GROUP_LENGTH);
53
+ const digest = fingerprint(group, bytes);
54
+ const bodies = Array.from({ length: shares }, () => new Uint8Array(bytes.length));
55
+ const coefficients = new Uint8Array(threshold);
56
+ for (let byteIndex = 0; byteIndex < bytes.length; byteIndex++) {
57
+ coefficients.set((0, utils_1.randomBytes)(threshold - 1), 1);
58
+ coefficients[0] = bytes[byteIndex];
59
+ for (let shareIndex = 0; shareIndex < shares; shareIndex++) {
60
+ bodies[shareIndex][byteIndex] = (0, gf256_1.evaluate)(coefficients, shareIndex + 1);
61
+ }
62
+ }
63
+ coefficients.fill(0);
64
+ return bodies.map((body, i) => (0, utils_1.concatBytes)(exports.MAGIC, new Uint8Array([exports.VERSION, threshold, i + 1]), group, digest, body));
65
+ };
66
+ exports.split = split;
67
+ /** Reads the non-secret metadata of a share. */
68
+ const parseShare = (share) => {
69
+ if (share.length <= HEADER_LENGTH)
70
+ throw new InvalidShareError('share is truncated');
71
+ for (let i = 0; i < exports.MAGIC.length; i++) {
72
+ if (share[i] !== exports.MAGIC[i])
73
+ throw new InvalidShareError('not a dcrypt share');
74
+ }
75
+ const version = share[4];
76
+ if (version !== exports.VERSION)
77
+ throw new InvalidShareError(`unsupported share version ${version}`);
78
+ const threshold = share[5];
79
+ const index = share[6];
80
+ if (threshold < 2)
81
+ throw new InvalidShareError('share declares an impossible threshold');
82
+ if (index < 1)
83
+ throw new InvalidShareError('share index must be 1-based');
84
+ return {
85
+ version,
86
+ threshold,
87
+ index,
88
+ group: share.slice(7, 7 + GROUP_LENGTH),
89
+ };
90
+ };
91
+ exports.parseShare = parseShare;
92
+ /**
93
+ * Reconstructs a secret from shares. Throws {@link InvalidShareError} when the shares are
94
+ * inconsistent (duplicates, mixed groups, too few) and {@link ReconstructionError} when the
95
+ * reconstructed bytes fail the integrity check.
96
+ */
97
+ const combine = (shares) => {
98
+ const parsed = shares.map((share) => {
99
+ const bytes = typeof share === 'string' ? (0, exports.dearmorShare)(share) : share;
100
+ return { info: (0, exports.parseShare)(bytes), bytes };
101
+ });
102
+ if (parsed.length === 0)
103
+ throw new InvalidShareError('no shares supplied');
104
+ const [first] = parsed;
105
+ const group = first.info.group;
106
+ const bodyLength = first.bytes.length - HEADER_LENGTH;
107
+ for (const { info, bytes } of parsed) {
108
+ if ((0, utils_1.bytesToHex)(info.group) !== (0, utils_1.bytesToHex)(group)) {
109
+ throw new InvalidShareError('shares belong to different splits');
110
+ }
111
+ if (bytes.length - HEADER_LENGTH !== bodyLength) {
112
+ throw new InvalidShareError('shares have inconsistent lengths');
113
+ }
114
+ }
115
+ const indices = new Set(parsed.map((p) => p.info.index));
116
+ if (indices.size !== parsed.length)
117
+ throw new InvalidShareError('duplicate share supplied');
118
+ if (parsed.length < first.info.threshold) {
119
+ throw new InvalidShareError(`need at least ${first.info.threshold} shares, got ${parsed.length}`);
120
+ }
121
+ const xs = Uint8Array.from(parsed.map((p) => p.info.index));
122
+ const ys = new Uint8Array(parsed.length);
123
+ const secret = new Uint8Array(bodyLength);
124
+ for (let byteIndex = 0; byteIndex < bodyLength; byteIndex++) {
125
+ for (let i = 0; i < parsed.length; i++)
126
+ ys[i] = parsed[i].bytes[HEADER_LENGTH + byteIndex];
127
+ secret[byteIndex] = (0, gf256_1.interpolateAtZero)(xs, ys);
128
+ }
129
+ const expected = first.bytes.slice(7 + GROUP_LENGTH, HEADER_LENGTH);
130
+ if ((0, utils_1.bytesToHex)(fingerprint(group, secret)) !== (0, utils_1.bytesToHex)(expected)) {
131
+ throw new ReconstructionError('reconstructed secret failed its integrity check: one or more shares are corrupt');
132
+ }
133
+ return secret;
134
+ };
135
+ exports.combine = combine;
136
+ /** True when the shares reconstruct to a secret matching the fingerprint recorded at split time. */
137
+ const verify = (shares) => {
138
+ try {
139
+ (0, exports.combine)(shares);
140
+ return true;
141
+ }
142
+ catch {
143
+ return false;
144
+ }
145
+ };
146
+ exports.verify = verify;
147
+ /** Encodes a share as single-line text, safe to paste into a password manager. */
148
+ const armorShare = (share) => exports.SHARE_PREFIX + base_1.base64.encode(share);
149
+ exports.armorShare = armorShare;
150
+ /** Inverse of {@link armorShare}. */
151
+ const dearmorShare = (text) => {
152
+ const trimmed = text.trim();
153
+ if (!trimmed.startsWith(exports.SHARE_PREFIX)) {
154
+ throw new InvalidShareError(`armored share must start with "${exports.SHARE_PREFIX}"`);
155
+ }
156
+ try {
157
+ return base_1.base64.decode(trimmed.slice(exports.SHARE_PREFIX.length));
158
+ }
159
+ catch {
160
+ throw new InvalidShareError('armored share is not valid base64');
161
+ }
162
+ };
163
+ exports.dearmorShare = dearmorShare;
164
+ /** {@link split}, returning armored text shares. */
165
+ const splitToStrings = (secret, options) => (0, exports.split)(secret, options).map(exports.armorShare);
166
+ exports.splitToStrings = splitToStrings;
167
+ /** {@link combine}, returning the secret as a UTF-8 string. */
168
+ const combineToString = (shares) => new TextDecoder().decode((0, exports.combine)(shares));
169
+ exports.combineToString = combineToString;
170
+ /**
171
+ * Truncated SHA-256 over the random group id and the secret. Because the group id is random and
172
+ * never derived from the secret, the fingerprint is useless to anyone who does not already hold
173
+ * a share.
174
+ */
175
+ const fingerprint = (group, secret) => (0, sha2_1.sha256)((0, utils_1.concatBytes)(group, secret)).slice(0, DIGEST_LENGTH);