@tik-choco/mistvault 0.0.0-stage → 0.3.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 +373 -0
- package/README.ja.md +164 -0
- package/README.md +221 -2
- package/README.zh.md +164 -0
- package/dist/appState.d.ts +24 -0
- package/dist/appState.js +20 -0
- package/dist/code.d.ts +7 -0
- package/dist/code.js +49 -0
- package/dist/controller.d.ts +55 -0
- package/dist/controller.js +74 -0
- package/dist/core/client.d.ts +112 -0
- package/dist/core/client.js +536 -0
- package/dist/core/crypto.d.ts +24 -0
- package/dist/core/crypto.js +185 -0
- package/dist/core/head.d.ts +54 -0
- package/dist/core/head.js +123 -0
- package/dist/core/parse.d.ts +1 -0
- package/dist/core/parse.js +1 -0
- package/dist/core/protocol.d.ts +74 -0
- package/dist/core/protocol.js +93 -0
- package/dist/elements/PanelElement.d.ts +30 -0
- package/dist/elements/PanelElement.js +56 -0
- package/dist/elements/RoomControls.d.ts +21 -0
- package/dist/elements/RoomControls.js +27 -0
- package/dist/elements/ScopeVaultPanelElement.d.ts +10 -0
- package/dist/elements/ScopeVaultPanelElement.js +27 -0
- package/dist/elements/VaultPanelElement.d.ts +39 -0
- package/dist/elements/VaultPanelElement.js +191 -0
- package/dist/elements/dom.d.ts +14 -0
- package/dist/elements/dom.js +58 -0
- package/dist/elements/index.d.ts +15 -0
- package/dist/elements/index.js +12 -0
- package/dist/i18n.d.ts +132 -0
- package/dist/i18n.js +96 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +12 -0
- package/dist/parts.d.ts +42 -0
- package/dist/parts.js +267 -0
- package/dist/preact/ScopeVaultPanel.d.ts +10 -0
- package/dist/preact/ScopeVaultPanel.js +8 -0
- package/dist/preact/VaultPanel.d.ts +16 -0
- package/dist/preact/VaultPanel.js +14 -0
- package/dist/preact/index.d.ts +5 -0
- package/dist/preact/index.js +3 -0
- package/dist/preact/ui.css +132 -0
- package/dist/preact/useVault.d.ts +6 -0
- package/dist/preact/useVault.js +13 -0
- package/dist/scopeKey.d.ts +1 -0
- package/dist/scopeKey.js +49 -0
- package/dist/scopeManager.d.ts +14 -0
- package/dist/scopeManager.js +110 -0
- package/dist/scopeVault.d.ts +39 -0
- package/dist/scopeVault.js +212 -0
- package/dist/session.d.ts +44 -0
- package/dist/session.js +736 -0
- package/dist/settings.d.ts +21 -0
- package/dist/settings.js +59 -0
- package/dist/stored.d.ts +4 -0
- package/dist/stored.js +27 -0
- package/dist/transport.d.ts +20 -0
- package/dist/transport.js +117 -0
- package/package.json +57 -4
|
@@ -0,0 +1,536 @@
|
|
|
1
|
+
import { DEFAULT_MAX_PLAINTEXT, decryptBlob, deriveEscrowKeys, encryptBlob, gunzip, gzip, sha256, supportsGzip } from './crypto.js';
|
|
2
|
+
import { buildHead, DEFAULT_MAX_BLOB, headHash, parseHead, safeInt, SLOT_RE, signDelete, verifyHead } from './head.js';
|
|
3
|
+
import { encodeEscrowMessage, parseEscrowMessage } from './protocol.js';
|
|
4
|
+
export class EscrowRequestError extends Error {
|
|
5
|
+
code;
|
|
6
|
+
constructor(code, message) { super(message); this.name = 'EscrowRequestError'; this.code = code; }
|
|
7
|
+
}
|
|
8
|
+
/** One handle owns one escrow room. Requests lazily join and discover providers. */
|
|
9
|
+
export class EscrowClient {
|
|
10
|
+
room;
|
|
11
|
+
transport;
|
|
12
|
+
options;
|
|
13
|
+
discovered = new Map();
|
|
14
|
+
// LRU favors recent heads of each slot; retained copies survive peer departures.
|
|
15
|
+
headProviders = new Map();
|
|
16
|
+
historyEvicted = false;
|
|
17
|
+
deleting = new Set();
|
|
18
|
+
pending = new Map();
|
|
19
|
+
subscriptions = [];
|
|
20
|
+
joining = null;
|
|
21
|
+
joined = false;
|
|
22
|
+
closed = false;
|
|
23
|
+
providerListeners = new Set();
|
|
24
|
+
closing = new Set();
|
|
25
|
+
constructor(transport, room, options = {}) {
|
|
26
|
+
if (!/^[A-Za-z0-9_./:-]{1,96}$/.test(room))
|
|
27
|
+
throw new Error('Invalid escrow room');
|
|
28
|
+
this.transport = transport;
|
|
29
|
+
this.room = room;
|
|
30
|
+
this.options = { maxBlob: DEFAULT_MAX_BLOB, maxPlaintext: DEFAULT_MAX_PLAINTEXT, getTimeoutMs: 4000, putTimeoutMs: 45000,
|
|
31
|
+
...options, canPut: options.canPut ?? (() => true) };
|
|
32
|
+
if (!safeInt(this.options.maxBlob, 28) || !safeInt(this.options.maxPlaintext, 0))
|
|
33
|
+
throw new Error('Invalid escrow limits');
|
|
34
|
+
this.timeout(this.options.getTimeoutMs);
|
|
35
|
+
this.timeout(this.options.putTimeoutMs);
|
|
36
|
+
}
|
|
37
|
+
get providers() {
|
|
38
|
+
return new Map(Array.from(this.discovered, ([id, info]) => [id, { ...info, ...(info.features ? { features: [...info.features] } : {}) }]));
|
|
39
|
+
}
|
|
40
|
+
join(retry = false) {
|
|
41
|
+
if (this.closed)
|
|
42
|
+
return Promise.reject(new EscrowRequestError('closed', 'Escrow client closed'));
|
|
43
|
+
if (retry && this.joined && this.joining && !this.discovered.size) {
|
|
44
|
+
for (const unsubscribe of this.subscriptions.splice(0))
|
|
45
|
+
unsubscribe();
|
|
46
|
+
this.transport.leave(this.room);
|
|
47
|
+
this.joining = null;
|
|
48
|
+
this.joined = false;
|
|
49
|
+
}
|
|
50
|
+
if (!this.joining) {
|
|
51
|
+
this.subscriptions.push(this.transport.onMessage(this.room, (id, bytes) => { void this.receive(id, bytes); }), this.transport.onPeer(this.room, (id, joined) => {
|
|
52
|
+
if (this.closed)
|
|
53
|
+
return;
|
|
54
|
+
if (joined) {
|
|
55
|
+
try {
|
|
56
|
+
this.send({ v: 1, type: 'escrow_hello' }, id);
|
|
57
|
+
}
|
|
58
|
+
catch { /* pending requests retain their timeout */ }
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
this.discovered.delete(id);
|
|
62
|
+
for (const cb of this.providerListeners)
|
|
63
|
+
cb();
|
|
64
|
+
for (const request of this.pending.values()) {
|
|
65
|
+
if (request.target === id) {
|
|
66
|
+
request.target = undefined;
|
|
67
|
+
this.dispatch(request);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}));
|
|
72
|
+
let timer;
|
|
73
|
+
let close;
|
|
74
|
+
const timeout = new Promise((_, reject) => {
|
|
75
|
+
timer = setTimeout(() => reject(new EscrowRequestError('timeout', 'Escrow join timed out')), this.options.putTimeoutMs);
|
|
76
|
+
close = () => reject(new EscrowRequestError('closed', 'Escrow client closed'));
|
|
77
|
+
this.closing.add(close);
|
|
78
|
+
});
|
|
79
|
+
const joined = Promise.resolve().then(() => this.transport.join(this.room))
|
|
80
|
+
.then(() => { if (this.closed)
|
|
81
|
+
this.transport.leave(this.room); });
|
|
82
|
+
this.joining = Promise.race([joined, timeout]).then(() => {
|
|
83
|
+
if (this.closed) {
|
|
84
|
+
this.transport.leave(this.room);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
this.joined = true;
|
|
88
|
+
this.send({ v: 1, type: 'escrow_hello' }, null);
|
|
89
|
+
}).catch(error => {
|
|
90
|
+
if (!this.closed) {
|
|
91
|
+
for (const unsubscribe of this.subscriptions.splice(0))
|
|
92
|
+
unsubscribe();
|
|
93
|
+
this.discovered.clear();
|
|
94
|
+
this.transport.leave(this.room);
|
|
95
|
+
this.joining = null;
|
|
96
|
+
this.joined = false;
|
|
97
|
+
const failure = new EscrowRequestError('transport', String(error));
|
|
98
|
+
for (const request of [...this.pending.values()])
|
|
99
|
+
request.finish(null, failure);
|
|
100
|
+
}
|
|
101
|
+
throw error;
|
|
102
|
+
}).finally(() => { clearTimeout(timer); this.closing.delete(close); });
|
|
103
|
+
}
|
|
104
|
+
return this.joining;
|
|
105
|
+
}
|
|
106
|
+
onProvider(cb) {
|
|
107
|
+
this.providerListeners.add(cb);
|
|
108
|
+
return () => { this.providerListeners.delete(cb); };
|
|
109
|
+
}
|
|
110
|
+
waitForProvider(timeoutMs = 20000) {
|
|
111
|
+
this.timeout(timeoutMs);
|
|
112
|
+
if (this.closed)
|
|
113
|
+
return Promise.reject(new EscrowRequestError('closed', 'Escrow client closed'));
|
|
114
|
+
if (this.discovered.size)
|
|
115
|
+
return Promise.resolve(true);
|
|
116
|
+
return new Promise((resolve, reject) => {
|
|
117
|
+
const finish = (found, error) => {
|
|
118
|
+
clearTimeout(timer);
|
|
119
|
+
off();
|
|
120
|
+
this.closing.delete(close);
|
|
121
|
+
if (error)
|
|
122
|
+
reject(error);
|
|
123
|
+
else
|
|
124
|
+
resolve(found);
|
|
125
|
+
};
|
|
126
|
+
const off = this.onProvider(() => { if (this.discovered.size)
|
|
127
|
+
finish(true); });
|
|
128
|
+
const close = () => finish(false, new EscrowRequestError('closed', 'Escrow client closed'));
|
|
129
|
+
const timer = setTimeout(() => finish(false), timeoutMs);
|
|
130
|
+
this.closing.add(close);
|
|
131
|
+
void this.join().catch(error => finish(false, error));
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
dispose() {
|
|
135
|
+
if (this.closed)
|
|
136
|
+
return;
|
|
137
|
+
this.closed = true;
|
|
138
|
+
for (const close of [...this.closing])
|
|
139
|
+
close();
|
|
140
|
+
this.providerListeners.clear();
|
|
141
|
+
for (const unsubscribe of this.subscriptions.splice(0))
|
|
142
|
+
unsubscribe();
|
|
143
|
+
for (const request of [...this.pending.values()])
|
|
144
|
+
request.finish(null, new EscrowRequestError('closed', 'Escrow client closed'));
|
|
145
|
+
this.discovered.clear();
|
|
146
|
+
this.headProviders.clear();
|
|
147
|
+
this.transport.leave(this.room);
|
|
148
|
+
}
|
|
149
|
+
getHead(slot, timeoutMs = this.options.getTimeoutMs) {
|
|
150
|
+
if (!SLOT_RE.test(slot))
|
|
151
|
+
return Promise.reject(new Error('Invalid escrow slot'));
|
|
152
|
+
return this.request({ v: 1, type: 'escrow_get', id: crypto.randomUUID(), slot }, timeoutMs);
|
|
153
|
+
}
|
|
154
|
+
async put(head, timeoutMs = this.options.putTimeoutMs, signal) {
|
|
155
|
+
const parsed = parseHead(head, this.options);
|
|
156
|
+
if (!parsed || !await verifyHead(parsed, { ...this.options, slot: parsed.slot, writer: parsed.writer }))
|
|
157
|
+
return { type: 'error', code: 'bad_sig', message: 'Invalid escrow head' };
|
|
158
|
+
const hash = await headHash(parsed, this.options);
|
|
159
|
+
return this.request({ v: 1, type: 'escrow_put', id: crypto.randomUUID(), head: parsed }, timeoutMs, hash, undefined, undefined, signal);
|
|
160
|
+
}
|
|
161
|
+
async deleteSlot(app, input, current) {
|
|
162
|
+
if (this.closed)
|
|
163
|
+
return { type: 'error', code: 'closed', message: 'Escrow client closed' };
|
|
164
|
+
return this.deleteWithKeys(await deriveEscrowKeys(app, input), current);
|
|
165
|
+
}
|
|
166
|
+
async deleteWithKeys(keys, current) {
|
|
167
|
+
if (this.closed)
|
|
168
|
+
return { type: 'error', code: 'closed', message: 'Escrow client closed' };
|
|
169
|
+
if (!await verifyHead(current, { ...this.options, slot: keys.slot, writer: keys.writer }))
|
|
170
|
+
return { type: 'error', code: 'bad_sig', message: 'Invalid escrow head' };
|
|
171
|
+
const fields = await signDelete(current, keys, this.options);
|
|
172
|
+
if (this.closed)
|
|
173
|
+
return { type: 'error', code: 'closed', message: 'Escrow client closed' };
|
|
174
|
+
try {
|
|
175
|
+
await this.join();
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
return { type: 'error', code: 'transport', message: String(error) };
|
|
179
|
+
}
|
|
180
|
+
if (this.closed)
|
|
181
|
+
return { type: 'error', code: 'closed', message: 'Escrow client closed' };
|
|
182
|
+
const provenance = this.headProviders.get(fields.head);
|
|
183
|
+
if (provenance) {
|
|
184
|
+
this.headProviders.delete(fields.head);
|
|
185
|
+
this.headProviders.set(fields.head, provenance);
|
|
186
|
+
}
|
|
187
|
+
if (this.deleting.has(fields.head) || [...this.pending.values()].some(request => request.message.type === 'escrow_put' && request.expectedHash === fields.head))
|
|
188
|
+
return { type: 'error', code: 'busy', message: 'Escrow head mutation already in progress' };
|
|
189
|
+
this.deleting.add(fields.head);
|
|
190
|
+
try {
|
|
191
|
+
const broadcast = !provenance || provenance.broadcast || !provenance.complete;
|
|
192
|
+
const targets = new Set(provenance?.providers);
|
|
193
|
+
if (broadcast)
|
|
194
|
+
for (const [id, provider] of this.discovered) {
|
|
195
|
+
if (provider.features?.includes('delete'))
|
|
196
|
+
targets.add(id);
|
|
197
|
+
}
|
|
198
|
+
if (!targets.size)
|
|
199
|
+
return this.discovered.size
|
|
200
|
+
? { type: 'unsupported', message: 'No known provider supports slot deletion' }
|
|
201
|
+
: { type: 'error', code: 'transport', message: 'No known providers; deletion cannot be confirmed' };
|
|
202
|
+
const providers = [...targets];
|
|
203
|
+
const results = await Promise.all(providers.map(provider => this.request({ v: 1, type: 'escrow_delete', id: crypto.randomUUID(), ...fields }, this.options.putTimeoutMs, undefined, keys.writer, provider)));
|
|
204
|
+
const failure = results.find(result => result.type !== 'deleted');
|
|
205
|
+
if (failure)
|
|
206
|
+
return failure;
|
|
207
|
+
if (this.historyEvicted && (!provenance || provenance.broadcast))
|
|
208
|
+
return { type: 'error', code: 'transport', message: 'Escrow head provenance was evicted; deletion cannot be confirmed' };
|
|
209
|
+
const latest = this.headProviders.get(fields.head);
|
|
210
|
+
if ((provenance && latest !== provenance) || (latest && (!latest.complete || [...latest.providers].some(id => !targets.has(id))))
|
|
211
|
+
|| (broadcast && [...this.discovered].some(([id, provider]) => provider.features?.includes('delete') && !targets.has(id))))
|
|
212
|
+
return { type: 'error', code: 'transport', message: 'Escrow head provider tracking changed or incomplete; retry deletion' };
|
|
213
|
+
return { type: 'deleted' };
|
|
214
|
+
}
|
|
215
|
+
finally {
|
|
216
|
+
this.deleting.delete(fields.head);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
fetchLatest(app, roomId, timeoutMs = 60000) {
|
|
220
|
+
return this.fetchWithKeySource(() => deriveEscrowKeys(app, roomId), timeoutMs);
|
|
221
|
+
}
|
|
222
|
+
fetchLatestWithKeys(keys, timeoutMs = 60000) {
|
|
223
|
+
return this.fetchWithKeySource(() => Promise.resolve(keys), timeoutMs, true);
|
|
224
|
+
}
|
|
225
|
+
fetchWithKeySource(source, timeoutMs, managed = false) {
|
|
226
|
+
this.timeout(timeoutMs);
|
|
227
|
+
return new Promise((resolve, reject) => {
|
|
228
|
+
let active = true;
|
|
229
|
+
const deadline = Date.now() + timeoutMs;
|
|
230
|
+
const close = () => finish(new EscrowRequestError('closed', 'Escrow client closed'));
|
|
231
|
+
const finish = (error, value) => {
|
|
232
|
+
if (!active)
|
|
233
|
+
return;
|
|
234
|
+
active = false;
|
|
235
|
+
clearTimeout(timer);
|
|
236
|
+
this.closing.delete(close);
|
|
237
|
+
if (error)
|
|
238
|
+
reject(error);
|
|
239
|
+
else
|
|
240
|
+
resolve(value ?? null);
|
|
241
|
+
};
|
|
242
|
+
const timer = setTimeout(() => finish(new EscrowRequestError('timeout', 'Escrow restore timed out')), timeoutMs);
|
|
243
|
+
this.closing.add(close);
|
|
244
|
+
void this.downloadLatest(source, deadline, () => active, managed).then(value => finish(undefined, value), finish);
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
async downloadLatest(source, deadline, active, managed) {
|
|
248
|
+
const keys = await source();
|
|
249
|
+
let reported = false;
|
|
250
|
+
const remaining = () => {
|
|
251
|
+
if (this.closed || !active())
|
|
252
|
+
throw new EscrowRequestError('closed', 'Escrow restore stopped');
|
|
253
|
+
const ms = deadline - Date.now();
|
|
254
|
+
if (ms <= 0)
|
|
255
|
+
throw new EscrowRequestError('timeout', 'Escrow restore timed out');
|
|
256
|
+
return ms;
|
|
257
|
+
};
|
|
258
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
259
|
+
try {
|
|
260
|
+
const head = await this.getHead(keys.slot, Math.min(this.options.getTimeoutMs, remaining()));
|
|
261
|
+
if (!head)
|
|
262
|
+
return null;
|
|
263
|
+
reported = true;
|
|
264
|
+
if (!await verifyHead(head, { ...this.options, slot: keys.slot, writer: keys.writer }))
|
|
265
|
+
throw new Error('Escrow head verification failed');
|
|
266
|
+
const ms = Math.min(30000 / 2 ** attempt, remaining());
|
|
267
|
+
const blob = await new Promise((resolve, reject) => {
|
|
268
|
+
const finish = (value, error) => {
|
|
269
|
+
clearTimeout(timer);
|
|
270
|
+
this.closing.delete(close);
|
|
271
|
+
if (error)
|
|
272
|
+
reject(error);
|
|
273
|
+
else
|
|
274
|
+
resolve(value);
|
|
275
|
+
};
|
|
276
|
+
const close = () => finish(undefined, new EscrowRequestError('closed', 'Escrow client closed'));
|
|
277
|
+
const timer = setTimeout(() => finish(undefined, new EscrowRequestError('timeout', 'Escrow download timed out')), ms);
|
|
278
|
+
if (managed)
|
|
279
|
+
this.closing.add(close);
|
|
280
|
+
void this.transport.storageGet(head.cid).then(value => finish(value), error => finish(undefined, error));
|
|
281
|
+
});
|
|
282
|
+
remaining();
|
|
283
|
+
if (blob.byteLength !== head.size || await sha256(blob) !== head.sha256)
|
|
284
|
+
throw new Error('Escrow blob hash or size mismatch');
|
|
285
|
+
const decrypted = await decryptBlob(keys.encKey, keys.slot, head.seq, blob);
|
|
286
|
+
const plaintext = head.comp === 'gzip' ? await gunzip(decrypted, this.options.maxPlaintext) : decrypted;
|
|
287
|
+
if (plaintext.byteLength > this.options.maxPlaintext)
|
|
288
|
+
throw new Error('Escrow plaintext exceeds limit');
|
|
289
|
+
remaining();
|
|
290
|
+
return { head, plaintext };
|
|
291
|
+
}
|
|
292
|
+
catch (error) {
|
|
293
|
+
if (!reported || attempt === 2 || this.closed || !active())
|
|
294
|
+
throw error;
|
|
295
|
+
await new Promise((resolve, reject) => {
|
|
296
|
+
const close = () => { clearTimeout(timer); this.closing.delete(close); reject(new EscrowRequestError('closed', 'Escrow client closed')); };
|
|
297
|
+
const timer = setTimeout(() => { this.closing.delete(close); resolve(); }, Math.min(250 * 2 ** attempt, remaining()));
|
|
298
|
+
if (managed)
|
|
299
|
+
this.closing.add(close);
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
throw new Error('Escrow restore retries exhausted');
|
|
304
|
+
}
|
|
305
|
+
async saveCheckpoint(app, roomId, plaintext, options) {
|
|
306
|
+
return this.saveWithKeySource(() => deriveEscrowKeys(app, roomId), plaintext, options);
|
|
307
|
+
}
|
|
308
|
+
async saveWithKeys(input, plaintext, options) {
|
|
309
|
+
return this.saveWithKeySource(() => Promise.resolve(input), plaintext, options);
|
|
310
|
+
}
|
|
311
|
+
async saveWithKeySource(source, plaintext, options) {
|
|
312
|
+
if (plaintext.byteLength > this.options.maxPlaintext)
|
|
313
|
+
throw new Error('Escrow plaintext exceeds limit');
|
|
314
|
+
if (this.closed || options.signal?.aborted)
|
|
315
|
+
return { type: 'error', code: this.closed ? 'closed' : 'timeout', message: 'Escrow save cancelled' };
|
|
316
|
+
const ms = options.timeoutMs ?? this.options.putTimeoutMs;
|
|
317
|
+
this.timeout(ms);
|
|
318
|
+
const abort = new AbortController(), end = Date.now() + ms;
|
|
319
|
+
const cancel = () => abort.abort(new EscrowRequestError('timeout', 'Escrow save cancelled'));
|
|
320
|
+
const close = () => abort.abort(new EscrowRequestError('closed', 'Escrow client closed'));
|
|
321
|
+
const timer = setTimeout(() => abort.abort(new EscrowRequestError('timeout', 'Escrow save timed out')), ms);
|
|
322
|
+
this.closing.add(close);
|
|
323
|
+
options.signal?.addEventListener('abort', cancel, { once: true });
|
|
324
|
+
if (this.closed)
|
|
325
|
+
close();
|
|
326
|
+
else if (options.signal?.aborted)
|
|
327
|
+
cancel();
|
|
328
|
+
const check = () => {
|
|
329
|
+
if (!abort.signal.aborted && Date.now() >= end)
|
|
330
|
+
cancel();
|
|
331
|
+
if (abort.signal.aborted)
|
|
332
|
+
throw abort.signal.reason;
|
|
333
|
+
};
|
|
334
|
+
const cancelled = new Promise((_, reject) => {
|
|
335
|
+
if (abort.signal.aborted)
|
|
336
|
+
reject(abort.signal.reason);
|
|
337
|
+
else
|
|
338
|
+
abort.signal.addEventListener('abort', () => reject(abort.signal.reason), { once: true });
|
|
339
|
+
});
|
|
340
|
+
const wait = async (pending) => { const value = await Promise.race([pending, cancelled]); check(); return value; };
|
|
341
|
+
try {
|
|
342
|
+
check();
|
|
343
|
+
const keys = await wait(source());
|
|
344
|
+
const comp = options.comp ?? (supportsGzip() ? 'gzip' : 'none');
|
|
345
|
+
if (comp !== 'gzip' && comp !== 'none')
|
|
346
|
+
throw new Error('Invalid escrow compression');
|
|
347
|
+
const payload = comp === 'gzip' ? await wait(gzip(plaintext, this.options.maxBlob - 28)) : plaintext;
|
|
348
|
+
const blob = await wait(encryptBlob(keys.encKey, keys.slot, options.seq, payload));
|
|
349
|
+
if (blob.byteLength > this.options.maxBlob)
|
|
350
|
+
return { type: 'error', code: 'too_large', message: 'Escrow blob exceeds limit' };
|
|
351
|
+
// Validate metadata before any upload.
|
|
352
|
+
const fields = { seq: options.seq, parent: options.parent, schema: options.schema, comp, size: blob.byteLength, sha256: await wait(sha256(blob)) };
|
|
353
|
+
await wait(buildHead(keys, { ...fields, cid: 'pending' }, this.options));
|
|
354
|
+
await wait(this.join());
|
|
355
|
+
if (!this.options.canPut())
|
|
356
|
+
return { type: 'error', code: 'not_writer', message: 'Writer election changed' };
|
|
357
|
+
const cid = await wait(this.transport.storageAdd('tc-escrow.bin', blob));
|
|
358
|
+
const head = await wait(buildHead(keys, { ...fields, cid }, this.options));
|
|
359
|
+
return await wait(this.put(head, Math.max(1, end - Date.now()), abort.signal));
|
|
360
|
+
}
|
|
361
|
+
catch (error) {
|
|
362
|
+
if (error instanceof EscrowRequestError)
|
|
363
|
+
return { type: 'error', code: error.code, message: error.message };
|
|
364
|
+
throw error;
|
|
365
|
+
}
|
|
366
|
+
finally {
|
|
367
|
+
clearTimeout(timer);
|
|
368
|
+
this.closing.delete(close);
|
|
369
|
+
options.signal?.removeEventListener('abort', cancel);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
timeout(ms) {
|
|
373
|
+
if (!safeInt(ms, 1, 2147483647))
|
|
374
|
+
throw new Error('Invalid escrow timeout');
|
|
375
|
+
}
|
|
376
|
+
request(message, ms, hash, writer, pinnedTarget, signal) {
|
|
377
|
+
this.timeout(ms);
|
|
378
|
+
return new Promise((resolve, reject) => {
|
|
379
|
+
const cancel = () => request.finish(null, new EscrowRequestError('timeout', 'Escrow save cancelled'));
|
|
380
|
+
const request = {
|
|
381
|
+
message, expectedHash: hash, writer, pinnedTarget,
|
|
382
|
+
timer: setTimeout(() => request.finish(null, new EscrowRequestError('timeout', 'Escrow request timed out')), ms),
|
|
383
|
+
finish: (value, error) => {
|
|
384
|
+
if (!this.pending.delete(message.id))
|
|
385
|
+
return;
|
|
386
|
+
clearTimeout(request.timer);
|
|
387
|
+
signal?.removeEventListener('abort', cancel);
|
|
388
|
+
if (error) {
|
|
389
|
+
if (message.type !== 'escrow_get')
|
|
390
|
+
resolve({ type: 'error', code: error.code, message: error.message });
|
|
391
|
+
else
|
|
392
|
+
reject(error);
|
|
393
|
+
}
|
|
394
|
+
else
|
|
395
|
+
resolve(value);
|
|
396
|
+
},
|
|
397
|
+
};
|
|
398
|
+
this.pending.set(message.id, request);
|
|
399
|
+
signal?.addEventListener('abort', cancel, { once: true });
|
|
400
|
+
if (signal?.aborted) {
|
|
401
|
+
cancel();
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
if (this.closed) {
|
|
405
|
+
request.finish(null, new EscrowRequestError('closed', 'Escrow client closed'));
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
void this.join().then(() => {
|
|
409
|
+
if (this.pending.has(message.id))
|
|
410
|
+
this.dispatch(request);
|
|
411
|
+
}).catch(error => request.finish(null, new EscrowRequestError('transport', String(error))));
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
send(message, id) {
|
|
415
|
+
this.transport.send(this.room, id, encodeEscrowMessage(message, this.options));
|
|
416
|
+
}
|
|
417
|
+
dispatch(request) {
|
|
418
|
+
if (request.target || this.closed)
|
|
419
|
+
return;
|
|
420
|
+
const entries = [...this.discovered].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
421
|
+
const target = request.pinnedTarget
|
|
422
|
+
? entries.find(([id]) => id === request.pinnedTarget)
|
|
423
|
+
: entries.find(([, provider]) => request.message.type !== 'escrow_put' || provider.maxBlob >= request.message.head.size);
|
|
424
|
+
if (!target) {
|
|
425
|
+
if (entries.length && request.message.type === 'escrow_put')
|
|
426
|
+
request.finish(null, new EscrowRequestError('too_large', 'Provider blob limit exceeded'));
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
if (request.message.type === 'escrow_delete' && !target[1].features?.includes('delete')) {
|
|
430
|
+
request.finish({ type: 'unsupported', message: 'Provider does not support slot deletion' });
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
if (request.message.type !== 'escrow_get' && !this.options.canPut()) {
|
|
434
|
+
request.finish(null, new EscrowRequestError('not_writer', 'Writer election changed'));
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
if (request.message.type === 'escrow_put') {
|
|
438
|
+
if (this.deleting.has(request.expectedHash)) {
|
|
439
|
+
request.finish(null, new EscrowRequestError('busy', 'Escrow head deletion in progress'));
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
// Record before send: a throw, timeout or lost ACK does not prove non-storage.
|
|
443
|
+
this.rememberProvider(request.expectedHash, request.message.head.slot, target[0]);
|
|
444
|
+
}
|
|
445
|
+
request.target = target[0];
|
|
446
|
+
try {
|
|
447
|
+
this.send(request.message, target[0]);
|
|
448
|
+
}
|
|
449
|
+
catch (error) {
|
|
450
|
+
request.finish(null, new EscrowRequestError('transport', String(error)));
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
rememberProvider(hash, slot, provider) {
|
|
454
|
+
let provenance = this.headProviders.get(hash);
|
|
455
|
+
if (!provenance) {
|
|
456
|
+
if (this.headProviders.size >= 1024) {
|
|
457
|
+
// Rotate this slot's oldest generation first, preserving other slots' latest heads.
|
|
458
|
+
const entries = [...this.headProviders];
|
|
459
|
+
const sameSlot = entries.filter(([, entry]) => entry.slot === slot);
|
|
460
|
+
this.headProviders.delete((sameSlot.length ? sameSlot[0] : entries[0])[0]);
|
|
461
|
+
this.historyEvicted = true;
|
|
462
|
+
}
|
|
463
|
+
// Without unbounded tombstones, a rediscovered hash could have evicted copies.
|
|
464
|
+
provenance = { slot, providers: new Set(), complete: true, broadcast: this.historyEvicted };
|
|
465
|
+
}
|
|
466
|
+
this.headProviders.delete(hash);
|
|
467
|
+
this.headProviders.set(hash, provenance);
|
|
468
|
+
if (provenance.providers.has(provider))
|
|
469
|
+
return;
|
|
470
|
+
if (provenance.providers.size >= 64) {
|
|
471
|
+
provenance.complete = false;
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
provenance.providers.add(provider);
|
|
475
|
+
}
|
|
476
|
+
async receive(fromId, bytes) {
|
|
477
|
+
if (this.closed)
|
|
478
|
+
return;
|
|
479
|
+
const message = parseEscrowMessage(bytes, this.options);
|
|
480
|
+
if (!message)
|
|
481
|
+
return;
|
|
482
|
+
if (message.type === 'escrow_provider') {
|
|
483
|
+
this.discovered.set(fromId, { maxBlob: message.maxBlob, ...(message.features ? { features: [...message.features] } : {}) });
|
|
484
|
+
for (const cb of this.providerListeners)
|
|
485
|
+
cb();
|
|
486
|
+
for (const request of this.pending.values())
|
|
487
|
+
this.dispatch(request);
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
if (!this.discovered.has(fromId) || !('id' in message))
|
|
491
|
+
return;
|
|
492
|
+
const request = this.pending.get(message.id);
|
|
493
|
+
if (!request || request.target !== fromId)
|
|
494
|
+
return;
|
|
495
|
+
const slot = request.message.type === 'escrow_put' ? request.message.head.slot : request.message.slot;
|
|
496
|
+
if (message.type === 'escrow_head' && request.message.type === 'escrow_get' && message.slot === slot) {
|
|
497
|
+
const hash = message.head && await verifyHead(message.head, { ...this.options, slot, writer: message.head.writer })
|
|
498
|
+
? await headHash(message.head, this.options) : null;
|
|
499
|
+
if (this.pending.get(message.id) !== request || request.target !== fromId || !this.discovered.has(fromId))
|
|
500
|
+
return;
|
|
501
|
+
if (hash)
|
|
502
|
+
this.rememberProvider(hash, slot, fromId);
|
|
503
|
+
request.finish(message.head);
|
|
504
|
+
}
|
|
505
|
+
else if (message.type === 'escrow_ack' && request.message.type === 'escrow_put') {
|
|
506
|
+
const ack = message;
|
|
507
|
+
if (ack.slot === slot && ack.seq === request.message.head.seq && ack.hash === request.expectedHash) {
|
|
508
|
+
request.finish({ type: 'ack', slot, seq: ack.seq, hash: ack.hash, head: request.message.head });
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
else if (message.type === 'escrow_deleted' && request.message.type === 'escrow_delete' && message.slot === slot) {
|
|
512
|
+
request.finish({ type: 'deleted' });
|
|
513
|
+
}
|
|
514
|
+
else if (message.type === 'escrow_error') {
|
|
515
|
+
if (message.code === 'conflict') {
|
|
516
|
+
if (request.message.type === 'escrow_get')
|
|
517
|
+
return;
|
|
518
|
+
const writer = request.message.type === 'escrow_put' ? request.message.head.writer : request.writer;
|
|
519
|
+
if (message.head && !await verifyHead(message.head, { ...this.options, slot, writer }))
|
|
520
|
+
return;
|
|
521
|
+
if (this.pending.get(message.id) !== request || request.target !== fromId || !this.discovered.has(fromId))
|
|
522
|
+
return;
|
|
523
|
+
request.finish({ type: 'conflict', head: message.head });
|
|
524
|
+
}
|
|
525
|
+
else if (message.code === 'deleted' && request.message.type === 'escrow_put') {
|
|
526
|
+
if (message.head && !await verifyHead(message.head, { ...this.options, slot, writer: request.message.head.writer }))
|
|
527
|
+
return;
|
|
528
|
+
if (this.pending.get(message.id) !== request || request.target !== fromId || !this.discovered.has(fromId))
|
|
529
|
+
return;
|
|
530
|
+
request.finish({ type: 'error', code: message.code, message: message.message, ...(message.head ? { head: message.head } : {}) });
|
|
531
|
+
}
|
|
532
|
+
else
|
|
533
|
+
request.finish(null, new EscrowRequestError(message.code, message.message));
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export declare const utf8: (value: string) => Uint8Array<ArrayBuffer>;
|
|
2
|
+
export declare const hex: (bytes: Uint8Array) => string;
|
|
3
|
+
export declare const fromHex: (value: string) => Uint8Array<ArrayBuffer>;
|
|
4
|
+
export declare function base64url(bytes: Uint8Array): string;
|
|
5
|
+
export declare function fromBase64url(value: string): Uint8Array<ArrayBuffer>;
|
|
6
|
+
export declare const sha256: (bytes: Uint8Array) => Promise<string>;
|
|
7
|
+
export interface EscrowKeys {
|
|
8
|
+
readonly slot: string;
|
|
9
|
+
readonly encKey: CryptoKey;
|
|
10
|
+
readonly writer: string;
|
|
11
|
+
sign(bytes: Uint8Array): Promise<Uint8Array<ArrayBuffer>>;
|
|
12
|
+
}
|
|
13
|
+
export declare function deriveEscrowKeys(app: string, roomId: string): Promise<EscrowKeys>;
|
|
14
|
+
export declare function deriveAutoRoom(app: string, roomId: string): Promise<string>;
|
|
15
|
+
export declare function blobAAD(slot: string, seq: number): Uint8Array<ArrayBuffer>;
|
|
16
|
+
export declare function encryptBlob(encKey: CryptoKey, slot: string, seq: number, plaintext: Uint8Array): Promise<Uint8Array<ArrayBuffer>>;
|
|
17
|
+
export declare function decryptBlob(encKey: CryptoKey, slot: string, seq: number, blob: Uint8Array): Promise<Uint8Array<ArrayBuffer>>;
|
|
18
|
+
export declare const DEFAULT_MAX_PLAINTEXT: number;
|
|
19
|
+
export declare const PART_ID_RE: RegExp;
|
|
20
|
+
/** Part slots share the main slot's cached PBKDF2 master. */
|
|
21
|
+
export declare function derivePartKeys(app: string, vaultCode: string, part: string): Promise<EscrowKeys>;
|
|
22
|
+
export declare const supportsGzip: () => boolean;
|
|
23
|
+
export declare function gzip(bytes: Uint8Array, maxBytes?: number): Promise<Uint8Array<ArrayBuffer>>;
|
|
24
|
+
export declare function gunzip(bytes: Uint8Array, maxBytes?: number): Promise<Uint8Array<ArrayBuffer>>;
|