@decryption/secrets 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 +21 -0
- package/README.md +131 -0
- package/esm/export.js +51 -0
- package/esm/index.js +4 -0
- package/esm/recovery.js +16 -0
- package/esm/serialize.js +51 -0
- package/esm/vault.js +153 -0
- package/export.d.ts +10 -0
- package/export.js +56 -0
- package/index.d.ts +4 -0
- package/index.js +20 -0
- package/package.json +50 -0
- package/recovery.d.ts +13 -0
- package/recovery.js +21 -0
- package/serialize.d.ts +8 -0
- package/serialize.js +56 -0
- package/vault.d.ts +66 -0
- package/vault.js +170 -0
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,131 @@
|
|
|
1
|
+
# @decryption/secrets
|
|
2
|
+
|
|
3
|
+
Team secrets in a file you can commit. Every value is encrypted individually, so a pull request
|
|
4
|
+
shows *which* secret changed without revealing any of them, and membership is managed by adding or
|
|
5
|
+
removing recipients rather than by resharing a passphrase.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @decryption/secrets
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
import {
|
|
17
|
+
createVault,
|
|
18
|
+
setValues,
|
|
19
|
+
getValue,
|
|
20
|
+
addRecipient,
|
|
21
|
+
exportValues,
|
|
22
|
+
serializeVault,
|
|
23
|
+
parseVault,
|
|
24
|
+
} from '@decryption/secrets';
|
|
25
|
+
|
|
26
|
+
let vault = createVault({
|
|
27
|
+
name: 'production',
|
|
28
|
+
recipients: [{ label: 'dan', recipient: 'dcrypt1…' }],
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
vault = setValues(vault, me, {
|
|
32
|
+
DATABASE_URL: 'postgres://…',
|
|
33
|
+
STRIPE_KEY: 'sk_live_…',
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
writeFileSync('secrets/production.json', serializeVault(vault));
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Reading, on another machine:
|
|
40
|
+
|
|
41
|
+
```typescript
|
|
42
|
+
const vault = parseVault(readFileSync('secrets/production.json', 'utf8'));
|
|
43
|
+
getValue(vault, me, 'DATABASE_URL');
|
|
44
|
+
writeFileSync('.env', exportValues(vault, me, 'dotenv'));
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Formats: `dotenv`, `shell` (`export FOO='…'`), `yaml`, `json`.
|
|
48
|
+
|
|
49
|
+
## Membership
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
vault = addRecipient(vault, me, { label: 'ada', recipient: 'dcrypt1…' });
|
|
53
|
+
vault = removeRecipient(vault, me, 'ada');
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Both **rekey the vault**: a fresh file key is generated and every value re-encrypted, so a new
|
|
57
|
+
recipient cannot read older copies of the file, and a removed one cannot read newer ones. Rotate
|
|
58
|
+
the underlying credentials too — anything a departing teammate already read is already read.
|
|
59
|
+
|
|
60
|
+
## File format
|
|
61
|
+
|
|
62
|
+
```json
|
|
63
|
+
{
|
|
64
|
+
"dcrypt": 1,
|
|
65
|
+
"name": "production",
|
|
66
|
+
"recipients": [{ "label": "dan", "recipient": "dcrypt1…" }],
|
|
67
|
+
"keys": [{ "recipient": "9f2c…", "ephemeral": "…", "wrapped": "…" }],
|
|
68
|
+
"values": {
|
|
69
|
+
"DATABASE_URL": "…base64…",
|
|
70
|
+
"STRIPE_KEY": "…base64…"
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
- One **file key** encrypts all values; `keys` holds one X25519 stanza per recipient
|
|
76
|
+
([`@decryption/keys`](../keys)).
|
|
77
|
+
- Each value is XChaCha20-Poly1305 with the secret's own name as associated data, so a ciphertext
|
|
78
|
+
copied to a different key fails to decrypt instead of silently succeeding.
|
|
79
|
+
- Recipients, stanzas and secret names are sorted, and the file ends with a newline — serializing
|
|
80
|
+
the same logical vault twice gives identical bytes, which keeps diffs minimal.
|
|
81
|
+
- Secret **names are not encrypted**. That is deliberate: it is what makes reviews useful. Do not
|
|
82
|
+
put sensitive information in a key name.
|
|
83
|
+
|
|
84
|
+
## Break-glass recovery
|
|
85
|
+
|
|
86
|
+
```typescript
|
|
87
|
+
import { splitRecoveryIdentity, recoverIdentity } from '@decryption/secrets';
|
|
88
|
+
|
|
89
|
+
const shares = splitRecoveryIdentity(breakGlass, { shares: 5, threshold: 3 });
|
|
90
|
+
const restored = recoverIdentity([shares[0], shares[3], shares[4]]);
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Add `breakGlass` to the vault as an ordinary recipient and give one share to each custodian.
|
|
94
|
+
Shamir is for this case only — see [`@decryption/shamir`](../shamir).
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## Development
|
|
99
|
+
|
|
100
|
+
### Setup
|
|
101
|
+
|
|
102
|
+
1. Clone the repository:
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
git clone https://github.com/constructive-io/decryption.git
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
2. Install dependencies:
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
cd decryption
|
|
112
|
+
pnpm install
|
|
113
|
+
pnpm build
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
3. Test the package of interest:
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
cd packages/<packagename>
|
|
120
|
+
pnpm test:watch
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## Credits
|
|
124
|
+
|
|
125
|
+
**🛠 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).**
|
|
126
|
+
|
|
127
|
+
## Disclaimer
|
|
128
|
+
|
|
129
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
130
|
+
|
|
131
|
+
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/export.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { getValues, VaultError } from './vault';
|
|
2
|
+
/** Renders the decrypted secrets in one of the shapes people actually consume. */
|
|
3
|
+
export const exportValues = (vault, identity, format = 'dotenv') => {
|
|
4
|
+
const values = getValues(vault, identity);
|
|
5
|
+
switch (format) {
|
|
6
|
+
case 'dotenv':
|
|
7
|
+
return render(values, (key, value) => `${key}=${quoteDotenv(value)}`);
|
|
8
|
+
case 'shell':
|
|
9
|
+
return render(values, (key, value) => `export ${key}=${quoteShell(value)}`);
|
|
10
|
+
case 'yaml':
|
|
11
|
+
return render(values, (key, value) => `${key}: ${quoteYaml(value)}`);
|
|
12
|
+
case 'json':
|
|
13
|
+
return JSON.stringify(values, null, 2) + '\n';
|
|
14
|
+
default:
|
|
15
|
+
throw new VaultError(`unknown export format: ${String(format)}`);
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Parses a `.env` file into secrets, so an existing project can be imported in one step.
|
|
20
|
+
* Comments, blank lines and a leading `export` are tolerated.
|
|
21
|
+
*/
|
|
22
|
+
export const parseDotenv = (text) => {
|
|
23
|
+
const values = {};
|
|
24
|
+
for (const rawLine of text.split('\n')) {
|
|
25
|
+
const line = rawLine.trim();
|
|
26
|
+
if (!line || line.startsWith('#'))
|
|
27
|
+
continue;
|
|
28
|
+
const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
|
|
29
|
+
if (!match)
|
|
30
|
+
continue;
|
|
31
|
+
values[match[1]] = unquote(match[2]);
|
|
32
|
+
}
|
|
33
|
+
return values;
|
|
34
|
+
};
|
|
35
|
+
const render = (values, line) => Object.entries(values)
|
|
36
|
+
.map(([key, value]) => line(key, value))
|
|
37
|
+
.join('\n') + '\n';
|
|
38
|
+
const unquote = (value) => {
|
|
39
|
+
const trimmed = value.trim();
|
|
40
|
+
if ((trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length > 1) ||
|
|
41
|
+
(trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length > 1)) {
|
|
42
|
+
const inner = trimmed.slice(1, -1);
|
|
43
|
+
return trimmed[0] === '"' ? inner.replace(/\\n/g, '\n').replace(/\\"/g, '"') : inner;
|
|
44
|
+
}
|
|
45
|
+
return trimmed;
|
|
46
|
+
};
|
|
47
|
+
const quoteDotenv = (value) => /^[A-Za-z0-9_./:@-]*$/.test(value)
|
|
48
|
+
? value
|
|
49
|
+
: `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n')}"`;
|
|
50
|
+
const quoteShell = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
|
|
51
|
+
const quoteYaml = (value) => JSON.stringify(value);
|
package/esm/index.js
ADDED
package/esm/recovery.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { identityFromPrivateKey } from '@decryption/keys';
|
|
2
|
+
import { combine, split } from '@decryption/shamir';
|
|
3
|
+
/**
|
|
4
|
+
* Break-glass recovery: split a recovery identity's private key into Shamir shares so that `t` of
|
|
5
|
+
* `n` custodians can restore access if the usual holders are unavailable.
|
|
6
|
+
*
|
|
7
|
+
* Add the recovery identity to the vault as an ordinary recipient (label it `break-glass`) and
|
|
8
|
+
* hand one share to each custodian. Shamir is deliberately *not* used for day-to-day membership —
|
|
9
|
+
* adding or removing a teammate should be a recipient change, not a new ceremony.
|
|
10
|
+
*/
|
|
11
|
+
export const splitRecoveryIdentity = (identity, options) => split(identity.privateKey, options);
|
|
12
|
+
/** Reassembles a recovery identity from its shares. */
|
|
13
|
+
export const recoverIdentity = (shares) => {
|
|
14
|
+
const privateKey = combine(shares);
|
|
15
|
+
return identityFromPrivateKey(privateKey);
|
|
16
|
+
};
|
package/esm/serialize.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { normalize, VAULT_VERSION, VaultError } from './vault';
|
|
2
|
+
/**
|
|
3
|
+
* Serializes a vault as deterministic, git-friendly JSON: sorted keys, one secret per line, and a
|
|
4
|
+
* trailing newline. The same logical vault always produces the same bytes.
|
|
5
|
+
*/
|
|
6
|
+
export const serializeVault = (vault) => JSON.stringify(normalize(vault), null, 2) + '\n';
|
|
7
|
+
/** Parses and validates a vault file. */
|
|
8
|
+
export const parseVault = (text) => {
|
|
9
|
+
let parsed;
|
|
10
|
+
try {
|
|
11
|
+
parsed = JSON.parse(text);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
throw new VaultError('vault file is not valid JSON');
|
|
15
|
+
}
|
|
16
|
+
if (!isRecord(parsed))
|
|
17
|
+
throw new VaultError('vault file must be a JSON object');
|
|
18
|
+
const version = parsed.dcrypt;
|
|
19
|
+
if (version !== VAULT_VERSION) {
|
|
20
|
+
throw new VaultError(`unsupported vault version ${String(version)}; this build understands ${VAULT_VERSION}`);
|
|
21
|
+
}
|
|
22
|
+
if (typeof parsed.name !== 'string')
|
|
23
|
+
throw new VaultError('vault is missing a name');
|
|
24
|
+
if (!Array.isArray(parsed.recipients) || parsed.recipients.length === 0) {
|
|
25
|
+
throw new VaultError('vault has no recipients');
|
|
26
|
+
}
|
|
27
|
+
if (!Array.isArray(parsed.keys) || parsed.keys.length === 0) {
|
|
28
|
+
throw new VaultError('vault has no wrapped keys');
|
|
29
|
+
}
|
|
30
|
+
if (!isRecord(parsed.values))
|
|
31
|
+
throw new VaultError('vault values must be an object');
|
|
32
|
+
for (const recipient of parsed.recipients) {
|
|
33
|
+
if (!isRecord(recipient) || typeof recipient.recipient !== 'string') {
|
|
34
|
+
throw new VaultError('malformed recipient entry');
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
for (const stanza of parsed.keys) {
|
|
38
|
+
if (!isRecord(stanza) ||
|
|
39
|
+
typeof stanza.recipient !== 'string' ||
|
|
40
|
+
typeof stanza.ephemeral !== 'string' ||
|
|
41
|
+
typeof stanza.wrapped !== 'string') {
|
|
42
|
+
throw new VaultError('malformed wrapped key entry');
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
for (const [key, value] of Object.entries(parsed.values)) {
|
|
46
|
+
if (typeof value !== 'string')
|
|
47
|
+
throw new VaultError(`secret "${key}" is not a string`);
|
|
48
|
+
}
|
|
49
|
+
return normalize(parsed);
|
|
50
|
+
};
|
|
51
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
package/esm/vault.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { base64 } from '@decryption/base';
|
|
2
|
+
import { openWithKey, sealWithKey } from '@decryption/core';
|
|
3
|
+
import { fingerprint, generateFileKey, recipientFromString, recipientToString, unwrapFileKey, wrapFileKey, } from '@decryption/keys';
|
|
4
|
+
/** File format version written by this package. */
|
|
5
|
+
export const VAULT_VERSION = 1;
|
|
6
|
+
export class VaultError extends Error {
|
|
7
|
+
constructor(message) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = new.target.name;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** Creates an empty vault readable by `recipients`. */
|
|
13
|
+
export const createVault = ({ name, recipients }) => {
|
|
14
|
+
if (recipients.length === 0)
|
|
15
|
+
throw new VaultError('a vault needs at least one recipient');
|
|
16
|
+
const fileKey = generateFileKey();
|
|
17
|
+
try {
|
|
18
|
+
return normalize({
|
|
19
|
+
dcrypt: VAULT_VERSION,
|
|
20
|
+
name,
|
|
21
|
+
recipients: recipients.map(validateRecipient),
|
|
22
|
+
keys: recipients.map((recipient) => wrapFileKey(fileKey, recipient.recipient)),
|
|
23
|
+
values: {},
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
finally {
|
|
27
|
+
fileKey.fill(0);
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Recovers the vault's file key. Callers must zero it when finished — prefer {@link getValue} and
|
|
32
|
+
* friends unless you are doing many operations at once.
|
|
33
|
+
*/
|
|
34
|
+
export const unlock = (vault, identity) => unwrapFileKey(vault.keys, identity);
|
|
35
|
+
/** Names of the secrets in the vault, sorted. Requires no key: names are not encrypted. */
|
|
36
|
+
export const listKeys = (vault) => Object.keys(vault.values).sort();
|
|
37
|
+
/** Decrypts one value. */
|
|
38
|
+
export const getValue = (vault, identity, key) => {
|
|
39
|
+
const fileKey = unlock(vault, identity);
|
|
40
|
+
try {
|
|
41
|
+
return decodeValue(vault, fileKey, key);
|
|
42
|
+
}
|
|
43
|
+
finally {
|
|
44
|
+
fileKey.fill(0);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
/** Decrypts every value into a plain object. */
|
|
48
|
+
export const getValues = (vault, identity) => {
|
|
49
|
+
const fileKey = unlock(vault, identity);
|
|
50
|
+
try {
|
|
51
|
+
return Object.fromEntries(listKeys(vault).map((key) => [key, decodeValue(vault, fileKey, key)]));
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
fileKey.fill(0);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
/** Returns a new vault with `key` set to `value`. The input vault is not modified. */
|
|
58
|
+
export const setValue = (vault, identity, key, value) => setValues(vault, identity, { [key]: value });
|
|
59
|
+
/** {@link setValue} for several secrets at once. */
|
|
60
|
+
export const setValues = (vault, identity, values) => {
|
|
61
|
+
const fileKey = unlock(vault, identity);
|
|
62
|
+
try {
|
|
63
|
+
const encrypted = Object.fromEntries(Object.entries(values).map(([key, value]) => [key, encodeValue(fileKey, key, value)]));
|
|
64
|
+
return normalize({ ...vault, values: { ...vault.values, ...encrypted } });
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
fileKey.fill(0);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
/** Returns a new vault without `key`. Removing a secret needs no decryption key. */
|
|
71
|
+
export const deleteValue = (vault, key) => {
|
|
72
|
+
if (!(key in vault.values))
|
|
73
|
+
throw new VaultError(`no such secret: ${key}`);
|
|
74
|
+
const values = { ...vault.values };
|
|
75
|
+
delete values[key];
|
|
76
|
+
return normalize({ ...vault, values });
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Adds a recipient. This rekeys the vault — a fresh file key is generated and every value is
|
|
80
|
+
* re-encrypted — so the new recipient cannot decrypt copies of the file from before they joined.
|
|
81
|
+
*/
|
|
82
|
+
export const addRecipient = (vault, identity, recipient) => {
|
|
83
|
+
validateRecipient(recipient);
|
|
84
|
+
if (vault.recipients.some((existing) => sameRecipient(existing, recipient))) {
|
|
85
|
+
throw new VaultError(`${recipient.recipient} is already a recipient`);
|
|
86
|
+
}
|
|
87
|
+
return rekey(vault, identity, [...vault.recipients, recipient]);
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Removes a recipient and rekeys. The removed teammate keeps whatever they already read — rotate
|
|
91
|
+
* the underlying secrets too — but cannot read anything written after this point.
|
|
92
|
+
*/
|
|
93
|
+
export const removeRecipient = (vault, identity, labelOrRecipient) => {
|
|
94
|
+
const remaining = vault.recipients.filter((existing) => existing.label !== labelOrRecipient && existing.recipient !== labelOrRecipient);
|
|
95
|
+
if (remaining.length === vault.recipients.length) {
|
|
96
|
+
throw new VaultError(`no such recipient: ${labelOrRecipient}`);
|
|
97
|
+
}
|
|
98
|
+
if (remaining.length === 0)
|
|
99
|
+
throw new VaultError('cannot remove the last recipient');
|
|
100
|
+
if (!remaining.some((r) => fingerprint(recipientFromString(r.recipient)) === fingerprint(identity.publicKey))) {
|
|
101
|
+
throw new VaultError('refusing to remove yourself: you would lose access to the vault');
|
|
102
|
+
}
|
|
103
|
+
return rekey(vault, identity, remaining);
|
|
104
|
+
};
|
|
105
|
+
/** Re-encrypts the vault under a brand new file key, keeping the same recipients. */
|
|
106
|
+
export const rotateFileKey = (vault, identity) => rekey(vault, identity, vault.recipients);
|
|
107
|
+
/** True when `identity` is one of the vault's recipients. */
|
|
108
|
+
export const canRead = (vault, identity) => {
|
|
109
|
+
const mine = fingerprint(identity.publicKey);
|
|
110
|
+
return vault.keys.some((stanza) => stanza.recipient === mine);
|
|
111
|
+
};
|
|
112
|
+
const rekey = (vault, identity, recipients) => {
|
|
113
|
+
const plaintext = getValues(vault, identity);
|
|
114
|
+
const fileKey = generateFileKey();
|
|
115
|
+
try {
|
|
116
|
+
return normalize({
|
|
117
|
+
...vault,
|
|
118
|
+
recipients: recipients.map(validateRecipient),
|
|
119
|
+
keys: recipients.map((recipient) => wrapFileKey(fileKey, recipient.recipient)),
|
|
120
|
+
values: Object.fromEntries(Object.entries(plaintext).map(([key, value]) => [key, encodeValue(fileKey, key, value)])),
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
fileKey.fill(0);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
/**
|
|
128
|
+
* Sorts recipients, stanzas and secret names so serializing the same logical vault twice produces
|
|
129
|
+
* the same file, byte for byte — the property that makes these files reviewable in git.
|
|
130
|
+
*/
|
|
131
|
+
export const normalize = (vault) => ({
|
|
132
|
+
dcrypt: vault.dcrypt,
|
|
133
|
+
name: vault.name,
|
|
134
|
+
recipients: [...vault.recipients].sort((a, b) => a.recipient.localeCompare(b.recipient)),
|
|
135
|
+
keys: [...vault.keys].sort((a, b) => a.recipient.localeCompare(b.recipient)),
|
|
136
|
+
values: Object.fromEntries(Object.entries(vault.values).sort(([a], [b]) => a.localeCompare(b))),
|
|
137
|
+
});
|
|
138
|
+
/** Values are bound to their own name, so moving a ciphertext to another key fails to decrypt. */
|
|
139
|
+
const encodeValue = (fileKey, key, value) => base64.encode(sealWithKey(fileKey, value, `dcrypt-secret:${key}`));
|
|
140
|
+
const decodeValue = (vault, fileKey, key) => {
|
|
141
|
+
const encoded = vault.values[key];
|
|
142
|
+
if (encoded === undefined)
|
|
143
|
+
throw new VaultError(`no such secret: ${key}`);
|
|
144
|
+
return new TextDecoder().decode(openWithKey(fileKey, base64.decode(encoded), `dcrypt-secret:${key}`));
|
|
145
|
+
};
|
|
146
|
+
const validateRecipient = (recipient) => {
|
|
147
|
+
if (!recipient.label.trim())
|
|
148
|
+
throw new VaultError('recipients need a label');
|
|
149
|
+
// throws if the recipient string is malformed
|
|
150
|
+
recipientToString(recipientFromString(recipient.recipient));
|
|
151
|
+
return recipient;
|
|
152
|
+
};
|
|
153
|
+
const sameRecipient = (a, b) => a.recipient === b.recipient;
|
package/export.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Identity } from '@decryption/keys';
|
|
2
|
+
import { Vault } from './vault';
|
|
3
|
+
export type ExportFormat = 'dotenv' | 'json' | 'yaml' | 'shell';
|
|
4
|
+
/** Renders the decrypted secrets in one of the shapes people actually consume. */
|
|
5
|
+
export declare const exportValues: (vault: Vault, identity: Identity, format?: ExportFormat) => string;
|
|
6
|
+
/**
|
|
7
|
+
* Parses a `.env` file into secrets, so an existing project can be imported in one step.
|
|
8
|
+
* Comments, blank lines and a leading `export` are tolerated.
|
|
9
|
+
*/
|
|
10
|
+
export declare const parseDotenv: (text: string) => Record<string, string>;
|
package/export.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseDotenv = exports.exportValues = void 0;
|
|
4
|
+
const vault_1 = require("./vault");
|
|
5
|
+
/** Renders the decrypted secrets in one of the shapes people actually consume. */
|
|
6
|
+
const exportValues = (vault, identity, format = 'dotenv') => {
|
|
7
|
+
const values = (0, vault_1.getValues)(vault, identity);
|
|
8
|
+
switch (format) {
|
|
9
|
+
case 'dotenv':
|
|
10
|
+
return render(values, (key, value) => `${key}=${quoteDotenv(value)}`);
|
|
11
|
+
case 'shell':
|
|
12
|
+
return render(values, (key, value) => `export ${key}=${quoteShell(value)}`);
|
|
13
|
+
case 'yaml':
|
|
14
|
+
return render(values, (key, value) => `${key}: ${quoteYaml(value)}`);
|
|
15
|
+
case 'json':
|
|
16
|
+
return JSON.stringify(values, null, 2) + '\n';
|
|
17
|
+
default:
|
|
18
|
+
throw new vault_1.VaultError(`unknown export format: ${String(format)}`);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
exports.exportValues = exportValues;
|
|
22
|
+
/**
|
|
23
|
+
* Parses a `.env` file into secrets, so an existing project can be imported in one step.
|
|
24
|
+
* Comments, blank lines and a leading `export` are tolerated.
|
|
25
|
+
*/
|
|
26
|
+
const parseDotenv = (text) => {
|
|
27
|
+
const values = {};
|
|
28
|
+
for (const rawLine of text.split('\n')) {
|
|
29
|
+
const line = rawLine.trim();
|
|
30
|
+
if (!line || line.startsWith('#'))
|
|
31
|
+
continue;
|
|
32
|
+
const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
|
|
33
|
+
if (!match)
|
|
34
|
+
continue;
|
|
35
|
+
values[match[1]] = unquote(match[2]);
|
|
36
|
+
}
|
|
37
|
+
return values;
|
|
38
|
+
};
|
|
39
|
+
exports.parseDotenv = parseDotenv;
|
|
40
|
+
const render = (values, line) => Object.entries(values)
|
|
41
|
+
.map(([key, value]) => line(key, value))
|
|
42
|
+
.join('\n') + '\n';
|
|
43
|
+
const unquote = (value) => {
|
|
44
|
+
const trimmed = value.trim();
|
|
45
|
+
if ((trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length > 1) ||
|
|
46
|
+
(trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length > 1)) {
|
|
47
|
+
const inner = trimmed.slice(1, -1);
|
|
48
|
+
return trimmed[0] === '"' ? inner.replace(/\\n/g, '\n').replace(/\\"/g, '"') : inner;
|
|
49
|
+
}
|
|
50
|
+
return trimmed;
|
|
51
|
+
};
|
|
52
|
+
const quoteDotenv = (value) => /^[A-Za-z0-9_./:@-]*$/.test(value)
|
|
53
|
+
? value
|
|
54
|
+
: `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n')}"`;
|
|
55
|
+
const quoteShell = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
|
|
56
|
+
const quoteYaml = (value) => JSON.stringify(value);
|
package/index.d.ts
ADDED
package/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
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("./export"), exports);
|
|
18
|
+
__exportStar(require("./recovery"), exports);
|
|
19
|
+
__exportStar(require("./serialize"), exports);
|
|
20
|
+
__exportStar(require("./vault"), exports);
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@decryption/secrets",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Team secrets files: per-value authenticated encryption, recipient management and .env export",
|
|
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
|
+
"secrets",
|
|
33
|
+
"dotenv",
|
|
34
|
+
"team",
|
|
35
|
+
"sops",
|
|
36
|
+
"age",
|
|
37
|
+
"vault",
|
|
38
|
+
"env"
|
|
39
|
+
],
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@decryption/base": "0.2.0",
|
|
42
|
+
"@decryption/core": "0.2.0",
|
|
43
|
+
"@decryption/keys": "0.2.0",
|
|
44
|
+
"@decryption/shamir": "0.2.0"
|
|
45
|
+
},
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"makage": "0.3.0"
|
|
48
|
+
},
|
|
49
|
+
"gitHead": "8d85fbfdbb1d57da93e99904a03e6e8d8531d281"
|
|
50
|
+
}
|
package/recovery.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Identity } from '@decryption/keys';
|
|
2
|
+
import { SplitOptions } from '@decryption/shamir';
|
|
3
|
+
/**
|
|
4
|
+
* Break-glass recovery: split a recovery identity's private key into Shamir shares so that `t` of
|
|
5
|
+
* `n` custodians can restore access if the usual holders are unavailable.
|
|
6
|
+
*
|
|
7
|
+
* Add the recovery identity to the vault as an ordinary recipient (label it `break-glass`) and
|
|
8
|
+
* hand one share to each custodian. Shamir is deliberately *not* used for day-to-day membership —
|
|
9
|
+
* adding or removing a teammate should be a recipient change, not a new ceremony.
|
|
10
|
+
*/
|
|
11
|
+
export declare const splitRecoveryIdentity: (identity: Identity, options: SplitOptions) => Uint8Array[];
|
|
12
|
+
/** Reassembles a recovery identity from its shares. */
|
|
13
|
+
export declare const recoverIdentity: (shares: (Uint8Array | string)[]) => Identity;
|
package/recovery.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.recoverIdentity = exports.splitRecoveryIdentity = void 0;
|
|
4
|
+
const keys_1 = require("@decryption/keys");
|
|
5
|
+
const shamir_1 = require("@decryption/shamir");
|
|
6
|
+
/**
|
|
7
|
+
* Break-glass recovery: split a recovery identity's private key into Shamir shares so that `t` of
|
|
8
|
+
* `n` custodians can restore access if the usual holders are unavailable.
|
|
9
|
+
*
|
|
10
|
+
* Add the recovery identity to the vault as an ordinary recipient (label it `break-glass`) and
|
|
11
|
+
* hand one share to each custodian. Shamir is deliberately *not* used for day-to-day membership —
|
|
12
|
+
* adding or removing a teammate should be a recipient change, not a new ceremony.
|
|
13
|
+
*/
|
|
14
|
+
const splitRecoveryIdentity = (identity, options) => (0, shamir_1.split)(identity.privateKey, options);
|
|
15
|
+
exports.splitRecoveryIdentity = splitRecoveryIdentity;
|
|
16
|
+
/** Reassembles a recovery identity from its shares. */
|
|
17
|
+
const recoverIdentity = (shares) => {
|
|
18
|
+
const privateKey = (0, shamir_1.combine)(shares);
|
|
19
|
+
return (0, keys_1.identityFromPrivateKey)(privateKey);
|
|
20
|
+
};
|
|
21
|
+
exports.recoverIdentity = recoverIdentity;
|
package/serialize.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Vault } from './vault';
|
|
2
|
+
/**
|
|
3
|
+
* Serializes a vault as deterministic, git-friendly JSON: sorted keys, one secret per line, and a
|
|
4
|
+
* trailing newline. The same logical vault always produces the same bytes.
|
|
5
|
+
*/
|
|
6
|
+
export declare const serializeVault: (vault: Vault) => string;
|
|
7
|
+
/** Parses and validates a vault file. */
|
|
8
|
+
export declare const parseVault: (text: string) => Vault;
|
package/serialize.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseVault = exports.serializeVault = void 0;
|
|
4
|
+
const vault_1 = require("./vault");
|
|
5
|
+
/**
|
|
6
|
+
* Serializes a vault as deterministic, git-friendly JSON: sorted keys, one secret per line, and a
|
|
7
|
+
* trailing newline. The same logical vault always produces the same bytes.
|
|
8
|
+
*/
|
|
9
|
+
const serializeVault = (vault) => JSON.stringify((0, vault_1.normalize)(vault), null, 2) + '\n';
|
|
10
|
+
exports.serializeVault = serializeVault;
|
|
11
|
+
/** Parses and validates a vault file. */
|
|
12
|
+
const parseVault = (text) => {
|
|
13
|
+
let parsed;
|
|
14
|
+
try {
|
|
15
|
+
parsed = JSON.parse(text);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
throw new vault_1.VaultError('vault file is not valid JSON');
|
|
19
|
+
}
|
|
20
|
+
if (!isRecord(parsed))
|
|
21
|
+
throw new vault_1.VaultError('vault file must be a JSON object');
|
|
22
|
+
const version = parsed.dcrypt;
|
|
23
|
+
if (version !== vault_1.VAULT_VERSION) {
|
|
24
|
+
throw new vault_1.VaultError(`unsupported vault version ${String(version)}; this build understands ${vault_1.VAULT_VERSION}`);
|
|
25
|
+
}
|
|
26
|
+
if (typeof parsed.name !== 'string')
|
|
27
|
+
throw new vault_1.VaultError('vault is missing a name');
|
|
28
|
+
if (!Array.isArray(parsed.recipients) || parsed.recipients.length === 0) {
|
|
29
|
+
throw new vault_1.VaultError('vault has no recipients');
|
|
30
|
+
}
|
|
31
|
+
if (!Array.isArray(parsed.keys) || parsed.keys.length === 0) {
|
|
32
|
+
throw new vault_1.VaultError('vault has no wrapped keys');
|
|
33
|
+
}
|
|
34
|
+
if (!isRecord(parsed.values))
|
|
35
|
+
throw new vault_1.VaultError('vault values must be an object');
|
|
36
|
+
for (const recipient of parsed.recipients) {
|
|
37
|
+
if (!isRecord(recipient) || typeof recipient.recipient !== 'string') {
|
|
38
|
+
throw new vault_1.VaultError('malformed recipient entry');
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
for (const stanza of parsed.keys) {
|
|
42
|
+
if (!isRecord(stanza) ||
|
|
43
|
+
typeof stanza.recipient !== 'string' ||
|
|
44
|
+
typeof stanza.ephemeral !== 'string' ||
|
|
45
|
+
typeof stanza.wrapped !== 'string') {
|
|
46
|
+
throw new vault_1.VaultError('malformed wrapped key entry');
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
for (const [key, value] of Object.entries(parsed.values)) {
|
|
50
|
+
if (typeof value !== 'string')
|
|
51
|
+
throw new vault_1.VaultError(`secret "${key}" is not a string`);
|
|
52
|
+
}
|
|
53
|
+
return (0, vault_1.normalize)(parsed);
|
|
54
|
+
};
|
|
55
|
+
exports.parseVault = parseVault;
|
|
56
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
package/vault.d.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { Identity, Stanza } from '@decryption/keys';
|
|
2
|
+
/** File format version written by this package. */
|
|
3
|
+
export declare const VAULT_VERSION = 1;
|
|
4
|
+
export declare class VaultError extends Error {
|
|
5
|
+
constructor(message: string);
|
|
6
|
+
}
|
|
7
|
+
/** A teammate (or machine) allowed to read the vault. */
|
|
8
|
+
export interface Recipient {
|
|
9
|
+
/** Human label — a name, an email, `ci`, `break-glass`. */
|
|
10
|
+
label: string;
|
|
11
|
+
/** `dcrypt1…` public recipient string. */
|
|
12
|
+
recipient: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* A team secrets file. One file key encrypts every value; each recipient gets a stanza wrapping
|
|
16
|
+
* that file key. Values are stored individually so a git diff shows *which* secret changed.
|
|
17
|
+
*/
|
|
18
|
+
export interface Vault {
|
|
19
|
+
dcrypt: number;
|
|
20
|
+
name: string;
|
|
21
|
+
recipients: Recipient[];
|
|
22
|
+
keys: Stanza[];
|
|
23
|
+
values: Record<string, string>;
|
|
24
|
+
}
|
|
25
|
+
export interface CreateVaultOptions {
|
|
26
|
+
name: string;
|
|
27
|
+
recipients: Recipient[];
|
|
28
|
+
}
|
|
29
|
+
/** Creates an empty vault readable by `recipients`. */
|
|
30
|
+
export declare const createVault: ({ name, recipients }: CreateVaultOptions) => Vault;
|
|
31
|
+
/**
|
|
32
|
+
* Recovers the vault's file key. Callers must zero it when finished — prefer {@link getValue} and
|
|
33
|
+
* friends unless you are doing many operations at once.
|
|
34
|
+
*/
|
|
35
|
+
export declare const unlock: (vault: Vault, identity: Identity) => Uint8Array;
|
|
36
|
+
/** Names of the secrets in the vault, sorted. Requires no key: names are not encrypted. */
|
|
37
|
+
export declare const listKeys: (vault: Vault) => string[];
|
|
38
|
+
/** Decrypts one value. */
|
|
39
|
+
export declare const getValue: (vault: Vault, identity: Identity, key: string) => string;
|
|
40
|
+
/** Decrypts every value into a plain object. */
|
|
41
|
+
export declare const getValues: (vault: Vault, identity: Identity) => Record<string, string>;
|
|
42
|
+
/** Returns a new vault with `key` set to `value`. The input vault is not modified. */
|
|
43
|
+
export declare const setValue: (vault: Vault, identity: Identity, key: string, value: string) => Vault;
|
|
44
|
+
/** {@link setValue} for several secrets at once. */
|
|
45
|
+
export declare const setValues: (vault: Vault, identity: Identity, values: Record<string, string>) => Vault;
|
|
46
|
+
/** Returns a new vault without `key`. Removing a secret needs no decryption key. */
|
|
47
|
+
export declare const deleteValue: (vault: Vault, key: string) => Vault;
|
|
48
|
+
/**
|
|
49
|
+
* Adds a recipient. This rekeys the vault — a fresh file key is generated and every value is
|
|
50
|
+
* re-encrypted — so the new recipient cannot decrypt copies of the file from before they joined.
|
|
51
|
+
*/
|
|
52
|
+
export declare const addRecipient: (vault: Vault, identity: Identity, recipient: Recipient) => Vault;
|
|
53
|
+
/**
|
|
54
|
+
* Removes a recipient and rekeys. The removed teammate keeps whatever they already read — rotate
|
|
55
|
+
* the underlying secrets too — but cannot read anything written after this point.
|
|
56
|
+
*/
|
|
57
|
+
export declare const removeRecipient: (vault: Vault, identity: Identity, labelOrRecipient: string) => Vault;
|
|
58
|
+
/** Re-encrypts the vault under a brand new file key, keeping the same recipients. */
|
|
59
|
+
export declare const rotateFileKey: (vault: Vault, identity: Identity) => Vault;
|
|
60
|
+
/** True when `identity` is one of the vault's recipients. */
|
|
61
|
+
export declare const canRead: (vault: Vault, identity: Identity) => boolean;
|
|
62
|
+
/**
|
|
63
|
+
* Sorts recipients, stanzas and secret names so serializing the same logical vault twice produces
|
|
64
|
+
* the same file, byte for byte — the property that makes these files reviewable in git.
|
|
65
|
+
*/
|
|
66
|
+
export declare const normalize: (vault: Vault) => Vault;
|
package/vault.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.normalize = exports.canRead = exports.rotateFileKey = exports.removeRecipient = exports.addRecipient = exports.deleteValue = exports.setValues = exports.setValue = exports.getValues = exports.getValue = exports.listKeys = exports.unlock = exports.createVault = exports.VaultError = exports.VAULT_VERSION = void 0;
|
|
4
|
+
const base_1 = require("@decryption/base");
|
|
5
|
+
const core_1 = require("@decryption/core");
|
|
6
|
+
const keys_1 = require("@decryption/keys");
|
|
7
|
+
/** File format version written by this package. */
|
|
8
|
+
exports.VAULT_VERSION = 1;
|
|
9
|
+
class VaultError extends Error {
|
|
10
|
+
constructor(message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = new.target.name;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
exports.VaultError = VaultError;
|
|
16
|
+
/** Creates an empty vault readable by `recipients`. */
|
|
17
|
+
const createVault = ({ name, recipients }) => {
|
|
18
|
+
if (recipients.length === 0)
|
|
19
|
+
throw new VaultError('a vault needs at least one recipient');
|
|
20
|
+
const fileKey = (0, keys_1.generateFileKey)();
|
|
21
|
+
try {
|
|
22
|
+
return (0, exports.normalize)({
|
|
23
|
+
dcrypt: exports.VAULT_VERSION,
|
|
24
|
+
name,
|
|
25
|
+
recipients: recipients.map(validateRecipient),
|
|
26
|
+
keys: recipients.map((recipient) => (0, keys_1.wrapFileKey)(fileKey, recipient.recipient)),
|
|
27
|
+
values: {},
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
finally {
|
|
31
|
+
fileKey.fill(0);
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
exports.createVault = createVault;
|
|
35
|
+
/**
|
|
36
|
+
* Recovers the vault's file key. Callers must zero it when finished — prefer {@link getValue} and
|
|
37
|
+
* friends unless you are doing many operations at once.
|
|
38
|
+
*/
|
|
39
|
+
const unlock = (vault, identity) => (0, keys_1.unwrapFileKey)(vault.keys, identity);
|
|
40
|
+
exports.unlock = unlock;
|
|
41
|
+
/** Names of the secrets in the vault, sorted. Requires no key: names are not encrypted. */
|
|
42
|
+
const listKeys = (vault) => Object.keys(vault.values).sort();
|
|
43
|
+
exports.listKeys = listKeys;
|
|
44
|
+
/** Decrypts one value. */
|
|
45
|
+
const getValue = (vault, identity, key) => {
|
|
46
|
+
const fileKey = (0, exports.unlock)(vault, identity);
|
|
47
|
+
try {
|
|
48
|
+
return decodeValue(vault, fileKey, key);
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
fileKey.fill(0);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
exports.getValue = getValue;
|
|
55
|
+
/** Decrypts every value into a plain object. */
|
|
56
|
+
const getValues = (vault, identity) => {
|
|
57
|
+
const fileKey = (0, exports.unlock)(vault, identity);
|
|
58
|
+
try {
|
|
59
|
+
return Object.fromEntries((0, exports.listKeys)(vault).map((key) => [key, decodeValue(vault, fileKey, key)]));
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
fileKey.fill(0);
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
exports.getValues = getValues;
|
|
66
|
+
/** Returns a new vault with `key` set to `value`. The input vault is not modified. */
|
|
67
|
+
const setValue = (vault, identity, key, value) => (0, exports.setValues)(vault, identity, { [key]: value });
|
|
68
|
+
exports.setValue = setValue;
|
|
69
|
+
/** {@link setValue} for several secrets at once. */
|
|
70
|
+
const setValues = (vault, identity, values) => {
|
|
71
|
+
const fileKey = (0, exports.unlock)(vault, identity);
|
|
72
|
+
try {
|
|
73
|
+
const encrypted = Object.fromEntries(Object.entries(values).map(([key, value]) => [key, encodeValue(fileKey, key, value)]));
|
|
74
|
+
return (0, exports.normalize)({ ...vault, values: { ...vault.values, ...encrypted } });
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
fileKey.fill(0);
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
exports.setValues = setValues;
|
|
81
|
+
/** Returns a new vault without `key`. Removing a secret needs no decryption key. */
|
|
82
|
+
const deleteValue = (vault, key) => {
|
|
83
|
+
if (!(key in vault.values))
|
|
84
|
+
throw new VaultError(`no such secret: ${key}`);
|
|
85
|
+
const values = { ...vault.values };
|
|
86
|
+
delete values[key];
|
|
87
|
+
return (0, exports.normalize)({ ...vault, values });
|
|
88
|
+
};
|
|
89
|
+
exports.deleteValue = deleteValue;
|
|
90
|
+
/**
|
|
91
|
+
* Adds a recipient. This rekeys the vault — a fresh file key is generated and every value is
|
|
92
|
+
* re-encrypted — so the new recipient cannot decrypt copies of the file from before they joined.
|
|
93
|
+
*/
|
|
94
|
+
const addRecipient = (vault, identity, recipient) => {
|
|
95
|
+
validateRecipient(recipient);
|
|
96
|
+
if (vault.recipients.some((existing) => sameRecipient(existing, recipient))) {
|
|
97
|
+
throw new VaultError(`${recipient.recipient} is already a recipient`);
|
|
98
|
+
}
|
|
99
|
+
return rekey(vault, identity, [...vault.recipients, recipient]);
|
|
100
|
+
};
|
|
101
|
+
exports.addRecipient = addRecipient;
|
|
102
|
+
/**
|
|
103
|
+
* Removes a recipient and rekeys. The removed teammate keeps whatever they already read — rotate
|
|
104
|
+
* the underlying secrets too — but cannot read anything written after this point.
|
|
105
|
+
*/
|
|
106
|
+
const removeRecipient = (vault, identity, labelOrRecipient) => {
|
|
107
|
+
const remaining = vault.recipients.filter((existing) => existing.label !== labelOrRecipient && existing.recipient !== labelOrRecipient);
|
|
108
|
+
if (remaining.length === vault.recipients.length) {
|
|
109
|
+
throw new VaultError(`no such recipient: ${labelOrRecipient}`);
|
|
110
|
+
}
|
|
111
|
+
if (remaining.length === 0)
|
|
112
|
+
throw new VaultError('cannot remove the last recipient');
|
|
113
|
+
if (!remaining.some((r) => (0, keys_1.fingerprint)((0, keys_1.recipientFromString)(r.recipient)) === (0, keys_1.fingerprint)(identity.publicKey))) {
|
|
114
|
+
throw new VaultError('refusing to remove yourself: you would lose access to the vault');
|
|
115
|
+
}
|
|
116
|
+
return rekey(vault, identity, remaining);
|
|
117
|
+
};
|
|
118
|
+
exports.removeRecipient = removeRecipient;
|
|
119
|
+
/** Re-encrypts the vault under a brand new file key, keeping the same recipients. */
|
|
120
|
+
const rotateFileKey = (vault, identity) => rekey(vault, identity, vault.recipients);
|
|
121
|
+
exports.rotateFileKey = rotateFileKey;
|
|
122
|
+
/** True when `identity` is one of the vault's recipients. */
|
|
123
|
+
const canRead = (vault, identity) => {
|
|
124
|
+
const mine = (0, keys_1.fingerprint)(identity.publicKey);
|
|
125
|
+
return vault.keys.some((stanza) => stanza.recipient === mine);
|
|
126
|
+
};
|
|
127
|
+
exports.canRead = canRead;
|
|
128
|
+
const rekey = (vault, identity, recipients) => {
|
|
129
|
+
const plaintext = (0, exports.getValues)(vault, identity);
|
|
130
|
+
const fileKey = (0, keys_1.generateFileKey)();
|
|
131
|
+
try {
|
|
132
|
+
return (0, exports.normalize)({
|
|
133
|
+
...vault,
|
|
134
|
+
recipients: recipients.map(validateRecipient),
|
|
135
|
+
keys: recipients.map((recipient) => (0, keys_1.wrapFileKey)(fileKey, recipient.recipient)),
|
|
136
|
+
values: Object.fromEntries(Object.entries(plaintext).map(([key, value]) => [key, encodeValue(fileKey, key, value)])),
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
fileKey.fill(0);
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
/**
|
|
144
|
+
* Sorts recipients, stanzas and secret names so serializing the same logical vault twice produces
|
|
145
|
+
* the same file, byte for byte — the property that makes these files reviewable in git.
|
|
146
|
+
*/
|
|
147
|
+
const normalize = (vault) => ({
|
|
148
|
+
dcrypt: vault.dcrypt,
|
|
149
|
+
name: vault.name,
|
|
150
|
+
recipients: [...vault.recipients].sort((a, b) => a.recipient.localeCompare(b.recipient)),
|
|
151
|
+
keys: [...vault.keys].sort((a, b) => a.recipient.localeCompare(b.recipient)),
|
|
152
|
+
values: Object.fromEntries(Object.entries(vault.values).sort(([a], [b]) => a.localeCompare(b))),
|
|
153
|
+
});
|
|
154
|
+
exports.normalize = normalize;
|
|
155
|
+
/** Values are bound to their own name, so moving a ciphertext to another key fails to decrypt. */
|
|
156
|
+
const encodeValue = (fileKey, key, value) => base_1.base64.encode((0, core_1.sealWithKey)(fileKey, value, `dcrypt-secret:${key}`));
|
|
157
|
+
const decodeValue = (vault, fileKey, key) => {
|
|
158
|
+
const encoded = vault.values[key];
|
|
159
|
+
if (encoded === undefined)
|
|
160
|
+
throw new VaultError(`no such secret: ${key}`);
|
|
161
|
+
return new TextDecoder().decode((0, core_1.openWithKey)(fileKey, base_1.base64.decode(encoded), `dcrypt-secret:${key}`));
|
|
162
|
+
};
|
|
163
|
+
const validateRecipient = (recipient) => {
|
|
164
|
+
if (!recipient.label.trim())
|
|
165
|
+
throw new VaultError('recipients need a label');
|
|
166
|
+
// throws if the recipient string is malformed
|
|
167
|
+
(0, keys_1.recipientToString)((0, keys_1.recipientFromString)(recipient.recipient));
|
|
168
|
+
return recipient;
|
|
169
|
+
};
|
|
170
|
+
const sameRecipient = (a, b) => a.recipient === b.recipient;
|