@cero-base/cero 2.4.1 → 2.6.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cero-base/cero",
3
- "version": "2.4.1",
3
+ "version": "2.6.0",
4
4
  "description": "The ideal p2p API — everything is a handle, handles contain refs, refs contain rows.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -44,6 +44,14 @@
44
44
  "./extensions": {
45
45
  "types": "./types/extensions/index.d.ts",
46
46
  "default": "./src/extensions/index.js"
47
+ },
48
+ "./push": {
49
+ "types": "./types/push/index.d.ts",
50
+ "default": "./src/push/index.js"
51
+ },
52
+ "./push/firebase": {
53
+ "types": "./types/push/firebase.d.ts",
54
+ "default": "./src/push/firebase.js"
47
55
  }
48
56
  },
49
57
  "typesVersions": {
@@ -59,6 +67,12 @@
59
67
  ],
60
68
  "extensions": [
61
69
  "types/extensions/index.d.ts"
70
+ ],
71
+ "push": [
72
+ "types/push/index.d.ts"
73
+ ],
74
+ "push/firebase": [
75
+ "types/push/firebase.d.ts"
62
76
  ]
63
77
  }
64
78
  },
@@ -99,24 +113,24 @@
99
113
  "test:node": "find test -name '*.test.js' | sort | xargs -P4 -n1 brittle-node"
100
114
  },
101
115
  "dependencies": {
102
- "@cero-base/core": "^2.4.1",
116
+ "@cero-base/core": "^2.6.0",
103
117
  "b4a": "^1.9.0",
104
118
  "bare-abort-controller": "^1.1.2",
105
119
  "bare-crypto": "^1.15.4",
106
- "bare-fs": "^4.8.2",
120
+ "bare-fs": "^4.8.4",
107
121
  "bare-path": "^3.1.2",
108
122
  "ble-swarm": "^2.3.4",
109
123
  "compact-encoding": "^3.5.2",
110
- "corestore": "^7.13.0",
124
+ "corestore": "^7.16.1",
111
125
  "hrpc": "^4.3.1",
112
- "hypercore": "^11.37.1",
126
+ "hypercore": "^11.39.3",
113
127
  "hypercore-crypto": "^3.7.0",
114
128
  "hypercore-id-encoding": "^1.3.0",
115
129
  "hypercore-storage": "^3.3.1",
116
- "hyperdb": "^6.9.0",
130
+ "hyperdb": "^6.11.0",
117
131
  "hyperdispatch": "^1.6.0",
118
132
  "hyperschema": "^1.26.2",
119
- "protomux": "^3.12.1",
133
+ "protomux": "^3.13.0",
120
134
  "ready-resource": "^1.2.0",
121
135
  "safety-catch": "^1.0.3",
122
136
  "streamx": "^2.28.1",
@@ -126,11 +140,11 @@
126
140
  "devDependencies": {
127
141
  "@hyperswarm/testnet": "^3.1.4",
128
142
  "bare-events": "^2.9.2",
129
- "bare-fetch": "^3.4.0",
143
+ "bare-fetch": "^3.4.1",
130
144
  "bare-process": "^4.5.1",
131
- "bare-url": "^2.5.4",
132
- "blind-peer": "^3.15.1",
133
- "brittle": "^4.2.0",
145
+ "bare-url": "^2.5.5",
146
+ "blind-peer": "^3.16.0",
147
+ "brittle": "^4.5.0",
134
148
  "typescript": "^7.0.2"
135
149
  },
136
150
  "license": "Apache-2.0"
@@ -185,6 +185,7 @@ function register(name, node, ctx) {
185
185
  ctx.types.push({ name, compact: false, fields: internal.fields(node.fields) })
186
186
  ctx.dispatches.push({ name, requestType: fqn })
187
187
  ctx.meta.refs[name] = { kind: 'action', path: [name], schema: fqn }
188
+ if (node.push) ctx.meta.refs[name].push = true
188
189
  return
189
190
  }
190
191
  if (node.kind === 'single') {
@@ -196,6 +197,7 @@ function register(name, node, ctx) {
196
197
  { kind: 'single', path: [name], schema: fqn },
197
198
  node.fields
198
199
  )
200
+ if (node.push) ctx.meta.refs[name].push = true
199
201
  return
200
202
  }
201
203
  if (node.kind === 'collection') {
@@ -220,6 +222,7 @@ function register(name, node, ctx) {
220
222
  node.fields
221
223
  )
222
224
  if (node.own) refEntry.own = true
225
+ if (node.push) refEntry.push = true
223
226
  ctx.meta.refs[name] = refEntry
224
227
  if (node.indexes) {
225
228
  for (const [idx, fields] of Object.entries(node.indexes)) {
@@ -14,13 +14,15 @@ export const defs = {
14
14
  },
15
15
  local: {
16
16
  master: { type: 'master', kind: 'single' },
17
+ device: { type: 'device', kind: 'single' },
17
18
  keypair: { type: 'keypair', kind: 'single' },
18
19
  'handle-keypairs': { type: 'handle-keypair' },
19
20
  joins: { type: 'join' },
20
21
  inbox: { type: 'mail' },
21
22
  outbox: { type: 'mail' },
22
23
  environment: { type: 'environment', kind: 'single' },
23
- serving: { type: 'serving' }
24
+ serving: { type: 'serving' },
25
+ topics: { type: 'subscription' }
24
26
  }
25
27
  }
26
28
 
@@ -28,7 +30,8 @@ export const defs = {
28
30
  const LIVE = {
29
31
  status: { type: 'status', kind: 'single' },
30
32
  joins: { type: 'joining', root: true },
31
- nearby: { type: 'peer', root: true }
33
+ nearby: { type: 'peer', root: true },
34
+ topics: { type: 'topic', root: true }
32
35
  }
33
36
 
34
37
  /**
@@ -10,7 +10,8 @@ export const main = {
10
10
  writer: {
11
11
  master: required(bytes),
12
12
  writer: required(bytes),
13
- sig: required(bytes),
13
+ // the device's proof over the admission, chained to `master`
14
+ proof: required(bytes),
14
15
  isIndexer: bool,
15
16
  ts: int,
16
17
  // the paired add-member decides the rank in the same transaction; `role` here is unread
@@ -37,7 +38,11 @@ export const main = {
37
38
  isMobile: bool,
38
39
  createdAt: int,
39
40
  updatedAt: int,
40
- index: uint
41
+ index: uint,
42
+ // the device key its admission proved: rotation seals to it
43
+ key: bytes,
44
+ // the chain to the identity, when a device of the member linked it here
45
+ proof: bytes
41
46
  },
42
47
  invite: {
43
48
  id: required(string),
@@ -57,7 +62,9 @@ export const main = {
57
62
  name: string,
58
63
  createdAt: int,
59
64
  updatedAt: int,
60
- index: uint
65
+ index: uint,
66
+ // its rotation epochs, for a device of the identity opening it later
67
+ epochs: bytes
61
68
  },
62
69
  file: {
63
70
  id: required(string),
@@ -83,7 +90,9 @@ export const main = {
83
90
  },
84
91
  accept: {
85
92
  id: required(string),
86
- role: string
93
+ role: string,
94
+ // the accepter's own device attests the joiner's: a device of the member, not a member
95
+ proof: bytes
87
96
  },
88
97
  // a join from its arrival until the joiner has its keys: waiting for a member on a confirm
89
98
  // invite, then admitted and owed its reply. `id` is the joiner's writer
@@ -97,7 +106,9 @@ export const main = {
97
106
  admitted: bool,
98
107
  expires: int,
99
108
  // what the join asks for, the invite's role; once admitted, the role granted
100
- role: string
109
+ role: string,
110
+ // the device key the join's proof ends at
111
+ key: bytes
101
112
  },
102
113
  // a removed member comes back only through an invite minted after `index`
103
114
  removal: {
@@ -145,6 +156,13 @@ export const main = {
145
156
  deny: {
146
157
  id: required(string),
147
158
  reason: string
159
+ },
160
+ // a handle's push topic: what a device subscribes to for pushes about it
161
+ topic: {
162
+ id: required(string),
163
+ handle: required(string),
164
+ type: required(string),
165
+ name: string
148
166
  }
149
167
  }
150
168
 
@@ -152,6 +170,14 @@ export const local = {
152
170
  master: {
153
171
  seed: required(bytes)
154
172
  },
173
+ // this device's key and its proof, with the identity it chains to and the root encryption key
174
+ device: {
175
+ publicKey: required(bytes),
176
+ secretKey: required(bytes),
177
+ proof: required(bytes),
178
+ identity: required(bytes),
179
+ encryptionKey: required(bytes)
180
+ },
155
181
  keypair: {
156
182
  publicKey: required(bytes),
157
183
  secretKey: required(bytes),
@@ -180,7 +206,10 @@ export const local = {
180
206
  // the reply, once it landed: the join then opens the handle without joining again
181
207
  key: bytes,
182
208
  encryptionKey: bytes,
183
- epochs: bytes
209
+ epochs: bytes,
210
+ // the root's join: this device's secret key, bare until the reply brings its proof
211
+ device: bytes,
212
+ proof: bytes
184
213
  },
185
214
  // mail the device's mailbox keeps: received until handled, sent until read. `mirrors` are
186
215
  // 32-byte keys back to back
@@ -192,6 +221,14 @@ export const local = {
192
221
  },
193
222
  environment: {
194
223
  channel: required(string)
224
+ },
225
+ // the handles rows a cold push process can read without the root: topic → handle and its key
226
+ subscription: {
227
+ id: required(string),
228
+ handle: required(string),
229
+ type: required(string),
230
+ key: required(bytes),
231
+ name: string
195
232
  }
196
233
  }
197
234
 
@@ -1,5 +1,6 @@
1
1
  import AbortController from 'bare-abort-controller'
2
2
  import b4a from 'b4a'
3
+ import c from 'compact-encoding'
3
4
  import { discoveryKey } from 'hypercore-crypto'
4
5
  import ReadyResource from 'ready-resource'
5
6
  import safetyCatch from 'safety-catch'
@@ -8,8 +9,9 @@ import z32 from 'z32'
8
9
 
9
10
  import { Identity } from '@cero-base/core/identity'
10
11
  import { Database } from '@cero-base/core/database'
11
- import { blobEpochKey } from '@cero-base/core/database/encryption'
12
+ import { blobEpochKey, epochEntries } from '@cero-base/core/database/encryption'
12
13
  import { Pairing } from '@cero-base/core/pairing'
14
+ import { verify } from '@cero-base/core/push'
13
15
  import { Invite } from '@cero-base/core/invite'
14
16
  import { Mailbox } from '@cero-base/core/mailbox'
15
17
  import hid from 'hypercore-id-encoding'
@@ -156,6 +158,8 @@ export class Handle extends ReadyResource {
156
158
  namespace: opts.namespace,
157
159
  keyPair: opts.keyPair,
158
160
  pinned: !parent,
161
+ // the root has no topic to push to
162
+ push: !!parent,
159
163
  onerror: this._onerror
160
164
  })
161
165
  /** @private */
@@ -170,8 +174,9 @@ export class Handle extends ReadyResource {
170
174
  this._live = {
171
175
  status: { get: () => this._status(), watch: (fn) => this._onStatus(fn) },
172
176
  ...(!this.parent && {
173
- joins: { get: (q) => this._joins(q), watch: (fn) => this._onJoins(fn) },
174
- nearby: { get: () => this._peers(), watch: (fn) => this._onRadio(fn) }
177
+ joins: { get: (q) => this._joins(q), watch: (fn) => this._onLocal(fn) },
178
+ nearby: { get: () => this._peers(), watch: (fn) => this._onRadio(fn) },
179
+ topics: { get: (q) => this._topics(q), watch: (fn) => this._onLocal(fn) }
175
180
  })
176
181
  }
177
182
  }
@@ -263,14 +268,14 @@ export class Handle extends ReadyResource {
263
268
  await this.store.ready()
264
269
  // a fresh device takes writes only once provisioned, and an operator waits for the open
265
270
  if (this._boot) await this.store.bootstrap(this._boot)
266
- if (this.parent) {
267
- this._pair = new Pairing({ mailbox: this.mailbox, db: this.store })
268
- await this._pair.ready()
269
- }
271
+ this._pair = new Pairing({ mailbox: this.mailbox, db: this.store })
272
+ await this._pair.ready()
270
273
  this.root._coreKeys.set(b4a.toHex(this.store.key), this.store.encryptionKey)
271
274
  if (!this.parent) {
272
275
  await this.fileServer.listen()
273
276
  await this.mailbox.ready()
277
+ const prune = this.store.onUpdate('devices', () => this._pruneAll().catch(this._onerror))
278
+ this.once('close', prune)
274
279
  if (this._bluetooth) {
275
280
  const off = this.store.onUpdate('profile', () => this._tell().catch(this._onerror))
276
281
  this.once('close', off)
@@ -278,6 +283,10 @@ export class Handle extends ReadyResource {
278
283
  }
279
284
  await this._carryOn().catch(this._onerror)
280
285
  this._reserve().catch(this._onerror)
286
+ // the handles rows, keyed by push topic, for a cold push process that cannot read the root
287
+ const off = this.store.onUpdate('handles', () => this._index().catch(this._onerror))
288
+ this.once('close', off)
289
+ await this._index()
281
290
  }
282
291
  }
283
292
 
@@ -353,20 +362,28 @@ export class Handle extends ReadyResource {
353
362
 
354
363
  // the verbs in lib/operators.js land here
355
364
 
365
+ // the root's invite is for a device of yours: one, confirmed by hand, carrying the identity the
366
+ // device checks its chain against
356
367
  /** @private */
357
- async _invite(opts) {
358
- return this._pairing().invite(opts)
368
+ async _invite(opts = {}) {
369
+ if (this.parent) return this._pair.invite(opts)
370
+ const { ttl = '2h' } = opts
371
+ return this._pair.invite({ role: 'owner', confirm: true, ttl, data: this.identity.publicKey })
359
372
  }
360
373
 
361
374
  /** @private */
362
375
  async _revoke(invite) {
363
- return this._pairing().revoke(invite)
376
+ return this._pair.revoke(invite)
364
377
  }
365
378
 
379
+ // accepting on the root links the device: this one attests its key
366
380
  /** @private */
367
381
  async _answer(id, { accept, role, reason }) {
368
- const pairing = this._pairing()
369
- return accept ? pairing.accept(id, { role }) : pairing.deny(id, reason)
382
+ if (!accept) return this._pair.deny(id, reason)
383
+ if (this.parent) return this._pair.accept(id, { role })
384
+ const { data: row } = await this.store.get('requests', id)
385
+ if (!row) throw CeroError.UNKNOWN('request', id)
386
+ return this._pair.accept(id, { proof: this.identity.link(row.key) })
370
387
  }
371
388
 
372
389
  /** @private */
@@ -390,12 +407,6 @@ export class Handle extends ReadyResource {
390
407
  })
391
408
  }
392
409
 
393
- /** @private */
394
- _pairing() {
395
- if (!this._pair) throw CeroError.INVALID('the root has no invites, open a handle first')
396
- return this._pair
397
- }
398
-
399
410
  /** @private */
400
411
  async _leave() {
401
412
  if (!this.parent) throw CeroError.INVALID('the root cannot be left')
@@ -445,6 +456,7 @@ export class Handle extends ReadyResource {
445
456
  behind: this.store.behind || 0,
446
457
  nearby: this.root._bluetooth?.state ?? null
447
458
  }
459
+ if (this.parent) data.topic = b4a.toHex(this.store.discoveryKey)
448
460
  return { data }
449
461
  }
450
462
 
@@ -521,11 +533,56 @@ export class Handle extends ReadyResource {
521
533
  }
522
534
 
523
535
  /** @private */
524
- _onJoins(fn) {
536
+ _onLocal(fn) {
525
537
  this.local.store.db.watch(fn)
526
538
  return () => this.local.store.db.unwatch(fn)
527
539
  }
528
540
 
541
+ /** @private */
542
+ async _topics(query = {}) {
543
+ const rows = (await this.local.store.get('topics')).data
544
+ const data = filter(
545
+ rows.map(({ id, handle, type, name }) => ({ id, handle, type, name })),
546
+ query
547
+ )
548
+ return { data, total: data.length, size: data.length }
549
+ }
550
+
551
+ // one pass at a time: two overlapping could put back a row the later one deleted
552
+ /** @private */
553
+ _index() {
554
+ this._indexing = (this._indexing ?? Promise.resolve()).then(() => this._reindex())
555
+ return this._indexing
556
+ }
557
+
558
+ /** @private */
559
+ async _reindex() {
560
+ if (this.closing || this.closed) return
561
+ const { data: handles } = await this.store.get('handles')
562
+ const { data: rows } = await this.local.store.get('topics')
563
+ const wanted = new Map(handles.map((h) => [b4a.toHex(discoveryKey(h.key)), h]))
564
+ const have = new Map(rows.map((row) => [row.id, row]))
565
+ for (const row of rows) {
566
+ if (!wanted.has(row.id)) await this.local.store.del('topics', row.id)
567
+ }
568
+ for (const [id, h] of wanted) {
569
+ const row = { id, handle: h.id, type: h.type, key: h.key, name: h.name ?? null }
570
+ if (same(have.get(id), row)) continue
571
+ await this.local.store.put('topics', row)
572
+ }
573
+ }
574
+
575
+ // a push about one of this device's handles, verified against its own cores
576
+ /** @private */
577
+ async _receive(payload) {
578
+ // a suspended storage answers no read: the cold entry serves a push while the app sleeps
579
+ if (this._sus.suspended) throw CeroError.INVALID('receive: the app is suspended')
580
+ const { data: rows } = await this.local.store.get('topics')
581
+ const handles = rows.map(({ handle, key, type, name }) => ({ id: handle, key, type, name }))
582
+ const hit = await verify(this.store.store.storage, payload, handles)
583
+ return hit && { id: hit.id, type: hit.type, name: hit.name, newer: hit.newer, ref: hit.ref }
584
+ }
585
+
529
586
  /** @private */
530
587
  async _phrase() {
531
588
  return this.identity.toPhrase()
@@ -680,7 +737,7 @@ export class Handle extends ReadyResource {
680
737
  await tx.call('add-writer', {
681
738
  master: this.identity.publicKey,
682
739
  writer: writerKey,
683
- sig: this.identity.sign(admission(child.store.key, writerKey, child.store.writerKey)),
740
+ proof: this.identity.sign(admission(child.store.key, writerKey, child.store.writerKey)),
684
741
  ts
685
742
  })
686
743
  await tx.call('add-member', {
@@ -826,6 +883,7 @@ export class Handle extends ReadyResource {
826
883
  type,
827
884
  key: child.store.key,
828
885
  encryptionKey: child.store.encryptionKey,
886
+ epochs: c.encode(epochEntries, child.store.keyring.all()),
829
887
  name: null,
830
888
  createdAt: ts,
831
889
  updatedAt: ts
@@ -907,6 +965,7 @@ export class Handle extends ReadyResource {
907
965
  namespace: `${NS}/handle/${type}/${id}`,
908
966
  key: data.key,
909
967
  encryptionKey: data.encryptionKey,
968
+ epochs: data.epochs ? c.decode(epochEntries, data.epochs) : undefined,
910
969
  keyPair: /** @type {KeyPair} */ (writer)
911
970
  })
912
971
  try {
@@ -956,9 +1015,59 @@ export class Handle extends ReadyResource {
956
1015
  this._pending.delete(child)
957
1016
  this.children.add(child)
958
1017
  this._serve(child)
1018
+ this._carry(child)
1019
+ this._prune(child).catch(this._onerror)
959
1020
  this.emit('handle', child, info)
960
1021
  }
961
1022
 
1023
+ // a device removed from the root loses its seats in every handle: its chain is static, so the
1024
+ // handles are told by whichever device of the identity has them open
1025
+ /** @private */
1026
+ async _prune(child) {
1027
+ const { data: mine } = await this.store.get('devices')
1028
+ const kept = new Set(mine.filter((d) => d.key).map((d) => b4a.toHex(d.key)))
1029
+ const { data: rows } = await child.store.get('devices')
1030
+ for (const row of rows) {
1031
+ if (row.memberId !== this.identity.id || !row.key || kept.has(b4a.toHex(row.key))) continue
1032
+ if (child.closing || child.closed) return
1033
+ await child.store.del('devices', row.id)
1034
+ }
1035
+ }
1036
+
1037
+ /** @private */
1038
+ async _pruneAll() {
1039
+ for (const child of this.children) await this._prune(child)
1040
+ }
1041
+
1042
+ // a handle's epochs ride in its root row, which only the identity's devices read: one that
1043
+ // opens the handle later reads history with them, since envelopes in the log address a device
1044
+ /** @private */
1045
+ _carry(child) {
1046
+ const save = async () => {
1047
+ const epochs = c.encode(epochEntries, child.store.keyring.all())
1048
+ const { data: row } = await this.store.get('handles', child.id)
1049
+ if (!row || b4a.equals(row.epochs || b4a.alloc(0), epochs)) return
1050
+ await this.store.set('handles', { id: row.id, epochs })
1051
+ }
1052
+ // read when the row changes, and when an announcement applies: it is learned only after that
1053
+ const read = async () => {
1054
+ const { data: row } = await this.store.get('handles', child.id)
1055
+ if (row?.epochs) await child.store.learn(c.decode(epochEntries, row.epochs))
1056
+ }
1057
+ const touches = (name) => (touched) => touched.has('*') || touched.has(name)
1058
+ const onepoch = () => save().catch(this._onerror)
1059
+ const onroot = (touched) => touches('handles')(touched) && read().catch(this._onerror)
1060
+ const onchild = (touched) => touches('epochs')(touched) && read().catch(this._onerror)
1061
+ child.store.on('epoch', onepoch)
1062
+ child.store.on('update', onchild)
1063
+ this.store.on('update', onroot)
1064
+ child.once('close', () => {
1065
+ child.store.off('epoch', onepoch)
1066
+ child.store.off('update', onchild)
1067
+ this.store.off('update', onroot)
1068
+ })
1069
+ }
1070
+
962
1071
  // before(me.room.notes, fn): on every handle open now and every one opened later
963
1072
  /** @private */
964
1073
  _hookType(ref, attach, opts) {
@@ -1072,6 +1181,17 @@ function randomNs() {
1072
1181
  return z32.encode(Identity.randomBytes(8))
1073
1182
  }
1074
1183
 
1184
+ // a topics row still describes its handle
1185
+ function same(row, next) {
1186
+ return (
1187
+ !!row &&
1188
+ row.handle === next.handle &&
1189
+ row.type === next.type &&
1190
+ (row.name ?? null) === next.name &&
1191
+ b4a.equals(row.key, next.key)
1192
+ )
1193
+ }
1194
+
1075
1195
  // run every teardown step, then surface the first failure: a bug must not leak the storage lock
1076
1196
  async function settle(steps) {
1077
1197
  let failed = null