@cero-base/core 2.6.0 → 2.8.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/package.json +1 -1
- package/src/database/index.js +41 -12
- package/src/database/rotation.js +2 -1
- package/src/lib/errors.js +8 -0
- package/src/lib/utils.js +4 -2
- package/src/network/index.js +4 -1
- package/src/pairing/invite.js +15 -0
- package/src/push/index.js +60 -2
- package/types/database/index.d.ts +3 -0
- package/types/lib/errors.d.ts +6 -0
- package/types/lib/utils.d.ts +1 -2
- package/types/push/index.d.ts +26 -1
package/package.json
CHANGED
package/src/database/index.js
CHANGED
|
@@ -107,6 +107,7 @@ export class Database extends ReadyResource {
|
|
|
107
107
|
/** @type {number | null} */
|
|
108
108
|
this.behind = null
|
|
109
109
|
this.namespace = opts.namespace || NAMESPACE
|
|
110
|
+
this._writable = false
|
|
110
111
|
this.encryptionKey = opts.encryptionKey
|
|
111
112
|
this.keyring = new Keyring()
|
|
112
113
|
if (opts.epochs) for (const e of opts.epochs) this.keyring.add(e.stamp, e.entropy, e.epoch)
|
|
@@ -186,7 +187,7 @@ export class Database extends ReadyResource {
|
|
|
186
187
|
|
|
187
188
|
/** @returns {boolean} whether the bee accepts local writes */
|
|
188
189
|
get writable() {
|
|
189
|
-
return this.
|
|
190
|
+
return this._writable
|
|
190
191
|
}
|
|
191
192
|
|
|
192
193
|
/** @returns {number} number of ops in the local writer */
|
|
@@ -228,9 +229,13 @@ export class Database extends ReadyResource {
|
|
|
228
229
|
|
|
229
230
|
// REMOVE-capable devices re-key when the epoch drifts from the member set
|
|
230
231
|
this.on('update', () => this.rotation.heal())
|
|
231
|
-
this.
|
|
232
|
+
this._writable = this.bee.writable
|
|
233
|
+
this.bee.on('writable', () => this._onwritable())
|
|
232
234
|
// falling edge: apps freeze the UI the moment access ends
|
|
233
|
-
this.bee.on('unwritable', () =>
|
|
235
|
+
this.bee.on('unwritable', () => {
|
|
236
|
+
this._writable = false
|
|
237
|
+
this.emit('unwritable')
|
|
238
|
+
})
|
|
234
239
|
// without a listener autobee escalates apply/view errors to a process crash
|
|
235
240
|
this.bee.on('error', this._onerror)
|
|
236
241
|
|
|
@@ -417,6 +422,9 @@ export class Database extends ReadyResource {
|
|
|
417
422
|
* @returns {Promise<void>}
|
|
418
423
|
*/
|
|
419
424
|
async write(ops) {
|
|
425
|
+
// behind, a set merges from a view missing the newer writes and every device takes the stale
|
|
426
|
+
// row: no writes until the update, but leaving, which touches nothing else
|
|
427
|
+
if (this.behind !== null && !leaving(ops, this.identity.id)) throw CeroError.BEHIND(this.behind)
|
|
420
428
|
if (this.txQueue) {
|
|
421
429
|
for (const op of ops) this.txQueue.push(op)
|
|
422
430
|
return
|
|
@@ -637,12 +645,11 @@ export class Database extends ReadyResource {
|
|
|
637
645
|
*/
|
|
638
646
|
async whenWritable({ timeout = 30000 } = {}) {
|
|
639
647
|
this.guard()
|
|
640
|
-
|
|
641
|
-
if (bee.writable) return
|
|
648
|
+
if (this.writable) return
|
|
642
649
|
return new Promise((resolve, reject) => {
|
|
643
650
|
const done = (err) => {
|
|
644
651
|
clearTimeout(timer)
|
|
645
|
-
|
|
652
|
+
this.off('writable', done)
|
|
646
653
|
this.off('close', onclose)
|
|
647
654
|
if (err) reject(err)
|
|
648
655
|
else resolve()
|
|
@@ -650,11 +657,25 @@ export class Database extends ReadyResource {
|
|
|
650
657
|
const onclose = () => done(CeroError.CLOSED('Database'))
|
|
651
658
|
const timer =
|
|
652
659
|
timeout > 0 ? setTimeout(() => done(CeroError.TIMEOUT('whenWritable')), timeout) : null
|
|
653
|
-
|
|
660
|
+
this.once('writable', done)
|
|
654
661
|
this.once('close', onclose)
|
|
655
662
|
})
|
|
656
663
|
}
|
|
657
664
|
|
|
665
|
+
// the bee flips writable inside the apply that admits this device, before that apply's view
|
|
666
|
+
// flush lands its row: writable here means the row is there to read
|
|
667
|
+
/** @private */
|
|
668
|
+
async _onwritable() {
|
|
669
|
+
try {
|
|
670
|
+
await this.bee.updated()
|
|
671
|
+
} catch {
|
|
672
|
+
return
|
|
673
|
+
}
|
|
674
|
+
if (this._writable || !this.bee.writable || this.closing || this.closed) return
|
|
675
|
+
this._writable = true
|
|
676
|
+
this.emit('writable')
|
|
677
|
+
}
|
|
678
|
+
|
|
658
679
|
/**
|
|
659
680
|
* Learn epochs handed over after the open, as a root carries them for a handle. One is kept
|
|
660
681
|
* once its announcement applied here and the secret meets the commitment it carries: hand them
|
|
@@ -763,14 +784,22 @@ export class Database extends ReadyResource {
|
|
|
763
784
|
await bee.update()
|
|
764
785
|
}
|
|
765
786
|
|
|
766
|
-
// ops skipped as too new apply once this version caught up
|
|
787
|
+
// ops skipped as too new apply once this version caught up, and a view whose definition grew
|
|
788
|
+
// since it was built (an index added by a rebuild) fills from the log: wipe the boot record and
|
|
789
|
+
// reboot
|
|
767
790
|
/** @private */
|
|
768
791
|
async _replay() {
|
|
769
|
-
const
|
|
792
|
+
const local = this.bee.local
|
|
793
|
+
const behind = await local.getUserData('cero/behind')
|
|
770
794
|
this.behind = behind ? c.decode(c.uint, behind) : null
|
|
771
|
-
|
|
772
|
-
await
|
|
773
|
-
|
|
795
|
+
const caught = this.behind !== null && this.behind <= this.version
|
|
796
|
+
const built = await local.getUserData('cero/view')
|
|
797
|
+
const { db } = this.spec.database.versions
|
|
798
|
+
const grown = !!built && c.decode(c.uint, built) < db
|
|
799
|
+
if (!built || grown) await local.setUserData('cero/view', c.encode(c.uint, db))
|
|
800
|
+
if (!caught && !grown) return false
|
|
801
|
+
await local.setUserData('autobee/head', null)
|
|
802
|
+
await local.setUserData('cero/behind', null)
|
|
774
803
|
await this.bee.close()
|
|
775
804
|
this.behind = null
|
|
776
805
|
return true
|
package/src/database/rotation.js
CHANGED
|
@@ -204,7 +204,8 @@ export class Rotation {
|
|
|
204
204
|
/** @private */
|
|
205
205
|
async _audit() {
|
|
206
206
|
const db = this.db
|
|
207
|
-
|
|
207
|
+
// behind, the membership this device sees is stale: the devices that read everything re-key
|
|
208
|
+
if (db.closing || db.closed || !db.writable || this.current || db.behind !== null) return
|
|
208
209
|
const { data: device } = await db.get('devices', hid.encode(db.writerKey))
|
|
209
210
|
const me = device?.memberId ? (await db.get('members', device.memberId)).data : null
|
|
210
211
|
if (!can(me?.role, REMOVE)) return
|
package/src/lib/errors.js
CHANGED
|
@@ -102,6 +102,14 @@ export class CeroError extends Error {
|
|
|
102
102
|
static NOT_WRITABLE(resource) {
|
|
103
103
|
return new CeroError('NOT_WRITABLE', `${resource} is not writable`)
|
|
104
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* This device skipped writes from a newer app version: it reads, but writes wait for the update.
|
|
107
|
+
*
|
|
108
|
+
* @param {number} version
|
|
109
|
+
*/
|
|
110
|
+
static BEHIND(version) {
|
|
111
|
+
return new CeroError('BEHIND', `behind app version ${version}: update to write`)
|
|
112
|
+
}
|
|
105
113
|
/**
|
|
106
114
|
* Async operation exceeded its deadline.
|
|
107
115
|
*
|
package/src/lib/utils.js
CHANGED
|
@@ -122,10 +122,12 @@ const fold = (s) =>
|
|
|
122
122
|
|
|
123
123
|
// every term must be a substring of a searched field
|
|
124
124
|
/** @param {Record<string, unknown>} row @param {string} term @param {string[]} [fields] @returns {boolean} */
|
|
125
|
+
const IDS = new Set(['id', 'memberId'])
|
|
126
|
+
|
|
125
127
|
export function searchHit(row, term, fields) {
|
|
126
128
|
const terms = String(term).split(/\s+/).map(fold).filter(Boolean)
|
|
127
|
-
//
|
|
128
|
-
const keys = fields && fields.length ? fields : Object.keys(row).filter((k) => k
|
|
129
|
+
// ids are random z32: any term can occur in one
|
|
130
|
+
const keys = fields && fields.length ? fields : Object.keys(row).filter((k) => !IDS.has(k))
|
|
129
131
|
const hay = keys.map((k) => (typeof row[k] === 'string' ? fold(row[k]) : '')).join(' ')
|
|
130
132
|
return terms.every((t) => hay.includes(t))
|
|
131
133
|
}
|
package/src/network/index.js
CHANGED
|
@@ -362,9 +362,12 @@ export class Network extends ReadyResource {
|
|
|
362
362
|
}
|
|
363
363
|
|
|
364
364
|
// data, not packets: a peer that acked our opener and froze has answered nothing
|
|
365
|
+
// silent since we got it: a direct connection carries its handshake on the stream, so the count
|
|
366
|
+
// starts above zero
|
|
365
367
|
function dropIfSilent(conn) {
|
|
368
|
+
const seen = conn.rawStream.bytesReceived
|
|
366
369
|
const timer = setTimeout(() => {
|
|
367
|
-
if (conn.rawStream.bytesReceived ===
|
|
370
|
+
if (conn.rawStream.bytesReceived === seen) conn.destroy()
|
|
368
371
|
}, SILENT_TIMEOUT)
|
|
369
372
|
timer.unref()
|
|
370
373
|
conn.once('close', () => clearTimeout(timer))
|
package/src/pairing/invite.js
CHANGED
|
@@ -101,6 +101,7 @@ export class Invite {
|
|
|
101
101
|
static create({ ttl = 0, key, address, link = null, data = null }) {
|
|
102
102
|
if (key?.byteLength !== 32) throw CeroError.INVALID('key must be a 32-byte buffer')
|
|
103
103
|
if (address?.byteLength !== 32) throw CeroError.INVALID('address must be a 32-byte buffer')
|
|
104
|
+
if (!sealable(address)) throw CeroError.INVALID('address cannot be sealed to')
|
|
104
105
|
const expires = ttl ? Date.now() + toMs(ttl) : 0
|
|
105
106
|
if (data !== null && !b4a.isBuffer(data)) throw CeroError.INVALID('data must be a buffer')
|
|
106
107
|
return new Invite({
|
|
@@ -128,10 +129,24 @@ export class Invite {
|
|
|
128
129
|
throw CeroError.INVALID_INVITE('not an invite')
|
|
129
130
|
}
|
|
130
131
|
if (fields.version !== VERSION) throw CeroError.INVALID_INVITE('unknown invite version')
|
|
132
|
+
if (!sealable(fields.address)) throw CeroError.INVALID_INVITE('address cannot be sealed to')
|
|
131
133
|
return new Invite({ ...fields, _str: str })
|
|
132
134
|
}
|
|
133
135
|
}
|
|
134
136
|
|
|
137
|
+
// a join is sealed to the address: a point nothing seals to (all zeros, a low-order one) would
|
|
138
|
+
// fail every join as a network error
|
|
139
|
+
function sealable(address) {
|
|
140
|
+
try {
|
|
141
|
+
crypto.encrypt(EMPTY, address)
|
|
142
|
+
return true
|
|
143
|
+
} catch {
|
|
144
|
+
return false
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const EMPTY = b4a.alloc(0)
|
|
149
|
+
|
|
135
150
|
// ms, or a duration like '12h' or '2d'
|
|
136
151
|
function toMs(ttl) {
|
|
137
152
|
const value = typeof ttl === 'string' ? ms(ttl) : ttl
|
package/src/push/index.js
CHANGED
|
@@ -1,10 +1,19 @@
|
|
|
1
1
|
import { decode, readNotification } from 'blind-push'
|
|
2
2
|
import crypto from 'hypercore-crypto'
|
|
3
3
|
import b4a from 'b4a'
|
|
4
|
+
import autobeeEncryption from 'autobee/lib/encryption.js'
|
|
5
|
+
import autobeeEncoding from 'autobee/lib/encoding.js'
|
|
6
|
+
|
|
7
|
+
import { Keyring } from '../database/encryption.js'
|
|
8
|
+
import { unwrap } from '../database/envelope.js'
|
|
9
|
+
|
|
10
|
+
const { AutobeeEncryption, WriterEncryption } = autobeeEncryption
|
|
11
|
+
const { decodeOplog } = autobeeEncoding
|
|
4
12
|
|
|
5
13
|
/**
|
|
6
14
|
* @typedef {{ id: string, key: Uint8Array }} Handle A handle this device holds: its id and its database key.
|
|
7
|
-
* @typedef {
|
|
15
|
+
* @typedef {{ index: number, value: Uint8Array, writer: Uint8Array }} Block The block a push carries when it fits: its index, its bytes as the writer's core holds them, and the writer's key.
|
|
16
|
+
* @typedef {Handle & { length: number, newer: boolean, ref: string | null, block: Block | null }} Hit The handle a push is about, the length it proves, whether this device is behind it, the ref the write was on, and the block when it rode along.
|
|
8
17
|
*/
|
|
9
18
|
|
|
10
19
|
/**
|
|
@@ -33,5 +42,54 @@ export async function verify(storage, payload, handles) {
|
|
|
33
42
|
}
|
|
34
43
|
if (!read) return null
|
|
35
44
|
const ref = read.extra?.length ? b4a.toString(read.extra) : null
|
|
36
|
-
|
|
45
|
+
const { block, key: writer } = read.result
|
|
46
|
+
return {
|
|
47
|
+
...handle,
|
|
48
|
+
length: read.result.length,
|
|
49
|
+
newer: read.result.newer,
|
|
50
|
+
ref,
|
|
51
|
+
block: block?.value ? { index: block.index, value: block.value, writer } : null
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The op a push's block holds, for a device with the handle's keys: decrypted as the writer's
|
|
57
|
+
* core would, under the epoch the block names, and stripped of its envelope. Null when the push
|
|
58
|
+
* carried no block, the writer is not stored here, or the epoch is not among `epochs`.
|
|
59
|
+
*
|
|
60
|
+
* @param {import('hypercore-storage')} storage The same storage `verify` read.
|
|
61
|
+
* @param {Hit} hit
|
|
62
|
+
* @param {{ encryptionKey: Uint8Array, epochs?: Array<{ epoch: number, stamp: number, entropy: Uint8Array }> }} keys The handle's encryption key and the rotation epochs it has learned.
|
|
63
|
+
* @returns {Promise<Uint8Array | null>}
|
|
64
|
+
*/
|
|
65
|
+
export async function decrypt(storage, hit, { encryptionKey, epochs = [] }) {
|
|
66
|
+
if (!hit.block) return null
|
|
67
|
+
const core = await storage.resumeCore(crypto.discoveryKey(hit.block.writer))
|
|
68
|
+
if (!core) return null
|
|
69
|
+
const rx = core.read()
|
|
70
|
+
const auth = rx.getAuth()
|
|
71
|
+
rx.tryFlush()
|
|
72
|
+
const manifest = (await auth)?.manifest
|
|
73
|
+
if (!manifest) return null
|
|
74
|
+
const keyring = new Keyring()
|
|
75
|
+
for (const e of epochs) keyring.add(e.stamp, e.entropy, e.epoch)
|
|
76
|
+
const auto = {
|
|
77
|
+
key: hit.key,
|
|
78
|
+
encryptionKey,
|
|
79
|
+
getEntropy: (id) => {
|
|
80
|
+
const entropy = keyring.entropy(id)
|
|
81
|
+
if (!entropy) throw new Error(`unknown epoch ${id}`)
|
|
82
|
+
return entropy
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const value = b4a.from(hit.block.value)
|
|
86
|
+
try {
|
|
87
|
+
await new WriterEncryption(auto).decrypt(hit.block.index, value, {
|
|
88
|
+
key: hit.block.writer,
|
|
89
|
+
manifest
|
|
90
|
+
})
|
|
91
|
+
return unwrap(decodeOplog(value.subarray(AutobeeEncryption.PADDING)).value)?.body ?? null
|
|
92
|
+
} catch {
|
|
93
|
+
return null
|
|
94
|
+
}
|
|
37
95
|
}
|
|
@@ -234,6 +234,7 @@ export declare class Database extends ReadyResource {
|
|
|
234
234
|
/** @type {number | null} */
|
|
235
235
|
behind: number | null;
|
|
236
236
|
namespace: string;
|
|
237
|
+
_writable: boolean;
|
|
237
238
|
encryptionKey: Uint8Array<ArrayBufferLike>;
|
|
238
239
|
keyring: Keyring;
|
|
239
240
|
/** @private */
|
|
@@ -467,6 +468,8 @@ export declare class Database extends ReadyResource {
|
|
|
467
468
|
whenWritable({ timeout }?: {
|
|
468
469
|
timeout?: number;
|
|
469
470
|
}): Promise<void>;
|
|
471
|
+
/** @private */
|
|
472
|
+
private _onwritable;
|
|
470
473
|
/**
|
|
471
474
|
* Learn epochs handed over after the open, as a root carries them for a handle. One is kept
|
|
472
475
|
* once its announcement applied here and the secret meets the commitment it carries: hand them
|
package/types/lib/errors.d.ts
CHANGED
|
@@ -73,6 +73,12 @@ export declare class CeroError extends Error {
|
|
|
73
73
|
* @param {string} resource
|
|
74
74
|
*/
|
|
75
75
|
static NOT_WRITABLE(resource: string): CeroError;
|
|
76
|
+
/**
|
|
77
|
+
* This device skipped writes from a newer app version: it reads, but writes wait for the update.
|
|
78
|
+
*
|
|
79
|
+
* @param {number} version
|
|
80
|
+
*/
|
|
81
|
+
static BEHIND(version: number): CeroError;
|
|
76
82
|
/**
|
|
77
83
|
* Async operation exceeded its deadline.
|
|
78
84
|
*
|
package/types/lib/utils.d.ts
CHANGED
|
@@ -31,8 +31,7 @@ export declare function subscribe<T>({ get, watch }: {
|
|
|
31
31
|
get: () => Promise<T> | T;
|
|
32
32
|
watch: (fn: () => void) => (() => void) | void;
|
|
33
33
|
}): import('streamx').Readable<T>;
|
|
34
|
-
|
|
35
|
-
export declare function searchHit(row: Record<string, unknown>, term: string, fields?: string[]): boolean;
|
|
34
|
+
export declare function searchHit(row: any, term: any, fields: any): boolean;
|
|
36
35
|
/**
|
|
37
36
|
* The in-memory query grammar over rows: equality on any non-reserved field,
|
|
38
37
|
* id ranges, `search`, then `reverse` and `limit`.
|
package/types/push/index.d.ts
CHANGED
|
@@ -2,14 +2,21 @@ export type Handle = {
|
|
|
2
2
|
id: string;
|
|
3
3
|
key: Uint8Array;
|
|
4
4
|
};
|
|
5
|
+
export type Block = {
|
|
6
|
+
index: number;
|
|
7
|
+
value: Uint8Array;
|
|
8
|
+
writer: Uint8Array;
|
|
9
|
+
};
|
|
5
10
|
export type Hit = Handle & {
|
|
6
11
|
length: number;
|
|
7
12
|
newer: boolean;
|
|
8
13
|
ref: string | null;
|
|
14
|
+
block: Block | null;
|
|
9
15
|
};
|
|
10
16
|
/**
|
|
11
17
|
* @typedef {{ id: string, key: Uint8Array }} Handle A handle this device holds: its id and its database key.
|
|
12
|
-
* @typedef {
|
|
18
|
+
* @typedef {{ index: number, value: Uint8Array, writer: Uint8Array }} Block The block a push carries when it fits: its index, its bytes as the writer's core holds them, and the writer's key.
|
|
19
|
+
* @typedef {Handle & { length: number, newer: boolean, ref: string | null, block: Block | null }} Hit The handle a push is about, the length it proves, whether this device is behind it, the ref the write was on, and the block when it rode along.
|
|
13
20
|
*/
|
|
14
21
|
/**
|
|
15
22
|
* Verify a push payload against this device's storage: the one the gateway sent, decoded from the
|
|
@@ -21,3 +28,21 @@ export type Hit = Handle & {
|
|
|
21
28
|
* @returns {Promise<Hit | null>}
|
|
22
29
|
*/
|
|
23
30
|
export declare function verify(storage: import('hypercore-storage'), payload: Uint8Array, handles: Handle[]): Promise<Hit | null>;
|
|
31
|
+
/**
|
|
32
|
+
* The op a push's block holds, for a device with the handle's keys: decrypted as the writer's
|
|
33
|
+
* core would, under the epoch the block names, and stripped of its envelope. Null when the push
|
|
34
|
+
* carried no block, the writer is not stored here, or the epoch is not among `epochs`.
|
|
35
|
+
*
|
|
36
|
+
* @param {import('hypercore-storage')} storage The same storage `verify` read.
|
|
37
|
+
* @param {Hit} hit
|
|
38
|
+
* @param {{ encryptionKey: Uint8Array, epochs?: Array<{ epoch: number, stamp: number, entropy: Uint8Array }> }} keys The handle's encryption key and the rotation epochs it has learned.
|
|
39
|
+
* @returns {Promise<Uint8Array | null>}
|
|
40
|
+
*/
|
|
41
|
+
export declare function decrypt(storage: import('hypercore-storage'), hit: Hit, { encryptionKey, epochs }: {
|
|
42
|
+
encryptionKey: Uint8Array;
|
|
43
|
+
epochs?: Array<{
|
|
44
|
+
epoch: number;
|
|
45
|
+
stamp: number;
|
|
46
|
+
entropy: Uint8Array;
|
|
47
|
+
}>;
|
|
48
|
+
}): Promise<Uint8Array | null>;
|