@engenty/vault 0.0.0-stage → 0.20.3
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 +30 -2
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/key-store.d.ts +37 -0
- package/dist/key-store.js +134 -0
- package/dist/redact.d.ts +11 -0
- package/dist/redact.js +59 -0
- package/dist/seal.d.ts +50 -0
- package/dist/seal.js +144 -0
- package/package.json +25 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Matthias Platzer
|
|
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
CHANGED
|
@@ -1,3 +1,31 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @engenty/vault
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Keeps the secrets of an app: tokens, passwords, keys a person typed. MIT, no dependencies beyond
|
|
4
|
+
Node’s own `crypto`.
|
|
5
|
+
|
|
6
|
+
- **Sealed and bound.** `seal(ring, binding, value)` encrypts with AES-256-GCM. The binding names
|
|
7
|
+
where the value belongs (an owner, a table, a row, a purpose). It is the cipher’s additional
|
|
8
|
+
data, so a value copied to another row or owner doesn’t open.
|
|
9
|
+
- **Fails closed.** `unseal` throws a `VaultError` (`format`, `unknown-key`, `not-opened`) and
|
|
10
|
+
never hands back something else. `sealKeyCheck` and `keyCheckHolds` let a store check its key
|
|
11
|
+
before it reads or writes anything.
|
|
12
|
+
- **A new key.** A key ring holds the key that seals and the earlier ones that still open.
|
|
13
|
+
`needsReseal` and `reseal` move values to the current key.
|
|
14
|
+
- **A key per purpose or per owner.** `deriveKey(secret, purpose)` makes one with HKDF-SHA256.
|
|
15
|
+
- **Keys outside the database.** `environmentKeyStore` (32 bytes as base64), `fileKeyStore` (a
|
|
16
|
+
private file, refused when others may read it) and `keychainKeyStore` (macOS; the key goes to
|
|
17
|
+
`security` on its standard input). `loadOrCreateKey` makes one on first use where the store
|
|
18
|
+
can keep it.
|
|
19
|
+
- **Secrets out of text.** `redactor(secrets)` replaces each value as it is and as JSON, a URL
|
|
20
|
+
and a form write it, in text (`text`) and in data (`value`).
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import { deriveKey, keyRing, seal, unseal } from "@engenty/vault";
|
|
24
|
+
|
|
25
|
+
const ring = keyRing(deriveKey(process.env.STORE_KEY!, "stored-secrets"));
|
|
26
|
+
const binding = [teamId, "connection", connectionId];
|
|
27
|
+
const sealed = seal(ring, binding, token);
|
|
28
|
+
const again = unseal(ring, binding, sealed);
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Sealed values look like `v2.<key id>.<nonce>.<tag>.<ciphertext>`.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { environmentKeyStore, fileKeyStore, type KeyStore, keychainKeyStore, loadOrCreateKey, parseKey, type SecurityRunner, } from "./key-store.js";
|
|
2
|
+
export { MIN_SECRET_LENGTH, REDACTED, type Redactor, redactor } from "./redact.js";
|
|
3
|
+
export { deriveKey, type KeyRing, keyCheckHolds, keyIdOf, keyRing, needsReseal, reseal, seal, sealKeyCheck, unseal, VaultError, type VaultErrorReason, type VaultKey, } from "./seal.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { environmentKeyStore, fileKeyStore, keychainKeyStore, loadOrCreateKey, parseKey, } from "./key-store.js";
|
|
2
|
+
export { MIN_SECRET_LENGTH, REDACTED, redactor } from "./redact.js";
|
|
3
|
+
export { deriveKey, keyCheckHolds, keyIdOf, keyRing, needsReseal, reseal, seal, sealKeyCheck, unseal, VaultError, } from "./seal.js";
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export interface KeyStore {
|
|
2
|
+
/** What the store is, for a message: "environment", "file", "keychain". */
|
|
3
|
+
readonly kind: string;
|
|
4
|
+
/** The key, or null when the store holds none yet. A key that is there but unusable throws. */
|
|
5
|
+
load(): Buffer | null;
|
|
6
|
+
/** Keeps a new key. Absent on a store that can't make one (the environment). */
|
|
7
|
+
create?(key: Buffer): void;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* The store's key, made and kept on first use when the store can keep one. A store that holds no
|
|
11
|
+
* key and can't make one throws: a vault never starts without its key.
|
|
12
|
+
*/
|
|
13
|
+
export declare function loadOrCreateKey(store: KeyStore): Buffer;
|
|
14
|
+
/** 32 bytes as base64, nothing else. */
|
|
15
|
+
export declare function parseKey(text: string): Buffer;
|
|
16
|
+
/** A key from a setting, such as an environment variable: 32 bytes as base64. */
|
|
17
|
+
export declare function environmentKeyStore(value: string | undefined): KeyStore;
|
|
18
|
+
/**
|
|
19
|
+
* A key in a file of its own: 32 raw bytes, readable by its owner only. A file others may read
|
|
20
|
+
* is refused, not used. The folder is made private when the store makes it.
|
|
21
|
+
*/
|
|
22
|
+
export declare function fileKeyStore(path: string): KeyStore;
|
|
23
|
+
/** Runs `security` with arguments and the given input; what it printed and its exit code. */
|
|
24
|
+
export type SecurityRunner = (args: readonly string[], input?: string) => {
|
|
25
|
+
code: number;
|
|
26
|
+
stdout: string;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* A key in the macOS Keychain, as a generic password of `service` and `account`, written as
|
|
30
|
+
* base64. A new key goes to `security` on its standard input, never as an argument other
|
|
31
|
+
* processes could list.
|
|
32
|
+
*/
|
|
33
|
+
export declare function keychainKeyStore(options: {
|
|
34
|
+
service: string;
|
|
35
|
+
account: string;
|
|
36
|
+
run?: SecurityRunner;
|
|
37
|
+
}): KeyStore;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, statSync, writeSync, } from "node:fs";
|
|
4
|
+
import { dirname } from "node:path";
|
|
5
|
+
/**
|
|
6
|
+
* The store's key, made and kept on first use when the store can keep one. A store that holds no
|
|
7
|
+
* key and can't make one throws: a vault never starts without its key.
|
|
8
|
+
*/
|
|
9
|
+
export function loadOrCreateKey(store) {
|
|
10
|
+
const found = store.load();
|
|
11
|
+
if (found) {
|
|
12
|
+
return found;
|
|
13
|
+
}
|
|
14
|
+
if (!store.create) {
|
|
15
|
+
throw new Error(`No key in the ${store.kind}, and it can't keep a new one.`);
|
|
16
|
+
}
|
|
17
|
+
store.create(randomBytes(32));
|
|
18
|
+
// Read it back: another process may have kept its own key first.
|
|
19
|
+
const kept = store.load();
|
|
20
|
+
if (!kept) {
|
|
21
|
+
throw new Error(`The ${store.kind} didn't keep the new key.`);
|
|
22
|
+
}
|
|
23
|
+
return kept;
|
|
24
|
+
}
|
|
25
|
+
/** 32 bytes as base64, nothing else. */
|
|
26
|
+
export function parseKey(text) {
|
|
27
|
+
const trimmed = text.trim();
|
|
28
|
+
const key = Buffer.from(trimmed, "base64");
|
|
29
|
+
if (key.length !== 32 || key.toString("base64") !== trimmed) {
|
|
30
|
+
throw new Error("A key is exactly 32 bytes, written as base64.");
|
|
31
|
+
}
|
|
32
|
+
return key;
|
|
33
|
+
}
|
|
34
|
+
/** A key from a setting, such as an environment variable: 32 bytes as base64. */
|
|
35
|
+
export function environmentKeyStore(value) {
|
|
36
|
+
return {
|
|
37
|
+
kind: "environment",
|
|
38
|
+
load() {
|
|
39
|
+
return value?.trim() ? parseKey(value) : null;
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
const PRIVATE = 0o077;
|
|
44
|
+
/**
|
|
45
|
+
* A key in a file of its own: 32 raw bytes, readable by its owner only. A file others may read
|
|
46
|
+
* is refused, not used. The folder is made private when the store makes it.
|
|
47
|
+
*/
|
|
48
|
+
export function fileKeyStore(path) {
|
|
49
|
+
const windows = process.platform === "win32";
|
|
50
|
+
return {
|
|
51
|
+
kind: "file",
|
|
52
|
+
load() {
|
|
53
|
+
const info = statSync(path, { throwIfNoEntry: false });
|
|
54
|
+
if (!info) {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
if (!windows && (info.mode & PRIVATE) !== 0) {
|
|
58
|
+
throw new Error(`The key file ${path} may be read by others: make it 0600.`);
|
|
59
|
+
}
|
|
60
|
+
const key = readFileSync(path);
|
|
61
|
+
if (key.length !== 32) {
|
|
62
|
+
throw new Error(`The key file ${path} doesn't hold a key of 32 bytes.`);
|
|
63
|
+
}
|
|
64
|
+
return key;
|
|
65
|
+
},
|
|
66
|
+
create(key) {
|
|
67
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
68
|
+
let file;
|
|
69
|
+
try {
|
|
70
|
+
// "wx": never over a key that is there.
|
|
71
|
+
file = openSync(path, "wx", 0o600);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (error.code === "EEXIST") {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
writeSync(file, key);
|
|
81
|
+
fsyncSync(file);
|
|
82
|
+
}
|
|
83
|
+
finally {
|
|
84
|
+
closeSync(file);
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
const runSecurity = (args, input) => {
|
|
90
|
+
const result = spawnSync("/usr/bin/security", args, {
|
|
91
|
+
input: input ?? "",
|
|
92
|
+
encoding: "utf8",
|
|
93
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
94
|
+
});
|
|
95
|
+
if (result.error) {
|
|
96
|
+
throw result.error;
|
|
97
|
+
}
|
|
98
|
+
return { code: result.status ?? 1, stdout: result.stdout };
|
|
99
|
+
};
|
|
100
|
+
/** `security` answers 44 when the Keychain holds no such item. */
|
|
101
|
+
const NOT_FOUND = 44;
|
|
102
|
+
/**
|
|
103
|
+
* A key in the macOS Keychain, as a generic password of `service` and `account`, written as
|
|
104
|
+
* base64. A new key goes to `security` on its standard input, never as an argument other
|
|
105
|
+
* processes could list.
|
|
106
|
+
*/
|
|
107
|
+
export function keychainKeyStore(options) {
|
|
108
|
+
const run = options.run ?? runSecurity;
|
|
109
|
+
const { service, account } = options;
|
|
110
|
+
if (!options.run && process.platform !== "darwin") {
|
|
111
|
+
throw new Error("The Keychain is on macOS only.");
|
|
112
|
+
}
|
|
113
|
+
if (/["\\\s]/.test(service + account)) {
|
|
114
|
+
throw new Error("A Keychain service or account has no quotes, backslashes or spaces.");
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
kind: "keychain",
|
|
118
|
+
load() {
|
|
119
|
+
const found = run(["find-generic-password", "-s", service, "-a", account, "-w"]);
|
|
120
|
+
if (found.code === NOT_FOUND) {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
if (found.code !== 0) {
|
|
124
|
+
throw new Error(`The Keychain didn't answer for ${service} (security exited ${found.code}).`);
|
|
125
|
+
}
|
|
126
|
+
return parseKey(found.stdout);
|
|
127
|
+
},
|
|
128
|
+
create(key) {
|
|
129
|
+
// `security -i` reads its commands from the standard input. Without -U it never replaces
|
|
130
|
+
// an item that is there; when one is, the add fails and `loadOrCreateKey` reads that one.
|
|
131
|
+
run(["-i"], `add-generic-password -s "${service}" -a "${account}" -w "${key.toString("base64")}"\n`);
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
}
|
package/dist/redact.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const REDACTED = "[secret]";
|
|
2
|
+
/** Values shorter than this are not looked for: they would match ordinary words and numbers. */
|
|
3
|
+
export declare const MIN_SECRET_LENGTH = 8;
|
|
4
|
+
export interface Redactor {
|
|
5
|
+
/** The text with every form of every secret replaced. */
|
|
6
|
+
text(value: string): string;
|
|
7
|
+
/** A copy of the data with every string in it redacted, keys of objects included. */
|
|
8
|
+
value<T>(value: T): T;
|
|
9
|
+
}
|
|
10
|
+
/** A redactor for these secrets. Longer ones are replaced first, so one inside another goes whole. */
|
|
11
|
+
export declare function redactor(secrets: Iterable<string>, replacement?: string): Redactor;
|
package/dist/redact.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Keeps the values of secrets out of text and data before a model, a message or a log sees them:
|
|
2
|
+
// a token an API echoes, an error that quotes the request, a URL with the key in its query.
|
|
3
|
+
// It matches the exact values it is given, as they are and as JSON, a URL and a form write them.
|
|
4
|
+
// Patterns that guess at secrets (a bearer header, an `sk-` key) are the caller's own.
|
|
5
|
+
export const REDACTED = "[secret]";
|
|
6
|
+
/** Values shorter than this are not looked for: they would match ordinary words and numbers. */
|
|
7
|
+
export const MIN_SECRET_LENGTH = 8;
|
|
8
|
+
function forms(secret) {
|
|
9
|
+
const all = new Set();
|
|
10
|
+
for (const value of [secret, secret.trim()]) {
|
|
11
|
+
if (value.length < MIN_SECRET_LENGTH) {
|
|
12
|
+
continue;
|
|
13
|
+
}
|
|
14
|
+
all.add(value);
|
|
15
|
+
all.add(JSON.stringify(value).slice(1, -1));
|
|
16
|
+
all.add(encodeURIComponent(value));
|
|
17
|
+
all.add(new URLSearchParams({ v: value }).toString().slice(2));
|
|
18
|
+
}
|
|
19
|
+
return [...all];
|
|
20
|
+
}
|
|
21
|
+
const literal = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
22
|
+
/** A redactor for these secrets. Longer ones are replaced first, so one inside another goes whole. */
|
|
23
|
+
export function redactor(secrets, replacement = REDACTED) {
|
|
24
|
+
const variants = [...new Set([...secrets].flatMap(forms))].sort((a, b) => b.length - a.length);
|
|
25
|
+
const pattern = variants.length ? new RegExp(variants.map(literal).join("|"), "g") : null;
|
|
26
|
+
const text = (value) => (pattern ? value.replace(pattern, replacement) : value);
|
|
27
|
+
const walk = (value, seen) => {
|
|
28
|
+
if (typeof value === "string") {
|
|
29
|
+
return text(value);
|
|
30
|
+
}
|
|
31
|
+
if (value === null || typeof value !== "object") {
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
if (seen.has(value)) {
|
|
35
|
+
return seen.get(value);
|
|
36
|
+
}
|
|
37
|
+
if (Array.isArray(value)) {
|
|
38
|
+
const copy = [];
|
|
39
|
+
seen.set(value, copy);
|
|
40
|
+
for (const item of value) {
|
|
41
|
+
copy.push(walk(item, seen));
|
|
42
|
+
}
|
|
43
|
+
return copy;
|
|
44
|
+
}
|
|
45
|
+
if (value instanceof Date || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
const copy = {};
|
|
49
|
+
seen.set(value, copy);
|
|
50
|
+
for (const [key, item] of Object.entries(value)) {
|
|
51
|
+
copy[text(key)] = walk(item, seen);
|
|
52
|
+
}
|
|
53
|
+
return copy;
|
|
54
|
+
};
|
|
55
|
+
return {
|
|
56
|
+
text,
|
|
57
|
+
value: (value) => (pattern ? walk(value, new WeakMap()) : value),
|
|
58
|
+
};
|
|
59
|
+
}
|
package/dist/seal.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** A key of a ring: 32 bytes and the id sealed values name it by. */
|
|
2
|
+
export interface VaultKey {
|
|
3
|
+
id: string;
|
|
4
|
+
key: Buffer;
|
|
5
|
+
}
|
|
6
|
+
/** The key that seals, and the earlier ones that still open what they sealed. */
|
|
7
|
+
export interface KeyRing {
|
|
8
|
+
current: VaultKey;
|
|
9
|
+
previous: readonly VaultKey[];
|
|
10
|
+
}
|
|
11
|
+
export type VaultErrorReason =
|
|
12
|
+
/** The text is not a sealed value of this format. */
|
|
13
|
+
"format"
|
|
14
|
+
/** The value names a key the ring doesn't hold. */
|
|
15
|
+
| "unknown-key"
|
|
16
|
+
/** The key or the binding is not the one it was sealed with, or the value was changed. */
|
|
17
|
+
| "not-opened";
|
|
18
|
+
export declare class VaultError extends Error {
|
|
19
|
+
readonly reason: VaultErrorReason;
|
|
20
|
+
constructor(reason: VaultErrorReason, message: string);
|
|
21
|
+
}
|
|
22
|
+
/** A ring from the key that seals and the earlier keys that still open. */
|
|
23
|
+
export declare function keyRing(current: VaultKey, ...previous: VaultKey[]): KeyRing;
|
|
24
|
+
/**
|
|
25
|
+
* A key of its own for one purpose, made from a longer-lived secret with HKDF-SHA256: one secret
|
|
26
|
+
* of an install gives a key per purpose (stored secrets, short-lived state) or per owner (a team,
|
|
27
|
+
* a person), and none of them opens what another sealed.
|
|
28
|
+
*/
|
|
29
|
+
export declare function deriveKey(secret: Buffer | string, purpose: string, id?: string): VaultKey;
|
|
30
|
+
/** Seals `value` with the ring's current key, bound to `binding`. */
|
|
31
|
+
export declare function seal(ring: KeyRing, binding: readonly string[], value: string): string;
|
|
32
|
+
/** The id of the key a value was sealed with. */
|
|
33
|
+
export declare function keyIdOf(sealed: string): string;
|
|
34
|
+
/**
|
|
35
|
+
* Opens a sealed value. It throws a `VaultError` when it can't, and never answers something
|
|
36
|
+
* else in its place: a caller that can't open a secret must not carry on as if there were none.
|
|
37
|
+
*/
|
|
38
|
+
export declare function unseal(ring: KeyRing, binding: readonly string[], sealed: string): string;
|
|
39
|
+
/** Whether a value was sealed with a key other than the ring's current one. */
|
|
40
|
+
export declare function needsReseal(ring: KeyRing, sealed: string): boolean;
|
|
41
|
+
/** The value sealed again with the ring's current key; a value sealed with it already comes back as it is. */
|
|
42
|
+
export declare function reseal(ring: KeyRing, binding: readonly string[], sealed: string): string;
|
|
43
|
+
/**
|
|
44
|
+
* A key check: a known text sealed for `owner`, kept beside the owner's secrets. Before a store
|
|
45
|
+
* reads or writes a secret it checks the ring against it (`keyCheckHolds`). A wrong or missing
|
|
46
|
+
* key then stops the store before it writes anything another key can't open.
|
|
47
|
+
*/
|
|
48
|
+
export declare function sealKeyCheck(ring: KeyRing, owner: string): string;
|
|
49
|
+
/** Whether the ring opens the owner's key check. */
|
|
50
|
+
export declare function keyCheckHolds(ring: KeyRing, owner: string, sealed: string): boolean;
|
package/dist/seal.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from "node:crypto";
|
|
2
|
+
// A sealed value is AES-256-GCM under one key of a key ring, bound to where it belongs.
|
|
3
|
+
//
|
|
4
|
+
// v2.<key id>.<nonce>.<tag>.<ciphertext> each part base64url
|
|
5
|
+
//
|
|
6
|
+
// The binding (an owner, a table, a row, a purpose: whatever the caller names) and the key id are
|
|
7
|
+
// the additional data of the cipher, so a value copied to another row, another owner or another
|
|
8
|
+
// purpose doesn't open, and neither does one whose key id was changed. Nothing of the binding is
|
|
9
|
+
// stored in the sealed value: the caller knows it from where the value is kept.
|
|
10
|
+
const FORMAT = "v2";
|
|
11
|
+
const AAD_PREFIX = "engenty-vault";
|
|
12
|
+
const KEY_ID = /^[A-Za-z0-9_-]{1,32}$/;
|
|
13
|
+
export class VaultError extends Error {
|
|
14
|
+
reason;
|
|
15
|
+
constructor(reason, message) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "VaultError";
|
|
18
|
+
this.reason = reason;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function checkKey(key) {
|
|
22
|
+
if (!KEY_ID.test(key.id)) {
|
|
23
|
+
throw new Error(`A key id is 1 to 32 letters, digits, "-" or "_": "${key.id}" is not.`);
|
|
24
|
+
}
|
|
25
|
+
if (!Buffer.isBuffer(key.key) || key.key.length !== 32) {
|
|
26
|
+
throw new Error(`The key "${key.id}" must be 32 bytes.`);
|
|
27
|
+
}
|
|
28
|
+
return key;
|
|
29
|
+
}
|
|
30
|
+
/** A ring from the key that seals and the earlier keys that still open. */
|
|
31
|
+
export function keyRing(current, ...previous) {
|
|
32
|
+
const all = [current, ...previous].map(checkKey);
|
|
33
|
+
const ids = new Set(all.map((k) => k.id));
|
|
34
|
+
if (ids.size !== all.length) {
|
|
35
|
+
throw new Error("Two keys of a ring have the same id.");
|
|
36
|
+
}
|
|
37
|
+
return { current, previous };
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* A key of its own for one purpose, made from a longer-lived secret with HKDF-SHA256: one secret
|
|
41
|
+
* of an install gives a key per purpose (stored secrets, short-lived state) or per owner (a team,
|
|
42
|
+
* a person), and none of them opens what another sealed.
|
|
43
|
+
*/
|
|
44
|
+
export function deriveKey(secret, purpose, id = "k1") {
|
|
45
|
+
const material = typeof secret === "string" ? Buffer.from(secret, "utf8") : secret;
|
|
46
|
+
if (material.length < 16) {
|
|
47
|
+
throw new Error("The secret a key is derived from must be at least 16 bytes.");
|
|
48
|
+
}
|
|
49
|
+
if (!purpose) {
|
|
50
|
+
throw new Error("A derived key needs a purpose.");
|
|
51
|
+
}
|
|
52
|
+
const key = Buffer.from(hkdfSync("sha256", material, AAD_PREFIX, purpose, 32));
|
|
53
|
+
return checkKey({ id, key });
|
|
54
|
+
}
|
|
55
|
+
function additionalData(keyId, binding) {
|
|
56
|
+
return Buffer.from(JSON.stringify([AAD_PREFIX, keyId, ...binding]), "utf8");
|
|
57
|
+
}
|
|
58
|
+
/** Seals `value` with the ring's current key, bound to `binding`. */
|
|
59
|
+
export function seal(ring, binding, value) {
|
|
60
|
+
const { id, key } = ring.current;
|
|
61
|
+
const nonce = randomBytes(12);
|
|
62
|
+
const cipher = createCipheriv("aes-256-gcm", key, nonce);
|
|
63
|
+
cipher.setAAD(additionalData(id, binding));
|
|
64
|
+
const body = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
|
|
65
|
+
return [FORMAT, id, nonce, cipher.getAuthTag(), body]
|
|
66
|
+
.map((part) => (typeof part === "string" ? part : part.toString("base64url")))
|
|
67
|
+
.join(".");
|
|
68
|
+
}
|
|
69
|
+
function parse(sealed) {
|
|
70
|
+
const parts = sealed.split(".");
|
|
71
|
+
const [format, keyId, nonce, tag, body] = parts;
|
|
72
|
+
if (parts.length !== 5 ||
|
|
73
|
+
format !== FORMAT ||
|
|
74
|
+
!keyId ||
|
|
75
|
+
!KEY_ID.test(keyId) ||
|
|
76
|
+
!nonce ||
|
|
77
|
+
!tag ||
|
|
78
|
+
body === undefined) {
|
|
79
|
+
throw new VaultError("format", "This is not a sealed value.");
|
|
80
|
+
}
|
|
81
|
+
const parsed = {
|
|
82
|
+
keyId,
|
|
83
|
+
nonce: Buffer.from(nonce, "base64url"),
|
|
84
|
+
tag: Buffer.from(tag, "base64url"),
|
|
85
|
+
body: Buffer.from(body, "base64url"),
|
|
86
|
+
};
|
|
87
|
+
if (parsed.nonce.length !== 12 || parsed.tag.length !== 16) {
|
|
88
|
+
throw new VaultError("format", "This is not a sealed value.");
|
|
89
|
+
}
|
|
90
|
+
return parsed;
|
|
91
|
+
}
|
|
92
|
+
/** The id of the key a value was sealed with. */
|
|
93
|
+
export function keyIdOf(sealed) {
|
|
94
|
+
return parse(sealed).keyId;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Opens a sealed value. It throws a `VaultError` when it can't, and never answers something
|
|
98
|
+
* else in its place: a caller that can't open a secret must not carry on as if there were none.
|
|
99
|
+
*/
|
|
100
|
+
export function unseal(ring, binding, sealed) {
|
|
101
|
+
const { keyId, nonce, tag, body } = parse(sealed);
|
|
102
|
+
const found = [ring.current, ...ring.previous].find((k) => k.id === keyId);
|
|
103
|
+
if (!found) {
|
|
104
|
+
throw new VaultError("unknown-key", `The value was sealed with the key "${keyId}", which the ring doesn't hold.`);
|
|
105
|
+
}
|
|
106
|
+
try {
|
|
107
|
+
const decipher = createDecipheriv("aes-256-gcm", found.key, nonce, { authTagLength: 16 });
|
|
108
|
+
decipher.setAAD(additionalData(keyId, binding));
|
|
109
|
+
decipher.setAuthTag(tag);
|
|
110
|
+
return Buffer.concat([decipher.update(body), decipher.final()]).toString("utf8");
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
throw new VaultError("not-opened", "The value doesn't open with this key and binding.");
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** Whether a value was sealed with a key other than the ring's current one. */
|
|
117
|
+
export function needsReseal(ring, sealed) {
|
|
118
|
+
return keyIdOf(sealed) !== ring.current.id;
|
|
119
|
+
}
|
|
120
|
+
/** The value sealed again with the ring's current key; a value sealed with it already comes back as it is. */
|
|
121
|
+
export function reseal(ring, binding, sealed) {
|
|
122
|
+
return needsReseal(ring, sealed) ? seal(ring, binding, unseal(ring, binding, sealed)) : sealed;
|
|
123
|
+
}
|
|
124
|
+
const CHECK_TEXT = "engenty-vault key check";
|
|
125
|
+
/**
|
|
126
|
+
* A key check: a known text sealed for `owner`, kept beside the owner's secrets. Before a store
|
|
127
|
+
* reads or writes a secret it checks the ring against it (`keyCheckHolds`). A wrong or missing
|
|
128
|
+
* key then stops the store before it writes anything another key can't open.
|
|
129
|
+
*/
|
|
130
|
+
export function sealKeyCheck(ring, owner) {
|
|
131
|
+
return seal(ring, ["key-check", owner], CHECK_TEXT);
|
|
132
|
+
}
|
|
133
|
+
/** Whether the ring opens the owner's key check. */
|
|
134
|
+
export function keyCheckHolds(ring, owner, sealed) {
|
|
135
|
+
try {
|
|
136
|
+
return unseal(ring, ["key-check", owner], sealed) === CHECK_TEXT;
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
if (error instanceof VaultError) {
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@engenty/vault",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.20.3",
|
|
4
|
+
"description": "Secrets sealed with AES-256-GCM and bound to where they belong, key rings for rotation, keys from the environment, a private file or the macOS Keychain, and a redactor that keeps secret values out of text.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/engenty/wizards.git",
|
|
9
|
+
"directory": "packages/vault"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"main": "./dist/index.js",
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"default": "./dist/index.js"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"dist",
|
|
22
|
+
"LICENSE"
|
|
23
|
+
],
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
}
|
|
27
|
+
}
|