@biolibs/bionet-client 0.0.0-stage → 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/src/backup.ts ADDED
@@ -0,0 +1,128 @@
1
+ /**
2
+ * A device's key, sealed so that it can be kept somewhere else.
3
+ *
4
+ * A device's key never leaves the device, with one exception: a lab with one member and one device
5
+ * is a lab that ends when the device does. So the key can be written out sealed under a passphrase,
6
+ * as a small document to keep somewhere that is not this machine, and opened again on a new one.
7
+ *
8
+ * What is sealed is useless without the passphrase, and nothing here remembers it. A sealed key
9
+ * whose passphrase is forgotten is a lost key.
10
+ */
11
+ import { importSigningKey, keyFingerprint } from "@biolibs/opencloning";
12
+
13
+ /** The version of the sealed-key document. */
14
+ export const BACKUP_VERSION = 1;
15
+
16
+ /** How many rounds the passphrase is stretched by. */
17
+ export const BACKUP_ROUNDS = 600_000;
18
+
19
+ /** The fewest characters a passphrase may have. */
20
+ export const SHORTEST_PASSPHRASE = 12;
21
+
22
+ /** A device's key, sealed under a passphrase. Every byte string is base64. */
23
+ export interface KeyBackup {
24
+ /** Which version of this document it is. */
25
+ bionet_key_backup: number;
26
+ /** The fingerprint of the key inside, so a person can tell which key a file holds without opening it. */
27
+ fingerprint: string;
28
+ /** How the passphrase becomes a key. */
29
+ kdf: { name: "PBKDF2"; hash: "SHA-256"; iterations: number; salt: string };
30
+ /** How the key was sealed. */
31
+ cipher: { name: "AES-GCM"; iv: string };
32
+ /** The sealed key. */
33
+ sealed: string;
34
+ }
35
+
36
+ const toBase64 = (bytes: Uint8Array): string => btoa(String.fromCharCode(...bytes));
37
+ const fromBase64 = (text: string): Uint8Array<ArrayBuffer> => Uint8Array.from(atob(text), (letter) => letter.charCodeAt(0));
38
+
39
+ async function stretch(passphrase: string, salt: Uint8Array<ArrayBuffer>, iterations: number): Promise<CryptoKey> {
40
+ const subtle = globalThis.crypto.subtle;
41
+ const material = await subtle.importKey("raw", new TextEncoder().encode(passphrase.normalize("NFKC")), "PBKDF2", false, ["deriveKey"]);
42
+ return subtle.deriveKey({ name: "PBKDF2", hash: "SHA-256", salt, iterations }, material, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
43
+ }
44
+
45
+ /**
46
+ * Seal a device's key under a passphrase.
47
+ *
48
+ * @param exported - The key, as `exportSigningKey` wrote it.
49
+ * @param passphrase - What it will take to open it again.
50
+ * @param options - `iterations` is only for tests, which cannot wait for the real number.
51
+ * @returns The sealed key, safe to write to a file.
52
+ * @throws If the passphrase is too short to be worth sealing anything with.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * import { exportSigningKey, generateSigningKey } from "@biolibs/opencloning";
57
+ * import { openKey, sealKey } from "@biolibs/bionet-client";
58
+ *
59
+ * const exported = await exportSigningKey(await generateSigningKey());
60
+ * const backup = await sealKey(exported, "correct horse battery staple");
61
+ * (await openKey(backup, "correct horse battery staple")) === exported; // true
62
+ * ```
63
+ */
64
+ export async function sealKey(exported: string, passphrase: string, options: { iterations?: number } = {}): Promise<KeyBackup> {
65
+ if (passphrase.length < SHORTEST_PASSPHRASE) {
66
+ throw new Error(`A passphrase of at least ${SHORTEST_PASSPHRASE} characters. Several unrelated words work well.`);
67
+ }
68
+ const iterations = options.iterations ?? BACKUP_ROUNDS;
69
+ const salt = globalThis.crypto.getRandomValues(new Uint8Array(16));
70
+ const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
71
+ const fingerprint = await keyFingerprint((await importSigningKey(exported)).publicKey);
72
+ const sealed = await globalThis.crypto.subtle.encrypt({ name: "AES-GCM", iv }, await stretch(passphrase, salt, iterations),
73
+ new TextEncoder().encode(exported));
74
+ return {
75
+ bionet_key_backup: BACKUP_VERSION, fingerprint,
76
+ kdf: { name: "PBKDF2", hash: "SHA-256", iterations, salt: toBase64(salt) },
77
+ cipher: { name: "AES-GCM", iv: toBase64(iv) },
78
+ sealed: toBase64(new Uint8Array(sealed)),
79
+ };
80
+ }
81
+
82
+ /**
83
+ * Read a sealed key, from the document or its text.
84
+ *
85
+ * @param value - What was in the file.
86
+ * @returns The sealed key.
87
+ * @throws If it is not one.
88
+ */
89
+ export function readBackup(value: unknown): KeyBackup {
90
+ let found = value;
91
+ if (typeof found === "string") {
92
+ try { found = JSON.parse(found); } catch { throw new Error("That is not a key backup."); }
93
+ }
94
+ const one = found as Partial<KeyBackup> | null;
95
+ const short = (text: unknown, most: number): text is string => typeof text === "string" && text.length > 0 && text.length <= most;
96
+ if (one === null || typeof one !== "object" || one.bionet_key_backup !== BACKUP_VERSION || !short(one.fingerprint, 100)
97
+ || one.kdf?.name !== "PBKDF2" || one.kdf.hash !== "SHA-256" || !Number.isSafeInteger(one.kdf.iterations)
98
+ || one.kdf.iterations < 1 || one.kdf.iterations > 10_000_000 || !short(one.kdf.salt, 200)
99
+ || one.cipher?.name !== "AES-GCM" || !short(one.cipher.iv, 200) || !short(one.sealed, 20_000)) {
100
+ throw new Error("That is not a key backup.");
101
+ }
102
+ return one as KeyBackup;
103
+ }
104
+
105
+ /**
106
+ * Open a sealed key.
107
+ *
108
+ * @param backup - The sealed key, or the text of the file it was kept in.
109
+ * @param passphrase - What it was sealed under.
110
+ * @returns The key, as `exportSigningKey` wrote it.
111
+ * @throws If the passphrase is wrong, or the document has been changed.
112
+ */
113
+ export async function openKey(backup: unknown, passphrase: string): Promise<string> {
114
+ const one = readBackup(backup);
115
+ let exported: string;
116
+ try {
117
+ const opened = await globalThis.crypto.subtle.decrypt({ name: "AES-GCM", iv: fromBase64(one.cipher.iv) },
118
+ await stretch(passphrase, fromBase64(one.kdf.salt), one.kdf.iterations), fromBase64(one.sealed));
119
+ exported = new TextDecoder().decode(opened);
120
+ } catch {
121
+ throw new Error("That passphrase does not open this backup.");
122
+ }
123
+ // The fingerprint on the outside is not sealed, so it is checked against what was inside.
124
+ if (await keyFingerprint((await importSigningKey(exported)).publicKey) !== one.fingerprint) {
125
+ throw new Error("This backup does not hold the key it says it does.");
126
+ }
127
+ return exported;
128
+ }
package/src/index.ts ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@biolibs/bionet-client`: one device in one lab.
4
+ *
5
+ * `@biolibs/bionet` says what a lab's signed log means. This is the thing that keeps one: a device's
6
+ * key, its copy of the log, every action a member can take, and the connection to the lab's web
7
+ * peer. It works with no network and syncs when there is one.
8
+ *
9
+ * It is an application with the edges left open. Where entries are kept, where the key lives and
10
+ * what opens a socket are handed in, so the same `Lab` runs behind a desktop window, in a browser or
11
+ * in a test:
12
+ *
13
+ * - `lab.ts` — the device: `Lab`, and the plain-data snapshot a window draws
14
+ * - `link.ts` — the connection to the web peer, which is allowed to fail
15
+ * - `source.ts` — the narrow way a window reaches a lab, in this process or another
16
+ * - `backup.ts` — the device's key, sealed under a passphrase to keep somewhere else
17
+ * - `store.ts` — the interfaces for storage and key keeping, with in-memory versions
18
+ * - `sqlite.ts` — storage in a SQLite file, at `@biolibs/bionet-client/sqlite` because it needs Node
19
+ */
20
+ export * from "./lab.js";
21
+ export * from "./link.js";
22
+ export * from "./store.js";
23
+ export * from "./source.js";
24
+ export * from "./backup.js";