@cero-base/cero 2.7.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cero-base/cero",
3
- "version": "2.7.0",
3
+ "version": "2.8.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,
@@ -103,7 +103,7 @@
103
103
  }
104
104
  },
105
105
  "scripts": {
106
- "build:test": "rm -rf test/fixtures/spec && node test/fixtures/build.js",
106
+ "build:test": "rm -rf test/fixtures/spec && node test/fixtures/build.js && node test/fixtures/compat.js",
107
107
  "build:types": "rm -rf types && tsc -p .",
108
108
  "pretest": "npm run build:test",
109
109
  "prepublishOnly": "npm run build:types",
@@ -113,7 +113,7 @@
113
113
  "test:node": "find test -name '*.test.js' | sort | xargs -P4 -n1 brittle-node"
114
114
  },
115
115
  "dependencies": {
116
- "@cero-base/core": "^2.7.0",
116
+ "@cero-base/core": "^2.8.0",
117
117
  "b4a": "^1.9.0",
118
118
  "bare-abort-controller": "^1.1.2",
119
119
  "bare-crypto": "^1.15.4",
@@ -239,12 +239,12 @@ function register(name, node, ctx) {
239
239
  }
240
240
 
241
241
  // one contract for the app, kept in contract.json: it rises once per build that changes what is
242
- // stored, at the root or in any handle type, never for RPC alone. A spec without one starts from
243
- // its builders' versions, so a shipped app's number never goes down
242
+ // stored, at the root or in any handle type, or what a write means to Cero, never for RPC alone.
243
+ // A spec without one starts from its builders' versions, so a shipped app's number never goes down
244
244
  async function contract(specDir, dirs) {
245
245
  const file = join(specDir, 'contract.json')
246
246
  const shapes = await Promise.all(dirs.map((dir) => shapeOf(join(specDir, dir))))
247
- const json = JSON.stringify(shapes.map((s) => s.stored))
247
+ const json = JSON.stringify([internal.contract.version, ...shapes.map((s) => s.stored)])
248
248
  const shape = b4a.toString(crypto.hash(b4a.from(json)), 'hex')
249
249
  const kept = await fs.readFile(file, 'utf-8').then(JSON.parse, () => null)
250
250
  const version = kept
@@ -3,6 +3,8 @@ import { COUNTERS, EPOCHS, REMOVALS, REFUSALS, SPENT } from '../lib/constants.js
3
3
  import * as schemas from './schemas.js'
4
4
 
5
5
  // internal refs by scope; kind defaults to collection
6
+ export const { contract } = schemas
7
+
6
8
  export const defs = {
7
9
  main: {
8
10
  members: { type: 'member' },
@@ -222,16 +222,23 @@ export const local = {
222
222
  environment: {
223
223
  channel: required(string)
224
224
  },
225
- // the handles rows a cold push process can read without the root: topic → handle and its key
225
+ // the handles rows a cold push process can read without the root: topic → handle, its keys and
226
+ // the epochs it learned, so a push's block opens there too
226
227
  subscription: {
227
228
  id: required(string),
228
229
  handle: required(string),
229
230
  type: required(string),
230
231
  key: required(bytes),
231
- name: string
232
+ name: string,
233
+ encryptionKey: bytes,
234
+ epochs: bytes
232
235
  }
233
236
  }
234
237
 
238
+ // what a write means to apply. A release that changes it without changing what is stored bumps
239
+ // this, so an app's next build raises its contract and devices on the old release skip the new writes
240
+ export const contract = { version: 1 }
241
+
235
242
  export const rpc = {
236
243
  'req-empty': {
237
244
  ok: bool
@@ -11,7 +11,7 @@ import { Identity } from '@cero-base/core/identity'
11
11
  import { Database } from '@cero-base/core/database'
12
12
  import { blobEpochKey, epochEntries } from '@cero-base/core/database/encryption'
13
13
  import { Pairing } from '@cero-base/core/pairing'
14
- import { verify } from '@cero-base/core/push'
14
+ import { read } from '../push/index.js'
15
15
  import { Invite } from '@cero-base/core/invite'
16
16
  import { Mailbox } from '@cero-base/core/mailbox'
17
17
  import hid from 'hypercore-id-encoding'
@@ -366,7 +366,12 @@ export class Handle extends ReadyResource {
366
366
  // device checks its chain against
367
367
  /** @private */
368
368
  async _invite(opts = {}) {
369
- if (this.parent) return this._pair.invite(opts)
369
+ if (this.parent) {
370
+ const invite = await this._pair.invite(opts)
371
+ // a close right after the invite must not drop the row that reopens this handle at boot
372
+ await this._saved
373
+ return invite
374
+ }
370
375
  const { ttl = '2h' } = opts
371
376
  return this._pair.invite({ role: 'owner', confirm: true, ttl, data: this.identity.publicKey })
372
377
  }
@@ -566,7 +571,15 @@ export class Handle extends ReadyResource {
566
571
  if (!wanted.has(row.id)) await this.local.store.del('topics', row.id)
567
572
  }
568
573
  for (const [id, h] of wanted) {
569
- const row = { id, handle: h.id, type: h.type, key: h.key, name: h.name ?? null }
574
+ const row = {
575
+ id,
576
+ handle: h.id,
577
+ type: h.type,
578
+ key: h.key,
579
+ name: h.name ?? null,
580
+ encryptionKey: h.encryptionKey ?? null,
581
+ epochs: h.epochs && c.decode(epochEntries, h.epochs).length ? h.epochs : null
582
+ }
570
583
  if (same(have.get(id), row)) continue
571
584
  await this.local.store.put('topics', row)
572
585
  }
@@ -578,9 +591,7 @@ export class Handle extends ReadyResource {
578
591
  // a suspended storage answers no read: the cold entry serves a push while the app sleeps
579
592
  if (this._sus.suspended) throw CeroError.INVALID('receive: the app is suspended')
580
593
  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 }
594
+ return read(this.store.store.storage, this.spec, payload, rows)
584
595
  }
585
596
 
586
597
  /** @private */
@@ -1104,8 +1115,12 @@ export class Handle extends ReadyResource {
1104
1115
  if (!serving) return this.local.store.del('serving', child.id)
1105
1116
  await this.local.store.put('serving', { id: child.id, type: child.type })
1106
1117
  }
1107
- child._pair.on('serving', () => save().catch(this._onerror))
1108
- save().catch(this._onerror)
1118
+ // one at a time, so an invite can wait for its row
1119
+ const queue = () => {
1120
+ child._saved = (child._saved || Promise.resolve()).then(save).catch(this._onerror)
1121
+ }
1122
+ child._pair.on('serving', queue)
1123
+ queue()
1109
1124
  }
1110
1125
 
1111
1126
  /** @private */
@@ -1190,10 +1205,16 @@ function same(row, next) {
1190
1205
  row.handle === next.handle &&
1191
1206
  row.type === next.type &&
1192
1207
  (row.name ?? null) === next.name &&
1193
- b4a.equals(row.key, next.key)
1208
+ b4a.equals(row.key, next.key) &&
1209
+ sameBytes(row.encryptionKey, next.encryptionKey) &&
1210
+ sameBytes(row.epochs, next.epochs)
1194
1211
  )
1195
1212
  }
1196
1213
 
1214
+ function sameBytes(a, b) {
1215
+ return a && b ? b4a.equals(a, b) : (a ?? null) === (b ?? null)
1216
+ }
1217
+
1197
1218
  // run every teardown step, then surface the first failure: a bug must not leak the storage lock
1198
1219
  async function settle(steps) {
1199
1220
  let failed = null
@@ -496,7 +496,7 @@ export async function deactivate(ctx) {
496
496
  *
497
497
  * @param {Context} me
498
498
  * @param {Uint8Array} payload
499
- * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null } | null>}
499
+ * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null } | null>}
500
500
  */
501
501
  export async function receive(me, payload) {
502
502
  if (me.parent) throw CeroError.INVALID("receive is the app's, on me")
package/src/push/index.js CHANGED
@@ -3,11 +3,47 @@ import Corestore from 'corestore'
3
3
  import b4a from 'b4a'
4
4
  import safetyCatch from 'safety-catch'
5
5
 
6
- import { verify } from '@cero-base/core/push'
6
+ import c from 'compact-encoding'
7
+ import { verify, decrypt } from '@cero-base/core/push'
7
8
  import { CeroError } from '@cero-base/core/errors'
9
+ import { epochEntries } from '@cero-base/core/database/encryption'
8
10
 
9
11
  import { Local } from '../local/index.js'
10
12
 
13
+ /**
14
+ * A push verified against the handles the topics rows name, with the row it wrote when the block
15
+ * rode along and this device holds the handle's keys.
16
+ *
17
+ * @param {import('hypercore-storage')} storage
18
+ * @param {import('../lib/spec.js').Spec} spec
19
+ * @param {Uint8Array} payload
20
+ * @param {Array<{ id: string, handle: string, type: string, key: Uint8Array, name: string | null, encryptionKey?: Uint8Array | null, epochs?: Uint8Array | null }>} rows The root's `topics` rows.
21
+ * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null } | null>}
22
+ */
23
+ export async function read(storage, spec, payload, rows) {
24
+ const handles = rows.map(({ handle, key, type, name }) => ({ id: handle, key, type, name }))
25
+ const hit = await verify(storage, payload, handles)
26
+ if (!hit) return null
27
+ const keys = rows.find((r) => r.handle === hit.id)
28
+ const row = await rowOf(storage, spec, hit, keys)
29
+ return { id: hit.id, type: hit.type, name: hit.name, newer: hit.newer, ref: hit.ref, row }
30
+ }
31
+
32
+ // the row a push's block holds: null when none rode along, or it does not decode with what we hold
33
+ async function rowOf(storage, spec, hit, { encryptionKey, epochs }) {
34
+ if (!hit.block || !encryptionKey) return null
35
+ try {
36
+ const body = await decrypt(storage, hit, {
37
+ encryptionKey,
38
+ epochs: epochs ? c.decode(epochEntries, epochs) : []
39
+ })
40
+ return body ? (spec.handles[hit.type].dispatch.decode(body).value ?? null) : null
41
+ } catch (err) {
42
+ safetyCatch(err)
43
+ return null
44
+ }
45
+ }
46
+
11
47
  /**
12
48
  * A push the platform delivered while the app is dead, verified from its storage opened
13
49
  * read-only. `null` while the live app holds the storage, which shows the activity itself, and
@@ -17,7 +53,7 @@ import { Local } from '../local/index.js'
17
53
  * @param {import('../lib/spec.js').Spec} spec
18
54
  * @param {Uint8Array} payload
19
55
  * @param {{ storageKey?: Uint8Array }} [opts] The key `cero()` encrypts the local store with, if any.
20
- * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null } | null>}
56
+ * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null } | null>}
21
57
  */
22
58
  export async function receive(dir, spec, payload, { storageKey } = {}) {
23
59
  const storage = new HypercoreStorage(`${dir}/main`, { readOnly: true })
@@ -29,9 +65,7 @@ export async function receive(dir, spec, payload, { storageKey } = {}) {
29
65
  local = new Local(null, spec, { store, storageKey })
30
66
  await local.ready()
31
67
  const { data: rows } = await local.store.get('topics')
32
- const handles = rows.map(({ handle, key, type, name }) => ({ id: handle, key, type, name }))
33
- const hit = await verify(storage, payload, handles)
34
- return hit && { id: hit.id, type: hit.type, name: hit.name, newer: hit.newer, ref: hit.ref }
68
+ return await read(storage, spec, payload, rows)
35
69
  } catch (err) {
36
70
  safetyCatch(err)
37
71
  return null
@@ -44,16 +78,16 @@ export async function receive(dir, spec, payload, { storageKey } = {}) {
44
78
 
45
79
  /**
46
80
  * The bare-kit push entry: on each push the OS hands this worklet, verify it and, for one about
47
- * new data on a handle this device holds, answer with what `show` returns: the notification,
48
- * `{ title, body }`, or nothing. The request carries `storage`, `payload` (base64) and, when the
81
+ * new data on a handle this device holds, answer with what the show handler returns: the
82
+ * notification, `{ title, body }`, or nothing. The request carries `storage`, `payload` (base64) and, when the
49
83
  * app encrypts its local store, `storageKey` (base64).
50
84
  *
51
85
  * @param {import('../lib/spec.js').Spec} spec
52
- * @param {(push: { id: string, type: string, name: string | null, newer: boolean, ref: string | null }) => { title: string, body: string } | null | undefined | Promise<{ title: string, body: string } | null | undefined>} show What to show for a verified push, as `cero.receive` would give it to the app.
86
+ * @param {(push: { id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null }) => { title: string, body: string } | null | undefined | Promise<{ title: string, body: string } | null | undefined>} show The show handler: what to show for a verified push, as `cero.receive` would give it to the app.
53
87
  * @returns {void}
54
88
  */
55
89
  export function push(spec, show) {
56
- if (typeof show !== 'function') throw CeroError.INVALID('push: show(push) says what to show')
90
+ if (typeof show !== 'function') throw CeroError.INVALID('push: a show handler says what to show')
57
91
  globalThis.BareKit.on('push', async (json, reply) => {
58
92
  let shown = null
59
93
  try {
@@ -1,3 +1,6 @@
1
+ export declare const contract: {
2
+ version: number;
3
+ };
1
4
  export declare const defs: {
2
5
  main: {
3
6
  members: {
@@ -190,8 +190,13 @@ export declare const local: {
190
190
  type: import("@cero-base/core").Prim;
191
191
  key: import("@cero-base/core").Prim;
192
192
  name: import("@cero-base/core").Prim;
193
+ encryptionKey: import("@cero-base/core").Prim;
194
+ epochs: import("@cero-base/core").Prim;
193
195
  };
194
196
  };
197
+ export declare const contract: {
198
+ version: number;
199
+ };
195
200
  export declare const rpc: {
196
201
  'req-empty': {
197
202
  ok: import("@cero-base/core").Prim;
@@ -55,6 +55,7 @@ export declare const cero: {
55
55
  name: string | null;
56
56
  newer: boolean;
57
57
  ref: string | null;
58
+ row: object | null;
58
59
  } | null>;
59
60
  phrase(me: operators.Context): Promise<string>;
60
61
  nearby(ctx: operators.Context, on: boolean, opts?: {
@@ -235,7 +235,7 @@ export declare function deactivate(ctx: Context): Promise<void>;
235
235
  *
236
236
  * @param {Context} me
237
237
  * @param {Uint8Array} payload
238
- * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null } | null>}
238
+ * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null } | null>}
239
239
  */
240
240
  export declare function receive(me: Context, payload: Uint8Array): Promise<{
241
241
  id: string;
@@ -243,6 +243,7 @@ export declare function receive(me: Context, payload: Uint8Array): Promise<{
243
243
  name: string | null;
244
244
  newer: boolean;
245
245
  ref: string | null;
246
+ row: object | null;
246
247
  } | null>;
247
248
  /**
248
249
  * Reveal the recovery phrase.
@@ -1,3 +1,29 @@
1
+ /**
2
+ * A push verified against the handles the topics rows name, with the row it wrote when the block
3
+ * rode along and this device holds the handle's keys.
4
+ *
5
+ * @param {import('hypercore-storage')} storage
6
+ * @param {import('../lib/spec.js').Spec} spec
7
+ * @param {Uint8Array} payload
8
+ * @param {Array<{ id: string, handle: string, type: string, key: Uint8Array, name: string | null, encryptionKey?: Uint8Array | null, epochs?: Uint8Array | null }>} rows The root's `topics` rows.
9
+ * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null } | null>}
10
+ */
11
+ export declare function read(storage: import('hypercore-storage'), spec: import('../lib/spec.js').Spec, payload: Uint8Array, rows: Array<{
12
+ id: string;
13
+ handle: string;
14
+ type: string;
15
+ key: Uint8Array;
16
+ name: string | null;
17
+ encryptionKey?: Uint8Array | null;
18
+ epochs?: Uint8Array | null;
19
+ }>): Promise<{
20
+ id: string;
21
+ type: string;
22
+ name: string | null;
23
+ newer: boolean;
24
+ ref: string | null;
25
+ row: object | null;
26
+ } | null>;
1
27
  /**
2
28
  * A push the platform delivered while the app is dead, verified from its storage opened
3
29
  * read-only. `null` while the live app holds the storage, which shows the activity itself, and
@@ -7,7 +33,7 @@
7
33
  * @param {import('../lib/spec.js').Spec} spec
8
34
  * @param {Uint8Array} payload
9
35
  * @param {{ storageKey?: Uint8Array }} [opts] The key `cero()` encrypts the local store with, if any.
10
- * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null } | null>}
36
+ * @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null } | null>}
11
37
  */
12
38
  export declare function receive(dir: string, spec: import('../lib/spec.js').Spec, payload: Uint8Array, { storageKey }?: {
13
39
  storageKey?: Uint8Array;
@@ -17,15 +43,16 @@ export declare function receive(dir: string, spec: import('../lib/spec.js').Spec
17
43
  name: string | null;
18
44
  newer: boolean;
19
45
  ref: string | null;
46
+ row: object | null;
20
47
  } | null>;
21
48
  /**
22
49
  * The bare-kit push entry: on each push the OS hands this worklet, verify it and, for one about
23
- * new data on a handle this device holds, answer with what `show` returns: the notification,
24
- * `{ title, body }`, or nothing. The request carries `storage`, `payload` (base64) and, when the
50
+ * new data on a handle this device holds, answer with what the show handler returns: the
51
+ * notification, `{ title, body }`, or nothing. The request carries `storage`, `payload` (base64) and, when the
25
52
  * app encrypts its local store, `storageKey` (base64).
26
53
  *
27
54
  * @param {import('../lib/spec.js').Spec} spec
28
- * @param {(push: { id: string, type: string, name: string | null, newer: boolean, ref: string | null }) => { title: string, body: string } | null | undefined | Promise<{ title: string, body: string } | null | undefined>} show What to show for a verified push, as `cero.receive` would give it to the app.
55
+ * @param {(push: { id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null }) => { title: string, body: string } | null | undefined | Promise<{ title: string, body: string } | null | undefined>} show The show handler: what to show for a verified push, as `cero.receive` would give it to the app.
29
56
  * @returns {void}
30
57
  */
31
58
  export declare function push(spec: import('../lib/spec.js').Spec, show: (push: {
@@ -34,6 +61,7 @@ export declare function push(spec: import('../lib/spec.js').Spec, show: (push: {
34
61
  name: string | null;
35
62
  newer: boolean;
36
63
  ref: string | null;
64
+ row: object | null;
37
65
  }) => {
38
66
  title: string;
39
67
  body: string;
@@ -47,6 +47,7 @@ declare const remote: {
47
47
  name: string | null;
48
48
  newer: boolean;
49
49
  ref: string | null;
50
+ row: object | null;
50
51
  } | null>;
51
52
  phrase(me: verbs.Context): Promise<string>;
52
53
  nearby(ctx: verbs.Context, on: boolean, opts?: {