@cero-base/core 1.18.1 → 1.19.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.
Files changed (46) hide show
  1. package/README.md +5 -6
  2. package/package.json +9 -9
  3. package/src/blobs/index.js +2 -2
  4. package/src/database/changes.js +37 -59
  5. package/src/database/dispatch.js +31 -45
  6. package/src/database/index.js +395 -343
  7. package/src/database/rotation.js +201 -189
  8. package/src/identity/index.js +3 -3
  9. package/src/lib/utils.js +50 -18
  10. package/src/pairing/candidate.js +125 -0
  11. package/src/pairing/index.js +6 -223
  12. package/src/pairing/request.js +102 -0
  13. package/src/storage/index.js +11 -18
  14. package/types/blobs/codec.d.ts +8 -8
  15. package/types/blobs/index.d.ts +34 -33
  16. package/types/blobs/server.d.ts +8 -8
  17. package/types/database/changes.d.ts +5 -7
  18. package/types/database/dispatch.d.ts +30 -23
  19. package/types/database/encryption.d.ts +14 -10
  20. package/types/database/envelope.d.ts +2 -2
  21. package/types/database/index.d.ts +173 -181
  22. package/types/database/rotation.d.ts +53 -30
  23. package/types/identity/index.d.ts +81 -81
  24. package/types/index.d.ts +37 -51
  25. package/types/lib/constants.d.ts +34 -38
  26. package/types/lib/errors.d.ts +10 -10
  27. package/types/lib/schema.d.ts +47 -37
  28. package/types/lib/spec/index.d.ts +29 -55
  29. package/types/lib/utils.d.ts +27 -17
  30. package/types/network/discovery.d.ts +7 -7
  31. package/types/network/index.d.ts +50 -48
  32. package/types/pairing/candidate.d.ts +37 -0
  33. package/types/pairing/index.d.ts +87 -139
  34. package/types/pairing/invite.d.ts +88 -88
  35. package/types/pairing/request.d.ts +135 -0
  36. package/types/rpc/client.d.ts +2 -2
  37. package/types/rpc/index.d.ts +33 -33
  38. package/types/rpc/peer.d.ts +9 -7
  39. package/types/rpc/server.d.ts +2 -2
  40. package/types/storage/index.d.ts +70 -68
  41. package/src/database/bootstrap.js +0 -133
  42. package/src/database/hooks.js +0 -112
  43. package/src/database/membership.js +0 -67
  44. package/types/database/bootstrap.d.ts +0 -20
  45. package/types/database/hooks.d.ts +0 -8
  46. package/types/database/membership.d.ts +0 -7
@@ -1,133 +0,0 @@
1
- import Hypercore from 'hypercore'
2
- import { Identity } from '../identity/index.js'
3
- import { CeroError } from '../lib/errors.js'
4
- import { toId, addWriterPayload } from '../lib/utils.js'
5
- import { wrap } from './envelope.js'
6
-
7
- /**
8
- * First-run device provisioning: mint a device writer keypair, persist it as a
9
- * writer, then swap the autobee's local core over to it. With `recovering`,
10
- * the swap happens FIRST and admission rides an optimistic append — the
11
- * backfilled genesis core is never appended to (autobee's contract: a writable
12
- * core has exactly one author, ever; resuming a replicated core is unsupported
13
- * and drops appends silently).
14
- *
15
- * @param {import('./index.js').Database} db
16
- * @param {{ name?: string | null, isMobile?: boolean, recovering?: boolean }} [opts]
17
- * @returns {Promise<{ id: Uint8Array, writer: import('../identity/index.js').KeyPair }>}
18
- */
19
- export async function bootstrap(db, { name, isMobile, recovering = false, timeout = 30000 } = {}) {
20
- const keyPair = Identity.randomKeyPair()
21
- const manifest = {
22
- version: db.store.manifestVersion,
23
- signers: [{ publicKey: keyPair.publicKey }]
24
- }
25
- const writerKey = Hypercore.key(manifest)
26
-
27
- if (recovering) {
28
- // swap before anything else: the genesis core then replicates as a REMOTE
29
- // writer, so its backfilled ops apply through the normal download path
30
- await swapWriter(db, keyPair, manifest)
31
- await waitForBackfill(db, timeout)
32
- await claimWriter(db, writerKey, timeout)
33
- await saveDevice(db, writerKey, { name, isMobile })
34
- } else {
35
- await saveWriter(db, writerKey, { name, isMobile })
36
- await swapWriter(db, keyPair, manifest)
37
- }
38
-
39
- return { id: writerKey, writer: keyPair }
40
- }
41
-
42
- // recovery has state to recover by definition — wait until replication has
43
- // delivered and applied it (the genesis device row is the first thing every
44
- // db writes), so a peer that never replicates fails loud instead of hanging
45
- async function waitForBackfill(db, timeout) {
46
- const deadline = Date.now() + timeout
47
- while (Date.now() < deadline) {
48
- if (db.closing || db.closed) throw CeroError.CLOSED('Database')
49
- const { data } = await db.get('devices')
50
- if (data.length > 0) return
51
- await db.bee.update()
52
- await new Promise((resolve) => setTimeout(resolve, 50))
53
- }
54
- throw CeroError.TIMED_OUT('recovery — no peer replicated')
55
- }
56
-
57
- // self-admission from the fresh core: the same master-signed add-writer op a
58
- // live device would write, appended optimistically so an unadmitted writer
59
- // can carry it — apply verifies the attestation and admits the core
60
- async function claimWriter(db, writerKey, timeout) {
61
- const encoded = db.spec.dispatch.encode(`@${db.ns}/add-writer`, {
62
- master: db.identity.publicKey,
63
- writer: writerKey,
64
- sig: db.identity.sign(addWriterPayload(db.key, writerKey, db.writerKey)),
65
- ts: Date.now()
66
- })
67
- await db.bee.append(wrap(db.version, encoded), { optimistic: true })
68
- await db.bee.update()
69
- if (!db.bee.writable) await db.whenWritable({ timeout })
70
- }
71
-
72
- async function saveDevice(db, writerKey, { name, isMobile }) {
73
- const ts = Date.now()
74
- await db.write([
75
- [
76
- 'set-device',
77
- {
78
- id: toId(writerKey),
79
- name: name || null,
80
- isMobile: isMobile === true,
81
- createdAt: ts,
82
- updatedAt: ts
83
- }
84
- ]
85
- ])
86
- }
87
-
88
- async function saveWriter(db, writerKey, { name, isMobile }) {
89
- const ts = Date.now()
90
- await db.write([
91
- [
92
- 'add-writer',
93
- {
94
- master: db.identity.publicKey,
95
- writer: writerKey,
96
- sig: db.identity.sign(addWriterPayload(db.key, writerKey, db.writerKey)),
97
- ts
98
- }
99
- ],
100
- [
101
- 'set-device',
102
- {
103
- id: toId(writerKey),
104
- name: name || null,
105
- isMobile: isMobile === true,
106
- createdAt: ts,
107
- updatedAt: ts
108
- }
109
- ]
110
- ])
111
- }
112
-
113
- // Writer rotation by reboot: close the bee and boot again with the device
114
- // keyPair — autobee's fully-supported path (a fresh boot re-drains the log
115
- // and rebuilds its own state, no upstream userData is touched). setLocal is
116
- // not usable here: appends made through the base right after a live rotation
117
- // queue without ever flushing (keet pre-writes the first op raw instead,
118
- // which needs autobee's private oplog encoding).
119
- async function swapWriter(db, keyPair, manifest) {
120
- const epochs = await db.bee.local.getUserData('cero/epochs')
121
-
122
- if (db.network) db.network.detach(db.bee)
123
- await db.bee.close()
124
- db.bee = null
125
-
126
- const deviceCore = db.store.namespace(db.namespace).get({ keyPair, manifest })
127
- await deviceCore.ready()
128
- if (epochs) await deviceCore.setUserData('cero/epochs', epochs)
129
- await deviceCore.close()
130
-
131
- db.keyPair = keyPair
132
- await db.openBee()
133
- }
@@ -1,112 +0,0 @@
1
- import safetyCatch from 'safety-catch'
2
-
3
- import { ACTION } from '../lib/constants.js'
4
- import { CeroError } from '../lib/errors.js'
5
-
6
- export function before(db, op, fn) {
7
- return addHook(db.beforeHooks, op, fn)
8
- }
9
-
10
- export function after(db, op, fn) {
11
- return addHook(db.afterHooks, op, fn)
12
- }
13
-
14
- export function onUpdate(db, fn, scope) {
15
- db.updaters.set(fn, scope || null)
16
- return () => db.updaters.delete(fn)
17
- }
18
-
19
- export function touch(db, nodes) {
20
- if (!db._byVerb) {
21
- db._byVerb = new Map()
22
- for (const [name, info] of Object.entries(db.refs)) {
23
- db._byVerb.set(info.verb || name, name)
24
- db._byVerb.set(name, name)
25
- }
26
- }
27
- for (const node of nodes) {
28
- try {
29
- const { name } = db.spec.dispatch.decode(node.value)
30
- const verb = name.slice(name.indexOf('/') + 1)
31
- const dash = verb.indexOf('-')
32
- const target = dash < 0 ? verb : verb.slice(dash + 1)
33
- const ref = db._byVerb.get(target)
34
- // an action's route handler writes wherever it wants, widen to all
35
- if (!ref || db.refs[ref]?.kind === ACTION) db._touched.add('*')
36
- else db._touched.add(ref)
37
- } catch {
38
- db._touched.add('*')
39
- }
40
- }
41
- }
42
-
43
- export function onApply(db, fn) {
44
- if (typeof fn !== 'function') return () => {}
45
- db.onApplyHooks.add(fn)
46
- return () => db.onApplyHooks.delete(fn)
47
- }
48
-
49
- export function observe(db, nodes) {
50
- for (const node of nodes) {
51
- let event
52
- try {
53
- const { name, value } = db.spec.dispatch.decode(node.value)
54
- const verb = name.slice(name.indexOf('/') + 1) // '@cero/set-messages' → 'set-messages'
55
- const dash = verb.indexOf('-')
56
- event = {
57
- op: dash < 0 ? verb : verb.slice(0, dash),
58
- name: dash < 0 ? verb : verb.slice(dash + 1),
59
- row: value,
60
- writerKey: node.key,
61
- seq: db._applySeq++
62
- }
63
- } catch (err) {
64
- safetyCatch(err)
65
- continue
66
- }
67
- for (const fn of db.onApplyHooks) {
68
- try {
69
- fn(event)
70
- } catch (err) {
71
- db._onerror(err)
72
- }
73
- }
74
- }
75
- }
76
-
77
- export async function runBefore(db, op, ctx) {
78
- const hooks = db.beforeHooks.get(op)
79
- if (hooks) {
80
- for (const fn of hooks) {
81
- const out = await fn(ctx)
82
- if (out === false) return false
83
- }
84
- }
85
- db.emit(`before:${op}`, ctx)
86
- return true
87
- }
88
-
89
- export async function runAfter(db, op, ctx) {
90
- const hooks = db.afterHooks.get(op)
91
- if (hooks) {
92
- for (const fn of hooks) {
93
- try {
94
- await fn(ctx)
95
- } catch (err) {
96
- db._onerror(err)
97
- }
98
- }
99
- }
100
- db.emit(`after:${op}`, ctx)
101
- }
102
-
103
- function addHook(map, op, fn) {
104
- if (typeof fn !== 'function') throw CeroError.INVALID('hook fn must be a function')
105
- let arr = map.get(op)
106
- if (!arr) map.set(op, (arr = []))
107
- arr.push(fn)
108
- return () => {
109
- const i = arr.indexOf(fn)
110
- if (i >= 0) arr.splice(i, 1)
111
- }
112
- }
@@ -1,67 +0,0 @@
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
- }
@@ -1,20 +0,0 @@
1
- /**
2
- * First-run device provisioning: mint a device writer keypair, persist it as a
3
- * writer, then swap the autobee's local core over to it. With `recovering`,
4
- * the swap happens FIRST and admission rides an optimistic append — the
5
- * backfilled genesis core is never appended to (autobee's contract: a writable
6
- * core has exactly one author, ever; resuming a replicated core is unsupported
7
- * and drops appends silently).
8
- *
9
- * @param {import('./index.js').Database} db
10
- * @param {{ name?: string | null, isMobile?: boolean, recovering?: boolean }} [opts]
11
- * @returns {Promise<{ id: Uint8Array, writer: import('../identity/index.js').KeyPair }>}
12
- */
13
- export function bootstrap(db: import("./index.js").Database, { name, isMobile, recovering, timeout }?: {
14
- name?: string | null;
15
- isMobile?: boolean;
16
- recovering?: boolean;
17
- }): Promise<{
18
- id: Uint8Array;
19
- writer: import("../identity/index.js").KeyPair;
20
- }>;
@@ -1,8 +0,0 @@
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>;
@@ -1,7 +0,0 @@
1
- export function claim(db: any): Promise<void>;
2
- export function claimOp(db: any): any;
3
- export function whenWritable(db: any, { timeout }?: {
4
- timeout?: number;
5
- }): Promise<any>;
6
- export function addWriter(db: any, publicKey: any): Promise<any>;
7
- export function removeWriter(db: any, publicKey: any): Promise<any>;