@biolibs/bionet-client 0.0.0-stage → 0.1.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/README.md +77 -2
- package/dist/index.d.ts +23 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +23 -0
- package/dist/index.js.map +1 -0
- package/dist/lab.d.ts +266 -0
- package/dist/lab.d.ts.map +1 -0
- package/dist/lab.js +372 -0
- package/dist/lab.js.map +1 -0
- package/dist/link.d.ts +83 -0
- package/dist/link.d.ts.map +1 -0
- package/dist/link.js +228 -0
- package/dist/link.js.map +1 -0
- package/dist/source.d.ts +52 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +36 -0
- package/dist/source.js.map +1 -0
- package/dist/sqlite.d.ts +9 -0
- package/dist/sqlite.d.ts.map +1 -0
- package/dist/sqlite.js +60 -0
- package/dist/sqlite.js.map +1 -0
- package/dist/store.d.ts +46 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +32 -0
- package/dist/store.js.map +1 -0
- package/package.json +48 -4
- package/src/index.ts +22 -0
- package/src/lab.ts +468 -0
- package/src/link.ts +240 -0
- package/src/source.ts +62 -0
- package/src/sqlite.ts +60 -0
- package/src/store.ts +59 -0
package/src/link.ts
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A device's connection to the lab's web peer.
|
|
3
|
+
*
|
|
4
|
+
* It is allowed to fail. A device works with no peer at all; this only carries entries to and from
|
|
5
|
+
* the lab's address when it can, says how that is going, and keeps trying when it cannot.
|
|
6
|
+
*
|
|
7
|
+
* The exchange is the one `@biolibs/bionet`'s `sync.ts` describes. The peer sends a number, this
|
|
8
|
+
* signs it with the device's key, and if that key is on the lab's roster the two swap whatever the
|
|
9
|
+
* other lacks. A peer that holds nothing knows no members, so on being refused this sends what it
|
|
10
|
+
* holds and asks again: that is how a lab's first entries get there at all.
|
|
11
|
+
*/
|
|
12
|
+
import { entriesBeyond, haveOf, readMessage, signHello, type Have, type SignedEntry, type SignedInventory,
|
|
13
|
+
type SyncMessage } from "@biolibs/bionet";
|
|
14
|
+
import type { SigningKey } from "@biolibs/opencloning";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* How the connection is going. `waiting` means the peer answered and this device's key is not on the
|
|
18
|
+
* roster it holds.
|
|
19
|
+
*/
|
|
20
|
+
export type LinkStatus = "offline" | "connecting" | "waiting" | "syncing" | "synced";
|
|
21
|
+
|
|
22
|
+
/** What a link needs. */
|
|
23
|
+
export interface LinkOptions {
|
|
24
|
+
/** The peer's socket address. */
|
|
25
|
+
url: string;
|
|
26
|
+
/** The lab's ID. */
|
|
27
|
+
lab: string;
|
|
28
|
+
/** This device's key. */
|
|
29
|
+
key: SigningKey;
|
|
30
|
+
/** What this device holds, now. */
|
|
31
|
+
held: () => readonly SignedEntry[];
|
|
32
|
+
/** Hand over entries that arrived. Resolves to how many were kept. */
|
|
33
|
+
take: (entries: readonly unknown[]) => Promise<number>;
|
|
34
|
+
/** Called whenever the status, the problem or what is pending changes. */
|
|
35
|
+
onChange: () => void;
|
|
36
|
+
/** Something to open sockets with. Defaults to the runtime's own `WebSocket`. */
|
|
37
|
+
WebSocket?: typeof globalThis.WebSocket;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** How many entries go in one message. */
|
|
41
|
+
const BATCH = 500;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The connection from one device to its lab's web peer.
|
|
45
|
+
*
|
|
46
|
+
* `Lab` makes and runs one of these; it is exported for anything that wants to drive the exchange
|
|
47
|
+
* itself. Give it the peer's address, the lab, the device's key and a way to read and add to what
|
|
48
|
+
* the device holds, then `start()` it. It reconnects on its own, waiting longer each time.
|
|
49
|
+
*/
|
|
50
|
+
export class PeerLink {
|
|
51
|
+
status: LinkStatus = "offline";
|
|
52
|
+
/** What is in the way, said for a person, or `null`. */
|
|
53
|
+
problem: string | null = null;
|
|
54
|
+
/** When this device and the peer last had the same entries. */
|
|
55
|
+
lastSynced: string | null = null;
|
|
56
|
+
/** What the peer holds, as far as this knows. `null` until the peer has said. */
|
|
57
|
+
peerHas: Have | null = null;
|
|
58
|
+
|
|
59
|
+
private ws: WebSocket | null = null;
|
|
60
|
+
private stopped = true;
|
|
61
|
+
private delay = 1_000;
|
|
62
|
+
private retry: ReturnType<typeof setTimeout> | null = null;
|
|
63
|
+
private turn: Promise<unknown> = Promise.resolve();
|
|
64
|
+
private publishing: ((answer: { ok: boolean; reason: string | null }) => void) | null = null;
|
|
65
|
+
private pushNow: () => void = () => {};
|
|
66
|
+
private sendInventory: (signed: SignedInventory) => void = () => {};
|
|
67
|
+
|
|
68
|
+
constructor(private readonly options: LinkOptions) {}
|
|
69
|
+
|
|
70
|
+
/** How many entries held here the peer is not known to have. */
|
|
71
|
+
get pending(): number {
|
|
72
|
+
const held = this.options.held();
|
|
73
|
+
return this.peerHas === null ? held.length : entriesBeyond(held, this.peerHas).length;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Start, and keep trying. */
|
|
77
|
+
start(): void {
|
|
78
|
+
this.stopped = false;
|
|
79
|
+
this.open();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Stop, and stop trying. */
|
|
83
|
+
stop(): void {
|
|
84
|
+
this.stopped = true;
|
|
85
|
+
if (this.retry !== null) clearTimeout(this.retry);
|
|
86
|
+
this.ws?.close();
|
|
87
|
+
this.ws = null;
|
|
88
|
+
this.pushNow = () => {};
|
|
89
|
+
this.sendInventory = () => {};
|
|
90
|
+
this.say("offline", null);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Send the peer whatever it lacks. Called whenever something is written on this device. */
|
|
94
|
+
push(): void {
|
|
95
|
+
this.pushNow();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Ask the peer to publish an inventory.
|
|
100
|
+
*
|
|
101
|
+
* @param signed - The inventory, signed by this device.
|
|
102
|
+
* @returns Whether it was published, and why not.
|
|
103
|
+
*/
|
|
104
|
+
publish(signed: SignedInventory): Promise<{ ok: boolean; reason: string | null }> {
|
|
105
|
+
if (this.status !== "synced" && this.status !== "syncing") {
|
|
106
|
+
return Promise.resolve({ ok: false, reason: "Not connected to the lab's peer as a member." });
|
|
107
|
+
}
|
|
108
|
+
return new Promise((resolve) => {
|
|
109
|
+
this.publishing = resolve;
|
|
110
|
+
this.sendInventory(signed);
|
|
111
|
+
setTimeout(() => {
|
|
112
|
+
if (this.publishing === resolve) {
|
|
113
|
+
this.publishing = null;
|
|
114
|
+
resolve({ ok: false, reason: "The lab's peer did not answer." });
|
|
115
|
+
}
|
|
116
|
+
}, 15_000);
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
private say(status: LinkStatus, problem: string | null = this.problem): void {
|
|
121
|
+
this.status = status;
|
|
122
|
+
this.problem = problem;
|
|
123
|
+
this.options.onChange();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
private settled(): void {
|
|
127
|
+
this.lastSynced = new Date().toISOString();
|
|
128
|
+
this.say("synced", null);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
private open(): void {
|
|
132
|
+
if (this.stopped) return;
|
|
133
|
+
const { lab, key, held, take } = this.options;
|
|
134
|
+
const Socket = this.options.WebSocket ?? globalThis.WebSocket;
|
|
135
|
+
this.say("connecting", null);
|
|
136
|
+
let ws: WebSocket;
|
|
137
|
+
try {
|
|
138
|
+
ws = new Socket(this.options.url);
|
|
139
|
+
} catch (cause) {
|
|
140
|
+
this.say("offline", `That is not an address a peer can be reached at: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
this.ws = ws;
|
|
144
|
+
let nonce = "";
|
|
145
|
+
let welcomed = false;
|
|
146
|
+
let pushedEverything = false;
|
|
147
|
+
const send = (message: SyncMessage): void => { if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(message)); };
|
|
148
|
+
const sendEntries = (entries: readonly SignedEntry[]): void => {
|
|
149
|
+
for (let at = 0; at < entries.length; at += BATCH) send({ type: "entries", entries: entries.slice(at, at + BATCH) });
|
|
150
|
+
};
|
|
151
|
+
const hello = async (): Promise<void> => send({ type: "hello", have: haveOf(held()), signature: await signHello(key, lab, nonce) });
|
|
152
|
+
|
|
153
|
+
this.pushNow = () => {
|
|
154
|
+
// Only over a connection that is open. Counting an entry as delivered because it was written
|
|
155
|
+
// into a socket that had already closed would leave it unsent and reported as sent.
|
|
156
|
+
if (!welcomed || this.peerHas === null || ws.readyState !== ws.OPEN) return;
|
|
157
|
+
const lacking = entriesBeyond(held(), this.peerHas);
|
|
158
|
+
if (lacking.length === 0) return;
|
|
159
|
+
this.peerHas = haveOf(held()); // what it will have, once it has kept these
|
|
160
|
+
this.say("syncing");
|
|
161
|
+
sendEntries(lacking);
|
|
162
|
+
};
|
|
163
|
+
this.sendInventory = (signed) => send({ type: "inventory", signed });
|
|
164
|
+
|
|
165
|
+
ws.addEventListener("message", (event) => {
|
|
166
|
+
this.turn = this.turn.then(async () => {
|
|
167
|
+
let message: SyncMessage;
|
|
168
|
+
try {
|
|
169
|
+
message = readMessage(String(event.data));
|
|
170
|
+
} catch {
|
|
171
|
+
return; // a peer that says something else is ignored, not obeyed
|
|
172
|
+
}
|
|
173
|
+
if (message.type === "challenge") {
|
|
174
|
+
if (message.lab !== lab) {
|
|
175
|
+
this.say("waiting", "That peer serves a different lab.");
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
nonce = message.nonce;
|
|
179
|
+
await hello();
|
|
180
|
+
} else if (message.type === "refused") {
|
|
181
|
+
if (message.code === "not-a-member") {
|
|
182
|
+
if (welcomed) {
|
|
183
|
+
welcomed = false;
|
|
184
|
+
this.say("waiting", message.reason);
|
|
185
|
+
} else if (!pushedEverything && held().length > 0) {
|
|
186
|
+
pushedEverything = true;
|
|
187
|
+
sendEntries(held());
|
|
188
|
+
} else {
|
|
189
|
+
this.say("waiting", "This device's key is not on the roster the lab's peer holds yet. A keeper has to add it and sync.");
|
|
190
|
+
// Ask again in a few seconds, on the same connection: the keeper may be doing it now.
|
|
191
|
+
setTimeout(() => { if (this.ws === ws && !welcomed) void hello(); }, 4_000);
|
|
192
|
+
}
|
|
193
|
+
} else if (message.code === "bad-inventory" && this.publishing !== null) {
|
|
194
|
+
this.publishing({ ok: false, reason: message.reason });
|
|
195
|
+
this.publishing = null;
|
|
196
|
+
} else {
|
|
197
|
+
this.say(this.status, message.reason);
|
|
198
|
+
}
|
|
199
|
+
} else if (message.type === "welcome") {
|
|
200
|
+
welcomed = true;
|
|
201
|
+
this.delay = 1_000;
|
|
202
|
+
this.peerHas = message.have;
|
|
203
|
+
this.say("syncing", null);
|
|
204
|
+
this.pushNow();
|
|
205
|
+
if (this.pending === 0) this.settled();
|
|
206
|
+
} else if (message.type === "entries") {
|
|
207
|
+
await take(message.entries);
|
|
208
|
+
if (welcomed && this.peerHas !== null) {
|
|
209
|
+
// Whatever the peer just sent, it has. Count it, so it is not offered straight back.
|
|
210
|
+
for (const { entry } of message.entries) {
|
|
211
|
+
this.peerHas[entry.author] = Math.max(this.peerHas[entry.author] ?? -1, entry.seq);
|
|
212
|
+
}
|
|
213
|
+
if (this.pending === 0) this.settled();
|
|
214
|
+
}
|
|
215
|
+
} else if (message.type === "kept") {
|
|
216
|
+
if (!welcomed) await hello(); // the peer now knows the roster; ask again
|
|
217
|
+
else if (this.pending === 0) this.settled();
|
|
218
|
+
} else if (message.type === "published" && this.publishing !== null) {
|
|
219
|
+
this.publishing({ ok: true, reason: null });
|
|
220
|
+
this.publishing = null;
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
});
|
|
224
|
+
ws.addEventListener("close", () => {
|
|
225
|
+
if (this.ws !== ws) return;
|
|
226
|
+
this.ws = null;
|
|
227
|
+
this.pushNow = () => {};
|
|
228
|
+
this.sendInventory = () => {};
|
|
229
|
+
if (this.publishing !== null) {
|
|
230
|
+
this.publishing({ ok: false, reason: "The connection to the lab's peer was lost." });
|
|
231
|
+
this.publishing = null;
|
|
232
|
+
}
|
|
233
|
+
if (this.stopped) return;
|
|
234
|
+
this.say("offline", this.status === "waiting" ? this.problem : null);
|
|
235
|
+
this.retry = setTimeout(() => this.open(), this.delay);
|
|
236
|
+
this.delay = Math.min(this.delay * 2, 30_000);
|
|
237
|
+
});
|
|
238
|
+
ws.addEventListener("error", () => {}); // the close that follows is what is acted on
|
|
239
|
+
}
|
|
240
|
+
}
|
package/src/source.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The narrow way a window reaches a lab.
|
|
3
|
+
*
|
|
4
|
+
* A window does not always share a process with the lab it shows. In a desktop app the lab lives
|
|
5
|
+
* where the key and the files are, and the window is deliberately given neither. So anything that
|
|
6
|
+
* draws a lab asks for it through this: the lab as plain data, to be told when it changes, and one
|
|
7
|
+
* of a fixed list of things to be done. A `Lab` is one of these directly (`sourceOf`), and so is a
|
|
8
|
+
* bridge to a lab somewhere else.
|
|
9
|
+
*/
|
|
10
|
+
import type { Lab, LabSnapshot } from "./lab.js";
|
|
11
|
+
|
|
12
|
+
/** Everything a window may ask a lab to do. Nothing outside this list can be asked for. */
|
|
13
|
+
export const ACTIONS = ["setPerson", "found", "join", "setPeer", "setOrigin", "addMember", "addPart", "addItem",
|
|
14
|
+
"adjust", "recount", "retire", "offer", "setField", "publish"] as const;
|
|
15
|
+
|
|
16
|
+
/** One thing a window may ask for. */
|
|
17
|
+
export type Action = (typeof ACTIONS)[number];
|
|
18
|
+
|
|
19
|
+
/** How asking went: what came back, or why it could not be done, said for a person. */
|
|
20
|
+
export type Answer = { ok: true; result: unknown } | { ok: false; error: string };
|
|
21
|
+
|
|
22
|
+
/** A lab, as a window reaches it. */
|
|
23
|
+
export interface LabSource {
|
|
24
|
+
/** Be told when the lab changes. Returns a function that stops the telling. */
|
|
25
|
+
subscribe(listener: () => void): () => void;
|
|
26
|
+
/** The lab as it stands, or `null` while it is still being opened. The same object until it changes. */
|
|
27
|
+
snapshot(): LabSnapshot | null;
|
|
28
|
+
/** Ask for one thing to be done. It never throws: a refusal comes back as an answer. */
|
|
29
|
+
act(action: Action, payload?: unknown): Promise<Answer>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Do one of the things a window may ask for.
|
|
34
|
+
*
|
|
35
|
+
* This is the door between a window and a lab, and it is deliberately the only one: an action that
|
|
36
|
+
* is not on the list is refused whatever it is called, so a window that has been tricked can still
|
|
37
|
+
* only do what a person at it could.
|
|
38
|
+
*
|
|
39
|
+
* @param lab - The lab.
|
|
40
|
+
* @param action - What to do.
|
|
41
|
+
* @param payload - What to do it with.
|
|
42
|
+
* @returns What came back, or why it could not be done.
|
|
43
|
+
*/
|
|
44
|
+
export async function perform(lab: Lab, action: string, payload?: unknown): Promise<Answer> {
|
|
45
|
+
if (!(ACTIONS as readonly string[]).includes(action)) return { ok: false, error: "That is not something this app does." };
|
|
46
|
+
try {
|
|
47
|
+
const method = (lab as unknown as Record<string, (given?: unknown) => Promise<unknown>>)[action]!;
|
|
48
|
+
return { ok: true, result: await method.call(lab, payload) };
|
|
49
|
+
} catch (cause) {
|
|
50
|
+
return { ok: false, error: cause instanceof Error ? cause.message : String(cause) };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* A lab in this process, as a window reaches it.
|
|
56
|
+
*
|
|
57
|
+
* @param lab - The lab, opened.
|
|
58
|
+
* @returns The source.
|
|
59
|
+
*/
|
|
60
|
+
export function sourceOf(lab: Lab): LabSource {
|
|
61
|
+
return { subscribe: lab.subscribe, snapshot: lab.snapshot, act: (action, payload) => perform(lab, action, payload) };
|
|
62
|
+
}
|
package/src/sqlite.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A device's store as one SQLite file, using the SQLite built into Node.
|
|
3
|
+
*
|
|
4
|
+
* This is its own entry point, `@biolibs/bionet-client/sqlite`, because it needs Node: importing the
|
|
5
|
+
* rest of the package into a browser must not drag it in.
|
|
6
|
+
*/
|
|
7
|
+
import { mkdirSync } from "node:fs";
|
|
8
|
+
import { createRequire } from "node:module";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import type { SignedEntry } from "@biolibs/bionet";
|
|
11
|
+
import type { LabStore } from "./store.js";
|
|
12
|
+
|
|
13
|
+
// Asked for at run time and not imported, because tools that bundle or transform code do not all
|
|
14
|
+
// know yet that `node:sqlite` is part of Node and has no name without its prefix.
|
|
15
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite") as typeof import("node:sqlite");
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Open, or make, a device's store in a folder.
|
|
19
|
+
*
|
|
20
|
+
* @param dir - The folder. The file is `lab.db` inside it.
|
|
21
|
+
* @returns The store.
|
|
22
|
+
*/
|
|
23
|
+
export function sqliteStore(dir: string): LabStore {
|
|
24
|
+
mkdirSync(dir, { recursive: true });
|
|
25
|
+
const db = new DatabaseSync(join(dir, "lab.db"));
|
|
26
|
+
db.exec(`
|
|
27
|
+
pragma journal_mode = wal;
|
|
28
|
+
create table if not exists entries (id text primary key, author text not null, seq integer not null, json text not null);
|
|
29
|
+
create index if not exists entries_by_log on entries (author, seq);
|
|
30
|
+
create table if not exists settings (name text primary key, value text not null);
|
|
31
|
+
`);
|
|
32
|
+
const insert = db.prepare("insert or ignore into entries (id, author, seq, json) values (?, ?, ?, ?)");
|
|
33
|
+
const put = db.prepare("insert into settings (name, value) values (?, ?) on conflict(name) do update set value = excluded.value");
|
|
34
|
+
const get = db.prepare("select value from settings where name = ?");
|
|
35
|
+
const forget = db.prepare("delete from settings where name = ?");
|
|
36
|
+
const all = db.prepare("select json from entries order by author, seq");
|
|
37
|
+
|
|
38
|
+
return {
|
|
39
|
+
entries: () => all.all().map((row) => JSON.parse(String(row["json"])) as SignedEntry),
|
|
40
|
+
add(entries) {
|
|
41
|
+
db.exec("begin");
|
|
42
|
+
try {
|
|
43
|
+
for (const { id, signed } of entries) insert.run(id, signed.entry.author, signed.entry.seq, JSON.stringify(signed));
|
|
44
|
+
db.exec("commit");
|
|
45
|
+
} catch (cause) {
|
|
46
|
+
db.exec("rollback");
|
|
47
|
+
throw cause;
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
setting(name) {
|
|
51
|
+
const row = get.get(name);
|
|
52
|
+
return row === undefined ? null : String(row["value"]);
|
|
53
|
+
},
|
|
54
|
+
set(name, value) {
|
|
55
|
+
if (value === null) forget.run(name);
|
|
56
|
+
else put.run(name, value);
|
|
57
|
+
},
|
|
58
|
+
close: () => db.close(),
|
|
59
|
+
};
|
|
60
|
+
}
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a device keeps: the lab's entries, and a few settings.
|
|
3
|
+
*
|
|
4
|
+
* The entries are the truth and everything shown is worked out from them, so a store has no table of
|
|
5
|
+
* items or amounts to fall out of step. Lose it, and the lab's web peer or any other member hands
|
|
6
|
+
* every entry back. Where it lives depends on the device, so it is an interface: a SQLite file on a
|
|
7
|
+
* desktop (`@biolibs/bionet-client/sqlite`), memory in a test, whatever a browser offers.
|
|
8
|
+
*/
|
|
9
|
+
import type { SignedEntry } from "@biolibs/bionet";
|
|
10
|
+
|
|
11
|
+
/** Where a device keeps things. */
|
|
12
|
+
export interface LabStore {
|
|
13
|
+
/** Every entry held. */
|
|
14
|
+
entries(): SignedEntry[];
|
|
15
|
+
/** Keep more entries, each with its ID. Adding one already held does nothing. */
|
|
16
|
+
add(entries: readonly { id: string; signed: SignedEntry }[]): void;
|
|
17
|
+
/** A setting, or `null` if it was never set. */
|
|
18
|
+
setting(name: string): string | null;
|
|
19
|
+
/** Set a setting. `null` forgets it. */
|
|
20
|
+
set(name: string, value: string | null): void;
|
|
21
|
+
/** Finish with the store. */
|
|
22
|
+
close(): void;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Where a device's private key lives. A desktop app gives one backed by the system's keychain. */
|
|
26
|
+
export interface KeyKeeper {
|
|
27
|
+
/** The key as `exportSigningKey` wrote it, or `null` if this device has none yet. */
|
|
28
|
+
load(): Promise<string | null>;
|
|
29
|
+
/** Keep a new key. */
|
|
30
|
+
save(exported: string): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* A store that lives in memory and is gone when the process is.
|
|
35
|
+
*
|
|
36
|
+
* @returns The store.
|
|
37
|
+
*/
|
|
38
|
+
export function memoryStore(): LabStore {
|
|
39
|
+
const held = new Map<string, SignedEntry>();
|
|
40
|
+
const settings = new Map<string, string>();
|
|
41
|
+
return {
|
|
42
|
+
entries: () => [...held.values()],
|
|
43
|
+
add: (entries) => { for (const { id, signed } of entries) if (!held.has(id)) held.set(id, signed); },
|
|
44
|
+
setting: (name) => settings.get(name) ?? null,
|
|
45
|
+
set: (name, value) => { if (value === null) settings.delete(name); else settings.set(name, value); },
|
|
46
|
+
close: () => {},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* A key kept in memory, for tests and for trying things out. A real device keeps its key somewhere
|
|
52
|
+
* the operating system guards.
|
|
53
|
+
*
|
|
54
|
+
* @returns The keeper.
|
|
55
|
+
*/
|
|
56
|
+
export function memoryKeys(): KeyKeeper {
|
|
57
|
+
let held: string | null = null;
|
|
58
|
+
return { load: async () => held, save: async (exported) => { held = exported; } };
|
|
59
|
+
}
|