@cero-base/core 1.17.0 → 1.18.1
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 +10 -9
- package/src/blobs/codec.js +2 -1
- package/src/database/dispatch.js +41 -1
- package/src/database/encryption.js +5 -3
- package/src/database/hooks.js +112 -0
- package/src/database/index.js +71 -467
- package/src/database/membership.js +67 -0
- package/src/database/rotation.js +228 -0
- package/src/lib/utils.js +19 -6
- package/src/network/index.js +68 -2
- package/src/pairing/index.js +3 -3
- package/src/pairing/invite.js +4 -2
- package/src/storage/index.js +12 -6
- package/types/database/encryption.d.ts +1 -1
- package/types/database/hooks.d.ts +8 -0
- package/types/database/index.d.ts +8 -56
- package/types/database/membership.d.ts +7 -0
- package/types/database/rotation.d.ts +32 -0
- package/types/lib/utils.d.ts +6 -7
- package/types/network/index.d.ts +19 -0
- package/types/pairing/index.d.ts +1 -1
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { CeroError } from '../lib/errors.js'
|
|
2
|
+
import { claimWriterPayload } from '../lib/utils.js'
|
|
3
|
+
import { wrap } from './envelope.js'
|
|
4
|
+
|
|
5
|
+
export async function claim(db) {
|
|
6
|
+
db.guard()
|
|
7
|
+
if (db.bee.writable) return
|
|
8
|
+
await db.bee.append(wrap(db.version, db.claimOp()), { optimistic: true })
|
|
9
|
+
await db.bee.update()
|
|
10
|
+
if (!db.bee.writable) await db.whenWritable()
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function claimOp(db) {
|
|
14
|
+
const writerKey = db.writerKey
|
|
15
|
+
return db.spec.dispatch.encode(`@${db.ns}/claim-writer`, {
|
|
16
|
+
identity: db.identity.publicKey,
|
|
17
|
+
writer: writerKey,
|
|
18
|
+
sig: db.identity.sign(claimWriterPayload(db.key, writerKey)),
|
|
19
|
+
ts: Date.now()
|
|
20
|
+
})
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function whenWritable(db, { timeout = 30000 } = {}) {
|
|
24
|
+
db.guard()
|
|
25
|
+
if (db.bee.writable) return
|
|
26
|
+
return new Promise((resolve, reject) => {
|
|
27
|
+
let timer = null
|
|
28
|
+
let pollTimer = null
|
|
29
|
+
let done = false
|
|
30
|
+
|
|
31
|
+
const finish = (err) => {
|
|
32
|
+
if (done) return
|
|
33
|
+
done = true
|
|
34
|
+
if (timer) clearTimeout(timer)
|
|
35
|
+
if (pollTimer) clearInterval(pollTimer)
|
|
36
|
+
if (db.bee) db.bee.off('writable', onWritable)
|
|
37
|
+
db.off('close', onClose)
|
|
38
|
+
if (err) reject(err)
|
|
39
|
+
else resolve()
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const onWritable = () => finish()
|
|
43
|
+
const onClose = () => finish(CeroError.CLOSED('Database'))
|
|
44
|
+
const poll = async () => {
|
|
45
|
+
if (done || !db.bee) return
|
|
46
|
+
try {
|
|
47
|
+
await db.bee.update()
|
|
48
|
+
if (!done && db.bee.writable) finish()
|
|
49
|
+
} catch {}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
db.bee.on('writable', onWritable)
|
|
53
|
+
db.on('close', onClose)
|
|
54
|
+
pollTimer = setInterval(poll, 1000)
|
|
55
|
+
if (timeout > 0) {
|
|
56
|
+
timer = setTimeout(() => finish(CeroError.TIMED_OUT('whenWritable')), timeout)
|
|
57
|
+
}
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function addWriter(db, publicKey) {
|
|
62
|
+
return db._write('add-writer', 'addWriter', publicKey)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function removeWriter(db, publicKey) {
|
|
66
|
+
return db._write('del-writer', 'removeWriter', publicKey)
|
|
67
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import c from 'compact-encoding'
|
|
2
|
+
import crypto from 'hypercore-crypto'
|
|
3
|
+
import b4a from 'b4a'
|
|
4
|
+
|
|
5
|
+
import { REMOVE } from '../lib/constants.js'
|
|
6
|
+
import { toId, toKey, can } from '../lib/utils.js'
|
|
7
|
+
import { wraps, epochEntries } from './encryption.js'
|
|
8
|
+
import { Identity } from '../identity/index.js'
|
|
9
|
+
import { CeroError } from '../lib/errors.js'
|
|
10
|
+
|
|
11
|
+
export async function rotate(db, retried = false) {
|
|
12
|
+
db.guard()
|
|
13
|
+
if (!db.writable) throw CeroError.NOT_WRITABLE('Database')
|
|
14
|
+
// queued in tx() the epoch is unobservable, and a batched rekey blurs the epoch
|
|
15
|
+
if (db.txQueue) throw CeroError.INVALID('rotate() cannot run inside tx()')
|
|
16
|
+
if (db._rotation) throw CeroError.INVALID('a rotation is already in progress')
|
|
17
|
+
// manifest v1 blocks carry no key id, rotating there is a silent downgrade
|
|
18
|
+
if (db.bee.local.manifest?.version < 2) {
|
|
19
|
+
throw CeroError.INVALID('rotation requires manifest v2 cores')
|
|
20
|
+
}
|
|
21
|
+
// claimed synchronously, no await may separate the check from the claim
|
|
22
|
+
db._rotation = { entropy: null, stamp: 0, epoch: 0 }
|
|
23
|
+
try {
|
|
24
|
+
const entropy = Identity.randomBytes(32)
|
|
25
|
+
const stamp = randomStamp(db)
|
|
26
|
+
const wrapped = sealFor(await members(db), entropy)
|
|
27
|
+
const epoch = await announce(db, stamp, entropy, wrapped)
|
|
28
|
+
if (!epoch) {
|
|
29
|
+
// a stamp collision (~2^-32, or an adversarial pre-claim) is not a refusal
|
|
30
|
+
if (!retried && (await stampTaken(db, stamp))) {
|
|
31
|
+
db._rotation = null
|
|
32
|
+
return db.rotate(true)
|
|
33
|
+
}
|
|
34
|
+
// permission is refused before the append, so the dry-run missed something
|
|
35
|
+
throw CeroError.INVALID('rotation was not applied')
|
|
36
|
+
}
|
|
37
|
+
db.keyring.add(stamp, entropy, epoch)
|
|
38
|
+
await saveEpochs(db)
|
|
39
|
+
return { epoch }
|
|
40
|
+
} finally {
|
|
41
|
+
db._rotation = null
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function members(db) {
|
|
46
|
+
const { data: members } = await db.get('members')
|
|
47
|
+
if (!Array.isArray(members) || members.length === 0) {
|
|
48
|
+
throw CeroError.INVALID('cannot rotate a database with no members')
|
|
49
|
+
}
|
|
50
|
+
return members
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** One sealed copy of the epoch secret per member, addressed by member id. */
|
|
54
|
+
function sealFor(members, entropy) {
|
|
55
|
+
return members.map((m) => {
|
|
56
|
+
let key
|
|
57
|
+
try {
|
|
58
|
+
key = toKey(m.id)
|
|
59
|
+
} catch {
|
|
60
|
+
throw CeroError.INVALID(`member id is not an identity key: ${m.id}`)
|
|
61
|
+
}
|
|
62
|
+
return { id: m.id, box: Identity.seal(key, entropy) }
|
|
63
|
+
})
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// append the announcement under the current epoch and wait for its apply;
|
|
67
|
+
// resolves the sequence apply assigned, 0 if it never applied
|
|
68
|
+
async function announce(db, stamp, entropy, wrapped) {
|
|
69
|
+
// defer our own hydration until the append flushed: the block is encrypted
|
|
70
|
+
// at drain time, so advancing the keyring now seals the announcement to itself
|
|
71
|
+
db._rotation.entropy = entropy
|
|
72
|
+
db._rotation.stamp = stamp
|
|
73
|
+
const from = db.bee.local.length
|
|
74
|
+
await db.call('rotate-key', {
|
|
75
|
+
epoch: 0, // sequence assigned deterministically at apply time
|
|
76
|
+
stamp,
|
|
77
|
+
wrapped: c.encode(wraps, wrapped),
|
|
78
|
+
createdAt: Date.now(),
|
|
79
|
+
commit: crypto.hash(entropy)
|
|
80
|
+
})
|
|
81
|
+
await db.bee.update()
|
|
82
|
+
// a block appended during a rotation must not carry the stamp it announces
|
|
83
|
+
for (let i = from; i < db.bee.local.length; i++) {
|
|
84
|
+
const raw = await db.bee.local.get(i, { raw: true })
|
|
85
|
+
const id = c.uint32.decode({ start: 4, end: 8, buffer: raw.subarray(0, 8) })
|
|
86
|
+
if (id === stamp) {
|
|
87
|
+
throw CeroError.INVALID('announcement encrypted under its own epoch — aborting rotation')
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return db._rotation.epoch
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function stampTaken(db, stamp) {
|
|
94
|
+
const rows = await db.view.find(`@${db.ns}/epochs`, {}).toArray()
|
|
95
|
+
return rows.some((r) => r.stamp === stamp)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Fresh nonzero uint32 block-header stamp not already used by a known epoch. */
|
|
99
|
+
function randomStamp(db) {
|
|
100
|
+
for (;;) {
|
|
101
|
+
const buf = Identity.randomBytes(4)
|
|
102
|
+
const stamp = ((buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]) >>> 0
|
|
103
|
+
if (stamp !== 0 && !db.keyring.entropy(stamp)) return stamp
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Per-peer side of an applied rotation: open our envelope, learn the epoch
|
|
109
|
+
* secret, persist it locally. Peers without an envelope (removed members)
|
|
110
|
+
* simply stop here — every block after the announcement is noise to them.
|
|
111
|
+
* Our own in-flight rotation is deferred to `rotate()` (see above).
|
|
112
|
+
*
|
|
113
|
+
* @param {import('./index.js').Database} db
|
|
114
|
+
* @param {{ epoch: number, wrapped: Uint8Array, createdAt: number }} row
|
|
115
|
+
*/
|
|
116
|
+
export async function onepoch(db, row) {
|
|
117
|
+
if (db.keyring.entropy(row.stamp)) {
|
|
118
|
+
// idempotent re-apply, but record the sequence if it was unknown
|
|
119
|
+
db.keyring.add(row.stamp, db.keyring.entropy(row.stamp), row.epoch)
|
|
120
|
+
scheduleHeal(db)
|
|
121
|
+
return
|
|
122
|
+
}
|
|
123
|
+
for (const w of c.decode(wraps, row.wrapped)) {
|
|
124
|
+
if (w.id !== db.identity.id) continue
|
|
125
|
+
const entropy = db.identity.unseal(w.box)
|
|
126
|
+
// keep scanning, a bad envelope ahead of a good one must not lock us out
|
|
127
|
+
if (entropy?.byteLength !== 32) continue
|
|
128
|
+
// a secret failing the row's commitment means the rotator sealed different ones
|
|
129
|
+
if (!row.commit || !b4a.equals(crypto.hash(entropy), row.commit)) {
|
|
130
|
+
db._onerror(CeroError.INVALID(`epoch ${row.epoch} envelope fails its commitment`))
|
|
131
|
+
continue
|
|
132
|
+
}
|
|
133
|
+
if (db._rotation?.entropy && b4a.equals(entropy, db._rotation.entropy)) {
|
|
134
|
+
db._rotation.epoch = row.epoch
|
|
135
|
+
} else {
|
|
136
|
+
db.keyring.add(row.stamp, entropy, row.epoch)
|
|
137
|
+
try {
|
|
138
|
+
await saveEpochs(db)
|
|
139
|
+
} catch (err) {
|
|
140
|
+
// an epoch we cannot reload after a restart must not be used for writes
|
|
141
|
+
db.keyring.remove(row.stamp)
|
|
142
|
+
db._onerror(err)
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
break
|
|
146
|
+
}
|
|
147
|
+
scheduleHeal(db)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Safety net after boot (userData priming happens in EpochAutobee's
|
|
152
|
+
* `_bootState`): scan the epochs collection for anything applied but never
|
|
153
|
+
* hydrated — e.g. a crash between a rotation's append and its save.
|
|
154
|
+
*/
|
|
155
|
+
export async function hydrateEpochs(db) {
|
|
156
|
+
try {
|
|
157
|
+
const rows = await db.view.find(`@${db.ns}/epochs`, {}).toArray()
|
|
158
|
+
for (const row of rows) {
|
|
159
|
+
if (db.keyring.entropy(row.stamp)) continue
|
|
160
|
+
await db._onepoch(row)
|
|
161
|
+
}
|
|
162
|
+
} catch {
|
|
163
|
+
// pre-rotation spec, or rows past our newest epoch, which hydrate via apply
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Persist known epoch secrets to local userData (device-only, never replicates). */
|
|
168
|
+
function saveEpochs(db) {
|
|
169
|
+
return db.bee.local.setUserData('cero/epochs', c.encode(epochEntries, db.keyring.all()))
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Debounced trigger for the epoch/membership consistency check. */
|
|
173
|
+
export function scheduleHeal(db) {
|
|
174
|
+
if (db._healTimer || db.closing || db.closed) return
|
|
175
|
+
db._healTimer = setTimeout(() => {
|
|
176
|
+
db._healTimer = null
|
|
177
|
+
healEpochs(db).catch(db._onerror)
|
|
178
|
+
}, 500)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Convergence rotation: rotations author their envelope set against the
|
|
183
|
+
* rotator's possibly-stale local view, so after linearization the current
|
|
184
|
+
* epoch may include a since-removed member (who then still holds the
|
|
185
|
+
* current key) or miss a since-added one (who is locked out). Every
|
|
186
|
+
* REMOVE-capable writable device audits the current epoch's recipients
|
|
187
|
+
* against canonical membership and re-keys on mismatch. Only rooms that
|
|
188
|
+
* have rotated at least once are audited — rotation stays opt-in.
|
|
189
|
+
*/
|
|
190
|
+
async function healEpochs(db) {
|
|
191
|
+
if (db.closing || db.closed || !db.writable || db._rotation) return
|
|
192
|
+
if (!db.keyring.current) return
|
|
193
|
+
const { data: device } = await db.get('devices', toId(db.writerKey))
|
|
194
|
+
const me = device?.memberId ? (await db.get('members', device.memberId)).data : null
|
|
195
|
+
if (!can(me?.role, REMOVE)) return
|
|
196
|
+
|
|
197
|
+
const rows = await db.view.find(`@${db.ns}/epochs`, {}).toArray()
|
|
198
|
+
if (!rows.length) return
|
|
199
|
+
const top = rows.reduce((a, b) => (b.epoch > a.epoch ? b : a))
|
|
200
|
+
const recipients = new Set(c.decode(wraps, top.wrapped).map((w) => w.id))
|
|
201
|
+
const { data: members } = await db.get('members')
|
|
202
|
+
const ids = new Set(members.map((m) => m.id))
|
|
203
|
+
const clean = recipients.size === ids.size && [...recipients].every((id) => ids.has(id))
|
|
204
|
+
if (clean) {
|
|
205
|
+
db._healedFor = null
|
|
206
|
+
return
|
|
207
|
+
}
|
|
208
|
+
// one attempt per (epoch, membership) state, a failing rotate must not loop
|
|
209
|
+
const state = `${top.stamp}:${[...ids].sort().join(',')}`
|
|
210
|
+
if (db._healedFor === state) return
|
|
211
|
+
db._healedFor = state
|
|
212
|
+
await db.rotate()
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Record that the log contains ops from a newer app version than this
|
|
217
|
+
* peer understands. Fires `'behind'` once per version so apps can prompt
|
|
218
|
+
* an upgrade; the marker survives restarts via local core userData.
|
|
219
|
+
*
|
|
220
|
+
* @param {import('./index.js').Database} db
|
|
221
|
+
* @param {number} version
|
|
222
|
+
*/
|
|
223
|
+
export function onfuture(db, version) {
|
|
224
|
+
if (db.behind !== null && version <= db.behind) return
|
|
225
|
+
db.behind = version
|
|
226
|
+
db.bee.local.setUserData('cero/behind', c.encode(c.uint, version)).catch(db._onerror)
|
|
227
|
+
db.emit('behind', version)
|
|
228
|
+
}
|
package/src/lib/utils.js
CHANGED
|
@@ -6,6 +6,10 @@ import { encode, decode } from 'hypercore-id-encoding'
|
|
|
6
6
|
|
|
7
7
|
import { ROLE_PERMS, RANK } from './constants.js'
|
|
8
8
|
|
|
9
|
+
// the capability names travel with can(): a caller cannot ask `can(role, REMOVE)`
|
|
10
|
+
// without them, and constants.js is not a public subpath
|
|
11
|
+
export { WRITE, INVITE, ASSIGN, REMOVE } from './constants.js'
|
|
12
|
+
|
|
9
13
|
/**
|
|
10
14
|
* Generate a short opaque id (z32-encoded 16 random bytes).
|
|
11
15
|
*
|
|
@@ -36,11 +40,14 @@ const ADD_WRITER_TAG = b4a.from('cero/add-writer/v2')
|
|
|
36
40
|
const CLAIM_WRITER_TAG = b4a.from('cero/claim-writer/v2')
|
|
37
41
|
|
|
38
42
|
/** @type {(dbKey: Uint8Array, writer: Uint8Array, appender: Uint8Array) => Uint8Array} */
|
|
39
|
-
export
|
|
40
|
-
b4a.concat([ADD_WRITER_TAG, dbKey, writer, appender])
|
|
43
|
+
export function addWriterPayload(dbKey, writer, appender) {
|
|
44
|
+
return b4a.concat([ADD_WRITER_TAG, dbKey, writer, appender])
|
|
45
|
+
}
|
|
41
46
|
|
|
42
47
|
/** @type {(dbKey: Uint8Array, writer: Uint8Array) => Uint8Array} */
|
|
43
|
-
export
|
|
48
|
+
export function claimWriterPayload(dbKey, writer) {
|
|
49
|
+
return b4a.concat([CLAIM_WRITER_TAG, dbKey, writer])
|
|
50
|
+
}
|
|
44
51
|
|
|
45
52
|
/**
|
|
46
53
|
* Whether `role` is granted `perm` under the default policy.
|
|
@@ -57,10 +64,16 @@ export function can(role, perm) {
|
|
|
57
64
|
// A role that is not one of the four ranks grants nothing and outranks
|
|
58
65
|
// nothing, so every gate built on `grants` silently refuses it. Callers that
|
|
59
66
|
// accept a role from an app or a peer must reject it loudly instead.
|
|
60
|
-
export
|
|
67
|
+
export function isRank(role) {
|
|
68
|
+
return RANK[role] != null
|
|
69
|
+
}
|
|
61
70
|
|
|
62
|
-
export
|
|
63
|
-
|
|
71
|
+
export function grants(a, b) {
|
|
72
|
+
return RANK[a] != null && RANK[b] != null && RANK[a] >= RANK[b]
|
|
73
|
+
}
|
|
74
|
+
export function outranks(a, b) {
|
|
75
|
+
return RANK[a] != null && RANK[b] != null && RANK[a] > RANK[b]
|
|
76
|
+
}
|
|
64
77
|
|
|
65
78
|
/**
|
|
66
79
|
* Stream-of-snapshots primitive. Couples a `get` (returns the latest value)
|
package/src/network/index.js
CHANGED
|
@@ -2,6 +2,7 @@ import NoiseSecretStream from '@hyperswarm/secret-stream'
|
|
|
2
2
|
import Autobee from 'autobee'
|
|
3
3
|
import BlindPairing from 'blind-pairing'
|
|
4
4
|
import BlindPeering from 'blind-peering'
|
|
5
|
+
import Protomux from 'protomux'
|
|
5
6
|
import ProtomuxWakeup from 'protomux-wakeup'
|
|
6
7
|
import ReadyResource from 'ready-resource'
|
|
7
8
|
import safetyCatch from 'safety-catch'
|
|
@@ -9,6 +10,7 @@ import { decode as decodeKey } from 'hypercore-id-encoding'
|
|
|
9
10
|
import { hash } from 'hypercore-crypto'
|
|
10
11
|
import Hyperswarm from 'hyperswarm'
|
|
11
12
|
import b4a from 'b4a'
|
|
13
|
+
import c from 'compact-encoding'
|
|
12
14
|
|
|
13
15
|
import { ACTIVE, PASSIVE } from '../lib/constants.js'
|
|
14
16
|
import { CeroError } from '../lib/errors.js'
|
|
@@ -61,6 +63,10 @@ export class Network extends ReadyResource {
|
|
|
61
63
|
this._swarm = null
|
|
62
64
|
this.wakeup = new ProtomuxWakeup()
|
|
63
65
|
|
|
66
|
+
this.info = null
|
|
67
|
+
this._peerInfo = new Map()
|
|
68
|
+
this._infoSenders = new Set()
|
|
69
|
+
|
|
64
70
|
this._replicateables = new Set()
|
|
65
71
|
this._discoveries = new Set()
|
|
66
72
|
this._injected = new Set()
|
|
@@ -110,6 +116,7 @@ export class Network extends ReadyResource {
|
|
|
110
116
|
conn.on('error', safetyCatch) // a dropped radio link must not crash the host
|
|
111
117
|
|
|
112
118
|
this.wakeup.addStream(conn)
|
|
119
|
+
this._attachInfo(conn)
|
|
113
120
|
for (const r of this._replicateables) replicateInto(r, conn)
|
|
114
121
|
this.emit('connection', conn, { injected: true })
|
|
115
122
|
return conn
|
|
@@ -155,6 +162,59 @@ export class Network extends ReadyResource {
|
|
|
155
162
|
for (const conn of this._injected) blind._onconnection(conn)
|
|
156
163
|
}
|
|
157
164
|
|
|
165
|
+
/**
|
|
166
|
+
* Declare this peer's self-reported info ({ name, ... }). Sent over an
|
|
167
|
+
* encrypted channel on every live and future connection — never on the
|
|
168
|
+
* radio advertisement or the DHT.
|
|
169
|
+
*
|
|
170
|
+
* @param {object | null} info
|
|
171
|
+
*/
|
|
172
|
+
setInfo(info) {
|
|
173
|
+
this.info = info || null
|
|
174
|
+
if (!this.info) return
|
|
175
|
+
for (const send of this._infoSenders) send()
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Info a connected peer declared about itself, or null.
|
|
180
|
+
*
|
|
181
|
+
* @param {Uint8Array | string} key Peer public key (bytes or hex).
|
|
182
|
+
* @returns {object | null}
|
|
183
|
+
*/
|
|
184
|
+
getInfo(key) {
|
|
185
|
+
const hex = typeof key === 'string' ? key : b4a.toString(key, 'hex')
|
|
186
|
+
return this._peerInfo.get(hex) ?? null
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// The channel stays silent until a side has info to send: bytes on a fresh
|
|
190
|
+
// connection make hyperswarm's duplicate-connection guard treat it as the
|
|
191
|
+
// stale one and drop it when both peers dialed each other at once.
|
|
192
|
+
_attachInfo(conn) {
|
|
193
|
+
const mux = Protomux.from(conn)
|
|
194
|
+
let message = null
|
|
195
|
+
const send = () => {
|
|
196
|
+
if (!message) {
|
|
197
|
+
const channel = mux.createChannel({ protocol: 'cero/info' })
|
|
198
|
+
if (channel === null) return
|
|
199
|
+
message = channel.addMessage({
|
|
200
|
+
encoding: c.json,
|
|
201
|
+
onmessage: (info) => {
|
|
202
|
+
if (!info || typeof info !== 'object') return
|
|
203
|
+
const hex = b4a.toString(conn.remotePublicKey, 'hex')
|
|
204
|
+
this._peerInfo.set(hex, info)
|
|
205
|
+
this.emit('peer-info', hex, info)
|
|
206
|
+
}
|
|
207
|
+
})
|
|
208
|
+
channel.open()
|
|
209
|
+
}
|
|
210
|
+
if (this.info) message.send(this.info)
|
|
211
|
+
}
|
|
212
|
+
mux.pair({ protocol: 'cero/info' }, send)
|
|
213
|
+
this._infoSenders.add(send)
|
|
214
|
+
conn.on('close', () => this._infoSenders.delete(send))
|
|
215
|
+
if (this.info) send()
|
|
216
|
+
}
|
|
217
|
+
|
|
158
218
|
/** @returns {Map<string, any>} Known peers keyed by public-key string. */
|
|
159
219
|
get peers() {
|
|
160
220
|
return this.swarm ? this.swarm.peers : new Map()
|
|
@@ -188,6 +248,7 @@ export class Network extends ReadyResource {
|
|
|
188
248
|
return
|
|
189
249
|
}
|
|
190
250
|
this.wakeup.addStream(stream)
|
|
251
|
+
this._attachInfo(stream)
|
|
191
252
|
for (const r of this._replicateables) replicateInto(r, stream)
|
|
192
253
|
this.emit('connection', stream, info)
|
|
193
254
|
})
|
|
@@ -338,8 +399,13 @@ export class Network extends ReadyResource {
|
|
|
338
399
|
// mirror the core so it stays available when its writers are offline —
|
|
339
400
|
// autobees announce their whole writer set, plain cores (blobs) just themselves
|
|
340
401
|
if (this._blindPeering) {
|
|
341
|
-
if (Autobee.isAutobee(core))
|
|
342
|
-
|
|
402
|
+
if (Autobee.isAutobee(core)) {
|
|
403
|
+
this._blindPeering.addAutobaseBackground(core)
|
|
404
|
+
// the bootstrap core leaves the writer set after the local swap, but joiners boot from it
|
|
405
|
+
const mirrorBootstrap = () =>
|
|
406
|
+
this._blindPeering?.addCoreBackground(core.bootstrap, { referrer: core.key })
|
|
407
|
+
core.ready().then(mirrorBootstrap, safetyCatch)
|
|
408
|
+
} else this._blindPeering.addCoreBackground(core)
|
|
343
409
|
}
|
|
344
410
|
}
|
|
345
411
|
|
package/src/pairing/index.js
CHANGED
|
@@ -106,7 +106,7 @@ export class Pairing extends ReadyResource {
|
|
|
106
106
|
this._member = this._blind.addMember({
|
|
107
107
|
// channel-scoped; the candidate hashes identically (no channel → identity)
|
|
108
108
|
discoveryKey: channelTopic(discoveryKey(this.topic), this.network.channel),
|
|
109
|
-
onadd: (req) => this.
|
|
109
|
+
onadd: (req) => this._oncandidate(req).catch(this._onerror)
|
|
110
110
|
})
|
|
111
111
|
}
|
|
112
112
|
await this.network.refreshInjected()
|
|
@@ -329,7 +329,7 @@ export class Pairing extends ReadyResource {
|
|
|
329
329
|
}
|
|
330
330
|
}
|
|
331
331
|
|
|
332
|
-
async
|
|
332
|
+
async _oncandidate(req) {
|
|
333
333
|
const id = b4a.toString(req.inviteId, 'hex')
|
|
334
334
|
const record = this._invites.get(id)
|
|
335
335
|
if (!record) return
|
|
@@ -368,7 +368,7 @@ export class Pairing extends ReadyResource {
|
|
|
368
368
|
|
|
369
369
|
/**
|
|
370
370
|
* Internal — a pairing request from an incoming candidate, awaiting the host's
|
|
371
|
-
* accept/deny. Built in `
|
|
371
|
+
* accept/deny. Built in `_oncandidate` and emitted on the `'candidate'` event so
|
|
372
372
|
* the host can decide via `confirm` / `deny`. (The candidate is the joiner; this
|
|
373
373
|
* is the host's handle to answer it.)
|
|
374
374
|
*
|
package/src/pairing/invite.js
CHANGED
|
@@ -108,10 +108,12 @@ export class Invite {
|
|
|
108
108
|
* @returns {Invite}
|
|
109
109
|
*/
|
|
110
110
|
static create({ secretKey, publicKey, role, expiresIn, data, blind, encoding }) {
|
|
111
|
-
if (!secretKey || secretKey.length !== 64)
|
|
111
|
+
if (!secretKey || secretKey.length !== 64) {
|
|
112
112
|
throw CeroError.INVALID('secretKey must be a 64-byte buffer')
|
|
113
|
-
|
|
113
|
+
}
|
|
114
|
+
if (!publicKey || publicKey.length !== 32) {
|
|
114
115
|
throw CeroError.INVALID('publicKey must be a 32-byte buffer')
|
|
116
|
+
}
|
|
115
117
|
if (!b4a.isBuffer(blind)) {
|
|
116
118
|
throw CeroError.INVALID('blind invite must be a buffer')
|
|
117
119
|
}
|
package/src/storage/index.js
CHANGED
|
@@ -46,15 +46,19 @@ export class Storage extends ReadyResource {
|
|
|
46
46
|
*/
|
|
47
47
|
constructor(dir, { spec, backend, root, store, storageKey } = {}) {
|
|
48
48
|
super()
|
|
49
|
-
if (!root && !store && (typeof dir !== 'string' || !dir))
|
|
49
|
+
if (!root && !store && (typeof dir !== 'string' || !dir)) {
|
|
50
50
|
throw CeroError.REQUIRED('dir, root, or store')
|
|
51
|
+
}
|
|
51
52
|
if (!spec || !spec.database) throw CeroError.REQUIRED('spec.database')
|
|
52
|
-
if (backend !== ROCKS && backend !== BEE)
|
|
53
|
+
if (backend !== ROCKS && backend !== BEE) {
|
|
53
54
|
throw CeroError.INVALID('backend must be "rocks" or "bee"')
|
|
54
|
-
|
|
55
|
+
}
|
|
56
|
+
if (storageKey && backend === ROCKS) {
|
|
55
57
|
throw CeroError.INVALID('storageKey requires the bee backend')
|
|
56
|
-
|
|
58
|
+
}
|
|
59
|
+
if (storageKey && storageKey.byteLength !== 32) {
|
|
57
60
|
throw CeroError.INVALID('storageKey must be 32 bytes')
|
|
61
|
+
}
|
|
58
62
|
|
|
59
63
|
this.dir = dir
|
|
60
64
|
this.spec = spec
|
|
@@ -104,8 +108,9 @@ export class Storage extends ReadyResource {
|
|
|
104
108
|
}
|
|
105
109
|
|
|
106
110
|
if (this.backend === ROCKS) {
|
|
107
|
-
if (!this.root)
|
|
111
|
+
if (!this.root) {
|
|
108
112
|
throw CeroError.INVALID('rocks backend requires a root storage, not store-only')
|
|
113
|
+
}
|
|
109
114
|
const cf = this.root.rocks.columnFamily(this._cf)
|
|
110
115
|
this.db = HyperDB.rocks(cf, this.spec.database)
|
|
111
116
|
} else {
|
|
@@ -277,8 +282,9 @@ export class Storage extends ReadyResource {
|
|
|
277
282
|
|
|
278
283
|
/** @param {string} name @returns {Ref} */
|
|
279
284
|
_ref(name) {
|
|
280
|
-
if (typeof name !== 'string' || !name)
|
|
285
|
+
if (typeof name !== 'string' || !name) {
|
|
281
286
|
throw CeroError.INVALID('name must be a non-empty string')
|
|
287
|
+
}
|
|
282
288
|
const ref = this.refs[name]
|
|
283
289
|
if (!ref) throw CeroError.UNKNOWN('ref', name)
|
|
284
290
|
return { name, kind: ref.kind || COLLECTION }
|
|
@@ -91,7 +91,7 @@ export class EpochAutobee {
|
|
|
91
91
|
_epochRetry: any;
|
|
92
92
|
_epochRetryDelay: number;
|
|
93
93
|
_epochRetrySeen: number;
|
|
94
|
-
_bumpPendingWriters(): Promise<any>;
|
|
94
|
+
_bumpPendingWriters(...args: any[]): Promise<any>;
|
|
95
95
|
_applyWakeupHints(): Promise<any>;
|
|
96
96
|
_scheduleEpochRetry(): void;
|
|
97
97
|
_close(): Promise<any>;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export function before(db: any, op: any, fn: any): () => void;
|
|
2
|
+
export function after(db: any, op: any, fn: any): () => void;
|
|
3
|
+
export function onUpdate(db: any, fn: any, scope: any): () => any;
|
|
4
|
+
export function touch(db: any, nodes: any): void;
|
|
5
|
+
export function onApply(db: any, fn: any): () => void;
|
|
6
|
+
export function observe(db: any, nodes: any): void;
|
|
7
|
+
export function runBefore(db: any, op: any, ctx: any): Promise<boolean>;
|
|
8
|
+
export function runAfter(db: any, op: any, ctx: any): Promise<void>;
|