@cero-base/core 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.
@@ -10,7 +10,7 @@ import { Identity } from '../identity/index.js'
10
10
  import { CeroError } from '../lib/errors.js'
11
11
 
12
12
  /**
13
- * Epoch key rotation for a database: mint a secret, seal it to every member, announce it
13
+ * Epoch key rotation for a database: mint a secret, seal it to every device, announce it
14
14
  * through the log, and on every peer learn the secrets addressed to it.
15
15
  */
16
16
  export class Rotation {
@@ -60,6 +60,7 @@ export class Rotation {
60
60
  keyring.add(row.stamp, entropy, row.epoch)
61
61
  try {
62
62
  await this._save()
63
+ this.db.emit('epoch')
63
64
  } catch (err) {
64
65
  // an epoch we cannot reload after a restart must not be used for writes
65
66
  keyring.remove(row.stamp)
@@ -107,7 +108,7 @@ export class Rotation {
107
108
  const stamp = this._mint()
108
109
  this.current = { entropy, stamp, epoch: 0 }
109
110
  try {
110
- const wrapped = seal(await this._members(), entropy)
111
+ const wrapped = seal(await this._devices(), entropy)
111
112
  const epoch = await this._announce(stamp, entropy, wrapped)
112
113
  if (!epoch) {
113
114
  // a stamp collision (~2^-32, or an adversarial pre-claim) is not a refusal
@@ -120,19 +121,20 @@ export class Rotation {
120
121
  }
121
122
  db.keyring.add(stamp, entropy, epoch)
122
123
  await this._save()
124
+ db.emit('epoch')
123
125
  return { epoch }
124
126
  } finally {
125
127
  this.current = null
126
128
  }
127
129
  }
128
130
 
131
+ // every seated device, readers' too: a member keeps reading on each of its devices
129
132
  /** @private */
130
- async _members() {
131
- const { data: members } = await this.db.get('members')
132
- if (!Array.isArray(members) || members.length === 0) {
133
- throw CeroError.INVALID('cannot rotate a database with no members')
134
- }
135
- return members
133
+ async _devices() {
134
+ const { data: devices } = await this.db.get('devices')
135
+ const keyed = devices.filter((d) => d.key)
136
+ if (keyed.length === 0) throw CeroError.INVALID('cannot rotate a database with no devices')
137
+ return keyed
136
138
  }
137
139
 
138
140
  // resolves the sequence apply assigned, 0 if it never applied
@@ -179,7 +181,8 @@ export class Rotation {
179
181
  // every envelope addressed to us is tried, a bad one must not lock us out
180
182
  /** @private */
181
183
  _unseal(row) {
182
- for (const entropy of opened(this.db.identity, row.wrapped)) {
184
+ const { identity, writerKey } = this.db
185
+ for (const entropy of opened(identity, hid.encode(writerKey), row.wrapped)) {
183
186
  if (entropy.byteLength !== 32) continue
184
187
  // a secret failing the row's commitment means the rotator sealed different ones
185
188
  if (row.commit && b4a.equals(crypto.hash(entropy), row.commit)) return entropy
@@ -214,8 +217,7 @@ export class Rotation {
214
217
  }
215
218
  const top = rows.reduce((a, b) => (b.epoch > a.epoch ? b : a))
216
219
  const recipients = new Set(c.decode(wraps, top.wrapped).map((w) => w.id))
217
- const { data: members } = await db.get('members')
218
- const ids = new Set(members.map((m) => m.id))
220
+ const ids = new Set((await this._devices()).map((d) => d.id))
219
221
  const sealedOut = !db.keyring.entropy(top.stamp)
220
222
  if (!sealedOut && recipients.size === ids.size && [...recipients].every((id) => ids.has(id))) {
221
223
  this._healedFor = null
@@ -1,58 +1,70 @@
1
1
  import sodium from 'sodium-universal'
2
2
  import IdentityKey from 'keet-identity-key'
3
+ import encoding from 'keet-identity-key/lib/encoding.js'
3
4
  import bip39 from 'bip39-mnemonic'
4
5
  import b4a from 'b4a'
6
+ import c from 'compact-encoding'
5
7
  import hid from 'hypercore-id-encoding'
6
8
 
7
9
  import { CeroError } from '../lib/errors.js'
8
10
 
11
+ const { ProofEncoding } = encoding
12
+
9
13
  const DERIVE_PATH = ['SLIP-0021', 'cero', 'v1', 'identity']
10
14
 
11
15
  /**
12
16
  * @typedef {{ publicKey: Uint8Array, secretKey: Uint8Array, id: string }} KeyPair
13
- * @typedef {{ publicKey: Uint8Array, secretKey: Uint8Array, encryptionKey: Uint8Array, seed: Uint8Array }} IdentityFields
17
+ *
18
+ * @typedef {object} IdentityFields
19
+ * @property {Uint8Array} publicKey The identity's public key.
20
+ * @property {Uint8Array} encryptionKey Its root encryption key, derived from the seed.
21
+ * @property {KeyPair} device This device's signing keypair.
22
+ * @property {Uint8Array} proof The device's chain of attestations back to the identity.
23
+ * @property {Uint8Array | null} [seed] The phrase's entropy: on the device that created or recovered the identity, never on a linked one.
24
+ *
25
+ * @typedef {{ identity: Uint8Array, device: Uint8Array }} Verified
14
26
  */
15
27
 
16
28
  /**
17
- * Long-lived user identity derived from a BIP-39 seed phrase.
29
+ * A user identity, as one of its devices holds it. The identity's secret key signs exactly one
30
+ * thing, a device's first proof, and is never kept: everything else is signed by the device key
31
+ * and carries the proof, so a stolen device leaks only itself.
18
32
  */
19
33
  export class Identity {
20
- /** @param {IdentityFields} keys */
21
- constructor(keys) {
34
+ /** @param {IdentityFields} fields */
35
+ constructor({ publicKey, encryptionKey, device, proof, seed = null }) {
22
36
  /**
23
37
  * Canonical z32-encoded public key.
24
38
  *
25
39
  * @type {string}
26
40
  */
27
- this.id = hid.encode(keys.publicKey)
28
- /** @type {Uint8Array} */
29
- this.publicKey = keys.publicKey
41
+ this.id = hid.encode(publicKey)
30
42
  /** @type {Uint8Array} */
31
- this.secretKey = keys.secretKey
43
+ this.publicKey = publicKey
32
44
  /**
33
45
  * Symmetric key for encrypting per-identity payloads.
34
46
  *
35
47
  * @type {Uint8Array}
36
48
  */
37
- this.encryptionKey = keys.encryptionKey
49
+ this.encryptionKey = encryptionKey
38
50
  /**
39
51
  * Hash of the public key — used as the swarm topic.
40
52
  *
41
53
  * @type {Uint8Array}
42
54
  */
43
- this.topic = topicOf(keys.publicKey)
44
- /**
45
- * Original 16- or 32-byte entropy.
46
- *
47
- * @type {Uint8Array}
48
- */
49
- this.seed = keys.seed
55
+ this.topic = topicOf(publicKey)
56
+ /** @type {KeyPair} */
57
+ this.device = { ...device, id: hid.encode(device.publicKey) }
58
+ /** @type {Uint8Array} */
59
+ this.proof = proof
60
+ /** @type {Uint8Array | null} */
61
+ this.seed = seed
50
62
  Object.freeze(this)
51
63
  }
52
64
 
53
65
  /**
54
- * Redacted — secretKey/encryptionKey/seed must never reach JSON.stringify
55
- * or a structured logger.
66
+ * Redacted — the device secret, encryptionKey and seed must never reach JSON.stringify or a
67
+ * structured logger.
56
68
  *
57
69
  * @returns {{ id: string }}
58
70
  */
@@ -65,31 +77,54 @@ export class Identity {
65
77
  }
66
78
 
67
79
  /**
68
- * Detached Ed25519 signature over `message`.
80
+ * A proof over `data`: this device's signature, under its chain to the identity.
69
81
  *
70
- * @param {Uint8Array} message
82
+ * @param {Uint8Array} data
71
83
  * @returns {Uint8Array}
72
84
  */
73
- sign(message) {
74
- const sig = b4a.alloc(sodium.crypto_sign_BYTES)
75
- sodium.crypto_sign_detached(sig, message, this.secretKey)
76
- return sig
85
+ sign(data) {
86
+ return IdentityKey.attestData(data, this.device, this.proof)
77
87
  }
78
88
 
79
89
  /**
80
- * Verify a signature against this identity's public key.
90
+ * A proof for a new device: this device attests it, one link further down the chain.
81
91
  *
82
- * @param {Uint8Array} message
83
- * @param {Uint8Array} signature
84
- * @returns {boolean}
92
+ * @param {Uint8Array} publicKey
93
+ * @returns {Uint8Array}
85
94
  */
86
- verify(message, signature) {
87
- return sodium.crypto_sign_verify_detached(signature, message, this.publicKey)
95
+ link(publicKey) {
96
+ return IdentityKey.attestDevice(publicKey, this.device, this.proof)
88
97
  }
89
98
 
90
99
  /**
91
- * Open a sealed box addressed to this identity (any device holding the seed-derived
92
- * keypair can open it).
100
+ * A device with no identity yet: it signs as itself, its own key standing for the identity,
101
+ * until one attests it.
102
+ *
103
+ * @param {KeyPair} [device] A fresh keypair by default.
104
+ * @returns {Promise<Identity>}
105
+ */
106
+ static async bare(device = Identity.randomKeyPair()) {
107
+ const proof = await IdentityKey.bootstrap({ identity: device }, device.publicKey)
108
+ return new Identity({ publicKey: device.publicKey, encryptionKey: null, device, proof })
109
+ }
110
+
111
+ /**
112
+ * The keys a proof chains through: the identity, then each device down to the signer.
113
+ *
114
+ * @param {Uint8Array} proof
115
+ * @returns {Uint8Array[]} Empty when it is not a proof.
116
+ */
117
+ static chain(proof) {
118
+ try {
119
+ const { identity, chain } = c.decode(ProofEncoding, proof)
120
+ return [identity, ...chain.map((link) => link.publicKey)]
121
+ } catch {
122
+ return []
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Open a sealed box addressed to this device.
93
128
  *
94
129
  * @param {Uint8Array} sealed
95
130
  * @returns {Uint8Array | null}
@@ -98,8 +133,8 @@ export class Identity {
98
133
  if (!b4a.isBuffer(sealed) || sealed.byteLength <= sodium.crypto_box_SEALBYTES) return null
99
134
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
100
135
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)
101
- sodium.crypto_sign_ed25519_pk_to_curve25519(publicKey, this.publicKey)
102
- sodium.crypto_sign_ed25519_sk_to_curve25519(secretKey, this.secretKey)
136
+ sodium.crypto_sign_ed25519_pk_to_curve25519(publicKey, this.device.publicKey)
137
+ sodium.crypto_sign_ed25519_sk_to_curve25519(secretKey, this.device.secretKey)
103
138
  const message = b4a.alloc(sealed.byteLength - sodium.crypto_box_SEALBYTES)
104
139
  const opened = sodium.crypto_box_seal_open(message, sealed, publicKey, secretKey)
105
140
  return opened ? message : null
@@ -111,24 +146,77 @@ export class Identity {
111
146
  * @returns {string}
112
147
  */
113
148
  toPhrase() {
149
+ if (!this.seed) {
150
+ throw CeroError.INVALID('no phrase on this device: it was linked, not created or recovered')
151
+ }
114
152
  return Identity.toPhrase(this.seed)
115
153
  }
116
154
 
117
155
  /**
118
- * An identity from its seed, 16 or 32 bytes; a fresh one without.
156
+ * An identity from its seed, 16 or 32 bytes; a fresh one without. The identity key attests
157
+ * `device` and is dropped.
119
158
  *
120
- * @param {{ seed?: Uint8Array | null, words?: 12 | 24 }} [opts] `words` sizes a fresh one.
159
+ * @param {{ seed?: Uint8Array | null, words?: 12 | 24, device?: KeyPair }} [opts] `words` sizes a fresh seed; `device` is a fresh keypair by default.
121
160
  * @returns {Promise<Identity>}
122
161
  */
123
- static async create({ seed = null, words = 12 } = {}) {
162
+ static async create({ seed = null, words = 12, device = Identity.randomKeyPair() } = {}) {
124
163
  seed ??= randomSeed(words)
125
164
  if (!b4a.isBuffer(seed) || (seed.byteLength !== 16 && seed.byteLength !== 32)) {
126
165
  throw CeroError.INVALID('seed must be 16 or 32 bytes')
127
166
  }
128
- const id = await IdentityKey.from({ mnemonic: bip39.entropyToMnemonic(seed) })
129
- const { publicKey, secretKey } = id.identityKeyPair
130
- const encryptionKey = id.keyChain.getSymmetricKey([...DERIVE_PATH, 'encryption'])
131
- return new Identity({ publicKey, secretKey, encryptionKey, seed })
167
+ const key = await IdentityKey.from({ mnemonic: bip39.entropyToMnemonic(seed) })
168
+ const publicKey = b4a.from(key.identityPublicKey)
169
+ const encryptionKey = key.keyChain.getSymmetricKey([...DERIVE_PATH, 'encryption'])
170
+ const proof = await IdentityKey.bootstrap({ identity: key.identityKeyPair }, device.publicKey)
171
+ key.clear()
172
+ return new Identity({ publicKey, encryptionKey, device, proof, seed })
173
+ }
174
+
175
+ /**
176
+ * The identity keypair a seed writes, for what only the identity itself may sign: the pointer
177
+ * core it is created with. Nothing else ever takes it.
178
+ *
179
+ * @param {Uint8Array} seed
180
+ * @returns {Promise<{ publicKey: Uint8Array, secretKey: Uint8Array }>}
181
+ */
182
+ static async keyPair(seed) {
183
+ const key = await IdentityKey.from({ mnemonic: bip39.entropyToMnemonic(seed) })
184
+ const { publicKey, secretKey } = key.identityKeyPair
185
+ const pair = { publicKey: b4a.from(publicKey), secretKey: b4a.from(secretKey) }
186
+ key.clear()
187
+ return pair
188
+ }
189
+
190
+ /**
191
+ * The identity as a stored or linked device holds it. The proof must chain `device` to it.
192
+ *
193
+ * @param {IdentityFields} fields
194
+ * @returns {Identity}
195
+ */
196
+ static from({ publicKey, encryptionKey, device, proof, seed = null }) {
197
+ const verified = Identity.verify(proof, null, publicKey)
198
+ if (!verified || !b4a.equals(verified.device, device.publicKey)) {
199
+ throw CeroError.INVALID('proof does not chain this device to the identity')
200
+ }
201
+ return new Identity({ publicKey, encryptionKey, device, proof, seed })
202
+ }
203
+
204
+ /**
205
+ * Who signed `data`: the identity a proof chains to and the device that signed, or null.
206
+ *
207
+ * @param {Uint8Array} proof
208
+ * @param {Uint8Array | null} [data] What the proof signs; null verifies the chain alone.
209
+ * @param {Uint8Array | null} [publicKey] The identity expected, any when omitted.
210
+ * @returns {Verified | null}
211
+ */
212
+ static verify(proof, data = null, publicKey = null) {
213
+ try {
214
+ const opts = publicKey ? { expectedIdentity: publicKey } : {}
215
+ const result = IdentityKey.verify(proof, data, opts)
216
+ return result && { identity: result.identityPublicKey, device: result.devicePublicKey }
217
+ } catch {
218
+ return null
219
+ }
132
220
  }
133
221
 
134
222
  /**
@@ -156,20 +244,7 @@ export class Identity {
156
244
  }
157
245
 
158
246
  /**
159
- * Verify a signature against an arbitrary public key.
160
- *
161
- * @param {Uint8Array} publicKey
162
- * @param {Uint8Array} message
163
- * @param {Uint8Array} signature
164
- * @returns {boolean}
165
- */
166
- static verify(publicKey, message, signature) {
167
- return sodium.crypto_sign_verify_detached(signature, message, publicKey)
168
- }
169
-
170
- /**
171
- * Seal a message to an identity's Ed25519 public key (sealed box over the curve25519
172
- * conversion).
247
+ * Seal a message to a device's Ed25519 public key (sealed box over the curve25519 conversion).
173
248
  *
174
249
  * @param {Uint8Array} publicKey
175
250
  * @param {Uint8Array} message
@@ -184,7 +259,7 @@ export class Identity {
184
259
  }
185
260
 
186
261
  /**
187
- * Generate a fresh Ed25519 keypair (for devices, blind invites, etc.).
262
+ * Generate a fresh Ed25519 keypair (for devices, writers, blind invites).
188
263
  *
189
264
  * @returns {KeyPair}
190
265
  */
package/src/lib/schema.js CHANGED
@@ -3,7 +3,7 @@ import { SINGLE, COLLECTION, ACTION } from './constants.js'
3
3
 
4
4
  /**
5
5
  * @typedef {{ prim: string, required?: boolean }} Prim
6
- * @typedef {{ kind: 'single' | 'collection' | 'action', fields: Record<string, Prim> }} TypeDef
6
+ * @typedef {{ kind: 'single' | 'collection' | 'action', fields: Record<string, Prim>, indexes?: Record<string, string[]>, own?: boolean, push?: boolean }} TypeDef
7
7
  * @typedef {{ [name: string]: TypeDef | Record<string, TypeDef> } & { local?: Record<string, TypeDef> }} SchemaDefs
8
8
  * @typedef {{ defs: SchemaDefs }} Schema
9
9
  */
@@ -39,24 +39,29 @@ export const t = {
39
39
  * Single-row table (one record, set/get by name).
40
40
  *
41
41
  * @param {Record<string, Prim>} fields
42
+ * @param {{ push?: boolean }} [opts] `push`: a write pushes a notification, see collection.
42
43
  * @returns {TypeDef}
43
44
  */
44
- single(fields) {
45
- return { kind: SINGLE, fields }
45
+ single(fields, opts) {
46
+ const def = { kind: SINGLE, fields }
47
+ if (opts?.push) def.push = true
48
+ return def
46
49
  },
47
50
 
48
51
  /**
49
52
  * Multi-row table keyed by `id`. `own` restricts a row to the member who wrote it — anyone
50
- * may add rows, but only the author changes or deletes theirs.
53
+ * may add rows, but only the author changes or deletes theirs. `push` makes a write to it push
54
+ * a notification to the other members' devices; what it says is the app's push worklet's.
51
55
  *
52
56
  * @param {Record<string, Prim>} fields
53
- * @param {{ indexes?: Record<string, string[]>, own?: boolean }} [opts]
57
+ * @param {{ indexes?: Record<string, string[]>, own?: boolean, push?: boolean }} [opts]
54
58
  * @returns {TypeDef}
55
59
  */
56
60
  collection(fields, opts) {
57
61
  const def = { kind: COLLECTION, fields }
58
62
  if (opts?.indexes) def.indexes = opts.indexes
59
63
  if (opts?.own) def.own = true
64
+ if (opts?.push) def.push = true
60
65
  return def
61
66
  },
62
67
 
@@ -64,10 +69,13 @@ export const t = {
64
69
  * RPC-style mutation that doesn't persist a row.
65
70
  *
66
71
  * @param {Record<string, Prim>} fields
72
+ * @param {{ push?: boolean }} [opts] `push`: a call pushes a notification, see collection.
67
73
  * @returns {TypeDef}
68
74
  */
69
- action(fields) {
70
- return { kind: ACTION, fields }
75
+ action(fields, opts) {
76
+ const def = { kind: ACTION, fields }
77
+ if (opts?.push) def.push = true
78
+ return def
71
79
  },
72
80
 
73
81
  /**
@@ -84,9 +84,8 @@ const encoding2 = {
84
84
  preencode(state, m) {
85
85
  c.fixed32.preencode(state, m.invite)
86
86
  c.fixed32.preencode(state, m.reply)
87
- c.fixed64.preencode(state, m.proof)
88
- c.fixed32.preencode(state, m.identity)
89
87
  c.fixed64.preencode(state, m.signature)
88
+ c.buffer.preencode(state, m.proof)
90
89
  state.end++ // max flag is 1 so always one byte
91
90
 
92
91
  if (m.ts) c.uint.preencode(state, m.ts)
@@ -96,9 +95,8 @@ const encoding2 = {
96
95
 
97
96
  c.fixed32.encode(state, m.invite)
98
97
  c.fixed32.encode(state, m.reply)
99
- c.fixed64.encode(state, m.proof)
100
- c.fixed32.encode(state, m.identity)
101
98
  c.fixed64.encode(state, m.signature)
99
+ c.buffer.encode(state, m.proof)
102
100
  c.uint.encode(state, flags)
103
101
 
104
102
  if (m.ts) c.uint.encode(state, m.ts)
@@ -107,16 +105,14 @@ const encoding2 = {
107
105
  const r0 = c.fixed32.decode(state)
108
106
  const r1 = c.fixed32.decode(state)
109
107
  const r2 = c.fixed64.decode(state)
110
- const r3 = c.fixed32.decode(state)
111
- const r4 = c.fixed64.decode(state)
108
+ const r3 = c.buffer.decode(state)
112
109
  const flags = c.uint.decode(state)
113
110
 
114
111
  return {
115
112
  invite: r0,
116
113
  reply: r1,
117
- proof: r2,
118
- identity: r3,
119
- signature: r4,
114
+ signature: r2,
115
+ proof: r3,
120
116
  ts: (flags & 1) !== 0 ? c.uint.decode(state) : 0
121
117
  }
122
118
  }
@@ -154,16 +150,21 @@ const encoding4_4 = c.array(encoding3)
154
150
  const encoding4 = {
155
151
  preencode(state, m) {
156
152
  c.uint.preencode(state, m.status)
157
- state.end++ // max flag is 8 so always one byte
153
+ state.end++ // max flag is 16 so always one byte
158
154
 
159
155
  if (m.reason) c.string.preencode(state, m.reason)
160
156
  if (m.key) c.fixed32.preencode(state, m.key)
161
157
  if (m.encryptionKey) c.buffer.preencode(state, m.encryptionKey)
162
158
  if (m.epochs) encoding4_4.preencode(state, m.epochs)
159
+ if (m.proof) c.buffer.preencode(state, m.proof)
163
160
  },
164
161
  encode(state, m) {
165
162
  const flags =
166
- (m.reason ? 1 : 0) | (m.key ? 2 : 0) | (m.encryptionKey ? 4 : 0) | (m.epochs ? 8 : 0)
163
+ (m.reason ? 1 : 0) |
164
+ (m.key ? 2 : 0) |
165
+ (m.encryptionKey ? 4 : 0) |
166
+ (m.epochs ? 8 : 0) |
167
+ (m.proof ? 16 : 0)
167
168
 
168
169
  c.uint.encode(state, m.status)
169
170
  c.uint.encode(state, flags)
@@ -172,6 +173,7 @@ const encoding4 = {
172
173
  if (m.key) c.fixed32.encode(state, m.key)
173
174
  if (m.encryptionKey) c.buffer.encode(state, m.encryptionKey)
174
175
  if (m.epochs) encoding4_4.encode(state, m.epochs)
176
+ if (m.proof) c.buffer.encode(state, m.proof)
175
177
  },
176
178
  decode(state) {
177
179
  const r0 = c.uint.decode(state)
@@ -182,7 +184,8 @@ const encoding4 = {
182
184
  reason: (flags & 1) !== 0 ? c.string.decode(state) : null,
183
185
  key: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
184
186
  encryptionKey: (flags & 4) !== 0 ? c.buffer.decode(state) : null,
185
- epochs: (flags & 8) !== 0 ? encoding4_4.decode(state) : null
187
+ epochs: (flags & 8) !== 0 ? encoding4_4.decode(state) : null,
188
+ proof: (flags & 16) !== 0 ? c.buffer.decode(state) : null
186
189
  }
187
190
  }
188
191
  }
@@ -75,7 +75,7 @@
75
75
  "name": "join",
76
76
  "namespace": "cero",
77
77
  "compact": false,
78
- "flagsPosition": 5,
78
+ "flagsPosition": 4,
79
79
  "fields": [
80
80
  {
81
81
  "name": "invite",
@@ -90,21 +90,15 @@
90
90
  "version": 1
91
91
  },
92
92
  {
93
- "name": "proof",
93
+ "name": "signature",
94
94
  "required": true,
95
95
  "type": "fixed64",
96
96
  "version": 1
97
97
  },
98
98
  {
99
- "name": "identity",
100
- "required": true,
101
- "type": "fixed32",
102
- "version": 1
103
- },
104
- {
105
- "name": "signature",
99
+ "name": "proof",
106
100
  "required": true,
107
- "type": "fixed64",
101
+ "type": "buffer",
108
102
  "version": 1
109
103
  },
110
104
  {
@@ -177,6 +171,12 @@
177
171
  "array": true,
178
172
  "type": "@cero/epoch",
179
173
  "version": 1
174
+ },
175
+ {
176
+ "name": "proof",
177
+ "required": false,
178
+ "type": "buffer",
179
+ "version": 1
180
180
  }
181
181
  ]
182
182
  },
package/src/lib/utils.js CHANGED
@@ -38,23 +38,24 @@ export function can(role, perm) {
38
38
  if (!PERMS.has(perm)) {
39
39
  throw CeroError.INVALID(`'${perm}' is not a permission: write, invite, assign or remove`)
40
40
  }
41
- const perms = ROLE_PERMS[role]
41
+ // an own key only: a role named after an object's own keys (constructor, __proto__) is none
42
+ const perms = Object.hasOwn(ROLE_PERMS, role) ? ROLE_PERMS[role] : null
42
43
  return !!perms && (perms.includes('*') || perms.includes(perm))
43
44
  }
44
45
 
45
46
  // an unknown role grants nothing; callers taking a role from an app must check it
46
47
  /** @type {(role: string) => boolean} */
47
48
  export function isRank(role) {
48
- return RANK[role] != null
49
+ return typeof role === 'string' && Object.hasOwn(RANK, role)
49
50
  }
50
51
 
51
52
  /** @type {(a: string, b: string) => boolean} */
52
53
  export function grants(a, b) {
53
- return RANK[a] != null && RANK[b] != null && RANK[a] >= RANK[b]
54
+ return isRank(a) && isRank(b) && RANK[a] >= RANK[b]
54
55
  }
55
56
  /** @type {(a: string, b: string) => boolean} */
56
57
  export function outranks(a, b) {
57
- return RANK[a] != null && RANK[b] != null && RANK[a] > RANK[b]
58
+ return isRank(a) && isRank(b) && RANK[a] > RANK[b]
58
59
  }
59
60
 
60
61
  /**
@@ -26,7 +26,6 @@ export function channelTopic(topic, channel) {
26
26
 
27
27
  /**
28
28
  * @typedef {object} NetworkOpts
29
- * @property {import('../identity/index.js').Identity} [identity] Long-lived keypair used as the swarm identity.
30
29
  * @property {Array<{ host: string, port: number }>} [bootstrap] Custom DHT bootstrap nodes.
31
30
  * @property {(remotePublicKey: Uint8Array, payload: unknown) => boolean} [firewall] Incoming-connection filter.
32
31
  * @property {Uint8Array[]} [relayThrough] Relay public keys to tunnel through.
@@ -45,7 +44,6 @@ export function channelTopic(topic, channel) {
45
44
  export class Network extends ReadyResource {
46
45
  /** @param {NetworkOpts} opts */
47
46
  constructor({
48
- identity,
49
47
  bootstrap,
50
48
  firewall,
51
49
  relayThrough,
@@ -58,7 +56,6 @@ export class Network extends ReadyResource {
58
56
  } = {}) {
59
57
  super()
60
58
  if (!store) throw CeroError.REQUIRED('store')
61
- this.identity = identity || null
62
59
  this.bootstrap = bootstrap || null
63
60
  this.firewall = firewall || null
64
61
  this.relayThrough = relayThrough || null
@@ -118,9 +115,6 @@ export class Network extends ReadyResource {
118
115
  adaptiveTimeout: { min: 150, max: 1000 }
119
116
  })
120
117
  const opts = { dht }
121
- if (this.identity) {
122
- opts.keyPair = { publicKey: this.identity.publicKey, secretKey: this.identity.secretKey }
123
- }
124
118
  if (this.firewall) opts.firewall = this.firewall
125
119
  if (this.relayThrough) opts.relayThrough = this.relayThrough
126
120
  if (this.backoffs) opts.backoffs = this.backoffs
@@ -202,10 +196,8 @@ export class Network extends ReadyResource {
202
196
  inject(stream, { isInitiator } = {}) {
203
197
  if (this.closing || this.closed) throw CeroError.CLOSED('Network')
204
198
  if (!stream) throw CeroError.REQUIRED('stream')
205
- // a raw duplex handshakes as this identity
206
- const keyPair = this.identity
207
- ? { publicKey: this.identity.publicKey, secretKey: this.identity.secretKey }
208
- : (this.swarm?.keyPair ?? undefined)
199
+ // a raw duplex handshakes as the swarm does
200
+ const keyPair = this.swarm?.keyPair ?? undefined
209
201
  const conn =
210
202
  stream.noiseStream === stream
211
203
  ? stream
@@ -278,6 +270,7 @@ export class Network extends ReadyResource {
278
270
  await this._blindPeering?.resume()
279
271
  // the lookups hyperswarm runs at resume can go out before the network is back
280
272
  this._relook(0)
273
+ this.emit('resume')
281
274
  }
282
275
 
283
276
  /**
@@ -368,9 +361,10 @@ export class Network extends ReadyResource {
368
361
  }
369
362
  }
370
363
 
364
+ // data, not packets: a peer that acked our opener and froze has answered nothing
371
365
  function dropIfSilent(conn) {
372
366
  const timer = setTimeout(() => {
373
- if (conn.rawStream.packetsReceived === 0) conn.destroy()
367
+ if (conn.rawStream.bytesReceived === 0) conn.destroy()
374
368
  }, SILENT_TIMEOUT)
375
369
  timer.unref()
376
370
  conn.once('close', () => clearTimeout(timer))