@cero-base/core 2.2.1 → 2.3.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/README.md +32 -212
- package/package.json +18 -9
- package/src/blobs/index.js +9 -0
- package/src/blobs/server.js +2 -0
- package/src/database/changes.js +1 -1
- package/src/database/dispatch.js +341 -209
- package/src/database/encryption.js +83 -33
- package/src/database/index.js +184 -83
- package/src/database/rotation.js +43 -30
- package/src/identity/index.js +20 -78
- package/src/index.js +3 -10
- package/src/lib/constants.js +2 -0
- package/src/lib/errors.js +3 -11
- package/src/lib/spec/index.js +136 -132
- package/src/lib/spec/schema.json +84 -99
- package/src/lib/utils.js +57 -3
- package/src/mailbox/inbox.js +103 -0
- package/src/mailbox/index.js +146 -0
- package/src/mailbox/post.js +69 -0
- package/src/network/discovery.js +26 -1
- package/src/network/index.js +105 -64
- package/src/network/presence.js +6 -2
- package/src/pairing/index.js +330 -254
- package/src/pairing/invite.js +83 -144
- package/src/pairing/request.js +54 -56
- package/src/rpc/index.js +18 -93
- package/src/rpc/peer.js +4 -1
- package/src/storage/index.js +78 -39
- package/types/blobs/index.d.ts +22 -9
- package/types/blobs/server.d.ts +4 -2
- package/types/database/changes.d.ts +2 -2
- package/types/database/dispatch.d.ts +19 -13
- package/types/database/encryption.d.ts +67 -29
- package/types/database/index.d.ts +144 -119
- package/types/database/rotation.d.ts +32 -13
- package/types/identity/index.d.ts +6 -47
- package/types/index.d.ts +3 -16
- package/types/lib/constants.d.ts +1 -0
- package/types/lib/errors.d.ts +3 -9
- package/types/lib/spec/index.d.ts +52 -16
- package/types/lib/utils.d.ts +40 -8
- package/types/mailbox/inbox.d.ts +52 -0
- package/types/mailbox/index.d.ts +111 -0
- package/types/mailbox/post.d.ts +37 -0
- package/types/network/discovery.d.ts +21 -5
- package/types/network/index.d.ts +64 -48
- package/types/network/presence.d.ts +17 -4
- package/types/pairing/index.d.ts +143 -134
- package/types/pairing/invite.d.ts +70 -114
- package/types/pairing/request.d.ts +58 -98
- package/types/rpc/index.d.ts +26 -44
- package/types/rpc/peer.d.ts +10 -7
- package/types/storage/index.d.ts +64 -54
- package/src/pairing/candidate.js +0 -123
- package/types/pairing/candidate.d.ts +0 -36
package/src/pairing/invite.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import
|
|
2
|
-
import sodium from 'sodium-universal'
|
|
1
|
+
import crypto from 'hypercore-crypto'
|
|
3
2
|
import b4a from 'b4a'
|
|
3
|
+
import ms from 'ms'
|
|
4
4
|
import z32 from 'z32'
|
|
5
5
|
import c from 'compact-encoding'
|
|
6
6
|
|
|
@@ -8,194 +8,133 @@ import { getEncoding } from '../lib/spec/index.js'
|
|
|
8
8
|
import { CeroError } from '../lib/errors.js'
|
|
9
9
|
|
|
10
10
|
const VERSION = 1
|
|
11
|
-
const
|
|
12
|
-
const
|
|
11
|
+
const Encoding = getEncoding('@cero/invite')
|
|
12
|
+
const [NS_KEY, NS_PROOF] = crypto.namespace('cero/invite', 2)
|
|
13
13
|
|
|
14
14
|
/**
|
|
15
15
|
* @typedef {object} InviteFields
|
|
16
|
-
* @property {
|
|
17
|
-
* @property {
|
|
18
|
-
* @property {
|
|
19
|
-
* @property {Uint8Array
|
|
20
|
-
* @property {Uint8Array}
|
|
21
|
-
* @property {Uint8Array} [
|
|
22
|
-
* @property {string | null} [_str] Cached z32 string form.
|
|
23
|
-
*
|
|
24
|
-
* @typedef {object} CreateInviteOpts
|
|
25
|
-
* @property {Uint8Array} secretKey 64-byte Ed25519 secret key used to sign.
|
|
26
|
-
* @property {Uint8Array} publicKey 32-byte Ed25519 public key matching `secretKey`.
|
|
27
|
-
* @property {string} role Optional role tag for the joiner.
|
|
28
|
-
* @property {number} expiresIn TTL in ms from now; `0` means never expires.
|
|
29
|
-
* @property {any} data Caller payload; encoded via `encoding` when provided.
|
|
30
|
-
* @property {Uint8Array} blind Raw blind-pairing invite to wrap.
|
|
31
|
-
* @property {any} [encoding] compact-encoding type used to encode `data`.
|
|
32
|
-
*
|
|
33
|
-
* @typedef {object} ParseInviteOpts
|
|
34
|
-
* @property {any} [encoding] compact-encoding type used to decode the embedded payload.
|
|
16
|
+
* @property {number} expires Absolute expiry timestamp; `0` means never.
|
|
17
|
+
* @property {Uint8Array} key Key of the database the invite opens.
|
|
18
|
+
* @property {Uint8Array} address The database's address: a join is sealed to it.
|
|
19
|
+
* @property {Uint8Array} seed The invite's secret; its keypair proves a join.
|
|
20
|
+
* @property {{ key: Uint8Array, length: number } | null} link The node that added its record: a join links it, so no member applies the join first.
|
|
21
|
+
* @property {Uint8Array | null} [data] The app's payload, readable before joining. Unsigned: a hint, not proof.
|
|
35
22
|
*/
|
|
36
23
|
|
|
37
24
|
/**
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
* @property {any} [_rawData] Decoded payload kept alongside the encoded `data` for convenience.
|
|
43
|
-
* @property {Uint8Array} _discoveryKey Cached discovery key of the wrapped blind invite.
|
|
25
|
+
* An invite: the database it opens, the address a join is sealed to, and a seed whose keypair
|
|
26
|
+
* proves the joiner holds the invite. Role and expiry come from the database's own record;
|
|
27
|
+
* `expires` is here so a joiner fails fast.
|
|
44
28
|
*/
|
|
45
29
|
export class Invite {
|
|
46
|
-
/** @param {InviteFields} fields */
|
|
47
|
-
constructor(
|
|
30
|
+
/** @param {InviteFields & { _str?: string }} fields */
|
|
31
|
+
constructor({ expires, key, address, seed, link = null, data = null, _str = null }) {
|
|
48
32
|
this.version = VERSION
|
|
49
|
-
this.
|
|
50
|
-
this.
|
|
51
|
-
this.
|
|
52
|
-
this.
|
|
53
|
-
this.
|
|
54
|
-
this.
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
33
|
+
this.expires = expires
|
|
34
|
+
this.key = key
|
|
35
|
+
this.address = address
|
|
36
|
+
this.seed = seed
|
|
37
|
+
this.link = link
|
|
38
|
+
this.data = data
|
|
39
|
+
/** @private */
|
|
40
|
+
this._str = _str
|
|
41
|
+
/** @private */
|
|
42
|
+
this._keyPair = null
|
|
58
43
|
}
|
|
59
44
|
|
|
60
|
-
/**
|
|
61
|
-
* Whether the invite is past its TTL (always `false` when `expires === 0`).
|
|
62
|
-
*
|
|
63
|
-
* @returns {boolean}
|
|
64
|
-
*/
|
|
45
|
+
/** @returns {boolean} Whether the invite is past its expiry (never when `expires === 0`). */
|
|
65
46
|
get expired() {
|
|
66
47
|
return this.expires > 0 && Date.now() > this.expires
|
|
67
48
|
}
|
|
68
49
|
|
|
69
|
-
/**
|
|
70
|
-
* Discovery key of the wrapped blind-pairing invite — the topic it targets.
|
|
71
|
-
*
|
|
72
|
-
* @returns {Uint8Array}
|
|
73
|
-
*/
|
|
50
|
+
/** @returns {Uint8Array} Discovery key of the database the invite opens. */
|
|
74
51
|
get discoveryKey() {
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
52
|
+
return crypto.discoveryKey(this.key)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** @returns {Uint8Array} The invite's id: the public key of its seed's keypair. */
|
|
56
|
+
get id() {
|
|
57
|
+
return this._pair().publicKey
|
|
79
58
|
}
|
|
80
59
|
|
|
81
60
|
/**
|
|
82
|
-
*
|
|
61
|
+
* Sign a writer with the invite's key, proving the join in that writer's core comes from its
|
|
62
|
+
* holder.
|
|
83
63
|
*
|
|
84
|
-
* @
|
|
64
|
+
* @param {Uint8Array} writer
|
|
65
|
+
* @returns {Uint8Array}
|
|
85
66
|
*/
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
67
|
+
prove(writer) {
|
|
68
|
+
return crypto.sign(crypto.hash([NS_PROOF, writer]), this._pair().secretKey)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** @returns {string} The z32 wire form. */
|
|
72
|
+
toString() {
|
|
73
|
+
this._str ??= z32.encode(c.encode(Encoding, this))
|
|
74
|
+
return this._str
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** @private */
|
|
78
|
+
_pair() {
|
|
79
|
+
this._keyPair ??= crypto.keyPair(crypto.hash([NS_KEY, this.seed]))
|
|
80
|
+
return this._keyPair
|
|
89
81
|
}
|
|
90
82
|
|
|
91
83
|
/**
|
|
92
|
-
*
|
|
84
|
+
* Whether `proof` is the invite `id`'s signature over `writer`.
|
|
93
85
|
*
|
|
94
|
-
* @
|
|
86
|
+
* @param {Uint8Array} id
|
|
87
|
+
* @param {Uint8Array} writer
|
|
88
|
+
* @param {Uint8Array} proof
|
|
89
|
+
* @returns {boolean}
|
|
95
90
|
*/
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
const buf = c.encode(Envelope, this)
|
|
99
|
-
this._str = z32.encode(buf)
|
|
100
|
-
return this._str
|
|
91
|
+
static proven(id, writer, proof) {
|
|
92
|
+
return crypto.verify(crypto.hash([NS_PROOF, writer]), proof, id)
|
|
101
93
|
}
|
|
102
94
|
|
|
103
95
|
/**
|
|
104
|
-
*
|
|
96
|
+
* A new invite with a fresh seed.
|
|
105
97
|
*
|
|
106
|
-
* @param {
|
|
98
|
+
* @param {{ ttl?: number | string, key: Uint8Array, address: Uint8Array, link?: { key: Uint8Array, length: number } | null, data?: Uint8Array | null }} opts
|
|
107
99
|
* @returns {Invite}
|
|
108
100
|
*/
|
|
109
|
-
static create({
|
|
110
|
-
if (
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
if (!
|
|
114
|
-
|
|
115
|
-
}
|
|
116
|
-
if (!b4a.isBuffer(blind)) {
|
|
117
|
-
throw CeroError.INVALID('blind invite must be a buffer')
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
const expires = expiresIn ? Date.now() + expiresIn : 0
|
|
121
|
-
const encoded = data == null ? null : encoding ? c.encode(encoding, data) : data
|
|
122
|
-
|
|
123
|
-
const fields = {
|
|
124
|
-
version: VERSION,
|
|
125
|
-
publicKey,
|
|
126
|
-
role: role || '',
|
|
101
|
+
static create({ ttl = 0, key, address, link = null, data = null }) {
|
|
102
|
+
if (key?.byteLength !== 32) throw CeroError.INVALID('key must be a 32-byte buffer')
|
|
103
|
+
if (address?.byteLength !== 32) throw CeroError.INVALID('address must be a 32-byte buffer')
|
|
104
|
+
const expires = ttl ? Date.now() + toMs(ttl) : 0
|
|
105
|
+
if (data !== null && !b4a.isBuffer(data)) throw CeroError.INVALID('data must be a buffer')
|
|
106
|
+
return new Invite({
|
|
127
107
|
expires,
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
sodium.crypto_sign_detached(sig, body, secretKey)
|
|
135
|
-
fields.sig = sig
|
|
136
|
-
|
|
137
|
-
const inv = new Invite(fields)
|
|
138
|
-
inv._rawData = data // remember decoded form for convenience
|
|
139
|
-
return inv
|
|
108
|
+
key,
|
|
109
|
+
address,
|
|
110
|
+
seed: crypto.randomBytes(32),
|
|
111
|
+
link,
|
|
112
|
+
data
|
|
113
|
+
})
|
|
140
114
|
}
|
|
141
115
|
|
|
142
116
|
/**
|
|
143
|
-
* Parse
|
|
144
|
-
* its payload.
|
|
117
|
+
* Parse an invite string.
|
|
145
118
|
*
|
|
146
119
|
* @param {string} str
|
|
147
|
-
* @param {ParseInviteOpts} [opts]
|
|
148
120
|
* @returns {Invite}
|
|
149
121
|
*/
|
|
150
|
-
static parse(str
|
|
122
|
+
static parse(str) {
|
|
151
123
|
if (typeof str !== 'string') throw CeroError.INVALID_INVITE('invite must be a string')
|
|
152
|
-
|
|
153
|
-
let buf
|
|
154
|
-
try {
|
|
155
|
-
buf = z32.decode(str)
|
|
156
|
-
} catch {
|
|
157
|
-
throw CeroError.INVALID_INVITE('invite is not valid z32')
|
|
158
|
-
}
|
|
159
|
-
|
|
160
124
|
let fields
|
|
161
125
|
try {
|
|
162
|
-
fields = c.decode(
|
|
126
|
+
fields = c.decode(Encoding, z32.decode(str))
|
|
163
127
|
} catch {
|
|
164
|
-
throw CeroError.INVALID_INVITE('
|
|
128
|
+
throw CeroError.INVALID_INVITE('not an invite')
|
|
165
129
|
}
|
|
166
|
-
|
|
167
130
|
if (fields.version !== VERSION) throw CeroError.INVALID_INVITE('unknown invite version')
|
|
168
|
-
|
|
169
|
-
const inv = new Invite({ ...fields, _str: str })
|
|
170
|
-
if (!inv.verify()) throw CeroError.INVALID_INVITE('invite signature is invalid')
|
|
171
|
-
|
|
172
|
-
if (encoding && inv.data) {
|
|
173
|
-
try {
|
|
174
|
-
inv._rawData = c.decode(encoding, inv.data)
|
|
175
|
-
} catch {
|
|
176
|
-
throw CeroError.INVALID_INVITE('invite data failed to decode')
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
return inv
|
|
131
|
+
return new Invite({ ...fields, _str: str })
|
|
181
132
|
}
|
|
133
|
+
}
|
|
182
134
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
* @returns {boolean}
|
|
189
|
-
*/
|
|
190
|
-
static isInvite(str) {
|
|
191
|
-
if (typeof str !== 'string') return false
|
|
192
|
-
try {
|
|
193
|
-
const buf = z32.decode(str)
|
|
194
|
-
const fields = c.decode(Envelope, buf)
|
|
195
|
-
if (fields.blind) BlindPairing.decodeInvite(fields.blind)
|
|
196
|
-
return true
|
|
197
|
-
} catch {
|
|
198
|
-
return false
|
|
199
|
-
}
|
|
200
|
-
}
|
|
135
|
+
// ms, or a duration like '12h' or '2d'
|
|
136
|
+
function toMs(ttl) {
|
|
137
|
+
const value = typeof ttl === 'string' ? ms(ttl) : ttl
|
|
138
|
+
if (!Number.isFinite(value)) throw CeroError.INVALID(`ttl '${ttl}' is not a duration`)
|
|
139
|
+
return value
|
|
201
140
|
}
|
package/src/pairing/request.js
CHANGED
|
@@ -1,96 +1,94 @@
|
|
|
1
|
-
import
|
|
1
|
+
import hid from 'hypercore-id-encoding'
|
|
2
2
|
import c from 'compact-encoding'
|
|
3
|
-
import { keyPair, sign } from 'hypercore-crypto'
|
|
4
3
|
|
|
5
4
|
import { getEncoding } from '../lib/spec/index.js'
|
|
6
5
|
import { CeroError } from '../lib/errors.js'
|
|
6
|
+
import { grants, isRank } from '../lib/utils.js'
|
|
7
7
|
|
|
8
8
|
export const STATUS_ACCEPTED = 0
|
|
9
9
|
export const STATUS_DENIED = 1
|
|
10
10
|
|
|
11
|
-
//
|
|
11
|
+
// an accept and a deny both ride this response
|
|
12
|
+
/** @type {import('compact-encoding').Encoder<{ status: number, reason?: string, key?: Uint8Array | null, encryptionKey?: Uint8Array | null, epochs?: Array<{ epoch: number, stamp: number, entropy: Uint8Array }> | null }>} */
|
|
12
13
|
export const Response = getEncoding('@cero/confirm')
|
|
13
14
|
|
|
14
15
|
/**
|
|
15
|
-
* @typedef {object} ConfirmOpts
|
|
16
|
-
* @property {Uint8Array} [key] 32-byte resource key delivered to the joiner; required at runtime.
|
|
17
|
-
* @property {Uint8Array | null} [encryptionKey] Optional 32-byte symmetric key.
|
|
18
|
-
* @property {Uint8Array | null} [additional] Extra opaque bytes piggybacked on the response.
|
|
19
|
-
*
|
|
20
16
|
* @typedef {object} RequestOpts
|
|
21
17
|
* @property {import('./index.js').Pairing} pairing Owning Pairing instance.
|
|
22
|
-
* @property {
|
|
23
|
-
* @property {
|
|
24
|
-
*
|
|
25
|
-
* @
|
|
26
|
-
* @property {
|
|
18
|
+
* @property {{ id: string, role: string, expires?: number }} invite The record of the invite the joiner used.
|
|
19
|
+
* @property {{ id: string, identity: Uint8Array, reply: Uint8Array }} row The waiting join, as the database keeps it.
|
|
20
|
+
*
|
|
21
|
+
* @typedef {object} AcceptOpts
|
|
22
|
+
* @property {string} [role] Role granted: the invite's by default, at most the invite's.
|
|
27
23
|
*/
|
|
28
24
|
|
|
29
25
|
/**
|
|
30
|
-
*
|
|
31
|
-
* accept/deny.
|
|
32
|
-
*
|
|
33
|
-
* @property {boolean} _settled Whether confirm/deny has already run.
|
|
26
|
+
* A join on a `confirm` invite, waiting in the database for a member to accept or deny it.
|
|
34
27
|
*/
|
|
35
28
|
export class Request {
|
|
36
29
|
/** @param {RequestOpts} opts */
|
|
37
|
-
constructor(
|
|
38
|
-
this.pairing =
|
|
39
|
-
this.
|
|
40
|
-
this.
|
|
41
|
-
this.
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
this.
|
|
46
|
-
|
|
30
|
+
constructor({ pairing, invite, row }) {
|
|
31
|
+
this.pairing = pairing
|
|
32
|
+
this.invite = invite
|
|
33
|
+
this.id = row.id
|
|
34
|
+
this.identity = row.identity
|
|
35
|
+
/** The role the join asks for: its invite's. */
|
|
36
|
+
this.role = invite.role
|
|
37
|
+
/** @type {Uint8Array} */
|
|
38
|
+
this.writer = hid.decode(row.id)
|
|
39
|
+
/** @private */
|
|
40
|
+
this._reply = row.reply
|
|
41
|
+
/** @private */
|
|
42
|
+
this._answer = null
|
|
47
43
|
}
|
|
48
44
|
|
|
49
45
|
/**
|
|
50
|
-
*
|
|
46
|
+
* Admit the joiner. Every device of an inviter then replies with the keys. Idempotent.
|
|
51
47
|
*
|
|
52
|
-
* @param {
|
|
48
|
+
* @param {AcceptOpts} [opts]
|
|
53
49
|
* @returns {Promise<void>}
|
|
54
50
|
*/
|
|
55
|
-
async
|
|
56
|
-
if (this.
|
|
57
|
-
|
|
58
|
-
if (
|
|
59
|
-
|
|
51
|
+
async accept({ role } = {}) {
|
|
52
|
+
if (this._answer) return this._answer
|
|
53
|
+
const { invite } = this
|
|
54
|
+
if (invite.expires > 0 && Date.now() > invite.expires) throw CeroError.EXPIRED()
|
|
55
|
+
role = role || invite.role
|
|
56
|
+
if (!isRank(role)) {
|
|
57
|
+
throw CeroError.INVALID(`role '${role}' is not a rank (owner, admin, member, reader)`)
|
|
60
58
|
}
|
|
61
|
-
if (
|
|
62
|
-
throw CeroError.INVALID('
|
|
59
|
+
if (!grants(invite.role, role)) {
|
|
60
|
+
throw CeroError.INVALID(`role '${role}' exceeds the invite role '${invite.role}'`)
|
|
63
61
|
}
|
|
64
|
-
this.
|
|
62
|
+
return this._answering(this.pairing.db.call('accept', { id: this.id, role }))
|
|
65
63
|
}
|
|
66
64
|
|
|
67
65
|
/**
|
|
68
|
-
*
|
|
66
|
+
* Refuse the joiner, with an optional reason. Idempotent.
|
|
69
67
|
*
|
|
70
68
|
* @param {string} [reason]
|
|
71
69
|
* @returns {Promise<void>}
|
|
72
70
|
*/
|
|
73
71
|
async deny(reason = '') {
|
|
74
|
-
if (this.
|
|
75
|
-
this.
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
72
|
+
if (this._answer) return this._answer
|
|
73
|
+
const { db, mailbox } = this.pairing
|
|
74
|
+
const denied = { status: STATUS_DENIED, reason, key: null, encryptionKey: null, epochs: null }
|
|
75
|
+
const denying = async () => {
|
|
76
|
+
await db.call('del-request', { id: this.id })
|
|
77
|
+
await mailbox.send(this._reply, c.encode(Response, denied))
|
|
78
|
+
}
|
|
79
|
+
return this._answering(denying())
|
|
82
80
|
}
|
|
83
81
|
|
|
84
|
-
//
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
this.
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
additional: { data, signature }
|
|
82
|
+
// the first answer holds while it is written; refused, the request is answerable again
|
|
83
|
+
/**
|
|
84
|
+
* @private
|
|
85
|
+
* @param {Promise<void>} answer
|
|
86
|
+
*/
|
|
87
|
+
_answering(answer) {
|
|
88
|
+
this._answer = answer
|
|
89
|
+
answer.catch(() => {
|
|
90
|
+
this._answer = null
|
|
94
91
|
})
|
|
92
|
+
return answer
|
|
95
93
|
}
|
|
96
94
|
}
|
package/src/rpc/index.js
CHANGED
|
@@ -9,32 +9,24 @@ export { RPCClient } from './client.js'
|
|
|
9
9
|
|
|
10
10
|
const EMPTY = b4a.alloc(0)
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
const
|
|
14
|
-
const DEFAULT_CHANGES = getEncoding('@cero/changes')
|
|
15
|
-
const DEFAULT_QUERY = getEncoding('@cero/query')
|
|
16
|
-
const DEFAULT_CREATE = getEncoding('@cero/create')
|
|
12
|
+
const ROWS = getEncoding('@cero/rows')
|
|
13
|
+
const CREATE = getEncoding('@cero/create')
|
|
17
14
|
|
|
18
15
|
/**
|
|
19
16
|
* @typedef {object} Spec
|
|
20
|
-
* @property {{ encode: (type: string, value:
|
|
21
|
-
* @property {
|
|
22
|
-
* @property {
|
|
23
|
-
* @property {Codec} [codec] Filled in by `bindCodec`.
|
|
17
|
+
* @property {{ encode: (type: string, value: unknown) => Uint8Array, decode: (type: string, buf: Uint8Array) => unknown }} schema hyperschema-shaped module.
|
|
18
|
+
* @property {new (stream: import('streamx').Duplex) => object} [rpc] hrpc constructor used by RPCServer/RPCClient.
|
|
19
|
+
* @property {Codec} [codec] Filled in by `bindCodec`.
|
|
24
20
|
*
|
|
25
21
|
* @typedef {object} Codec
|
|
26
|
-
* @property {(type: string, row:
|
|
27
|
-
* @property {(type: string, buf: Uint8Array) =>
|
|
28
|
-
* @property {(type: string, rows:
|
|
29
|
-
* @property {(type: string,
|
|
30
|
-
* @property {(
|
|
31
|
-
* @property {(
|
|
32
|
-
* @property {(
|
|
33
|
-
* @property {(buf: Uint8Array) =>
|
|
34
|
-
* @property {(row: any) => Uint8Array} encodeCreate
|
|
35
|
-
* @property {(buf: Uint8Array) => any} decodeCreate
|
|
36
|
-
* @property {(handle: any, op: string, data: any) => Uint8Array} encodeAction
|
|
37
|
-
* @property {(handle: any, op: string, buf: Uint8Array) => any} decodeAction
|
|
22
|
+
* @property {(type: string, row: Record<string, unknown>) => Uint8Array} encodeRow
|
|
23
|
+
* @property {(type: string, buf: Uint8Array) => Record<string, unknown>} decodeRow
|
|
24
|
+
* @property {(type: string, rows: Record<string, unknown>[]) => Uint8Array} encodeRows
|
|
25
|
+
* @property {(type: string, buf: Uint8Array) => Record<string, unknown>[]} decodeRows
|
|
26
|
+
* @property {(row: Record<string, unknown>) => Uint8Array} encodeCreate
|
|
27
|
+
* @property {(buf: Uint8Array) => Record<string, unknown>} decodeCreate
|
|
28
|
+
* @property {(handle: Record<string, { schema?: string }>, op: string, data: unknown) => Uint8Array} encodeAction
|
|
29
|
+
* @property {(handle: Record<string, { schema?: string }>, op: string, buf: Uint8Array) => unknown} decodeAction
|
|
38
30
|
*/
|
|
39
31
|
|
|
40
32
|
/**
|
|
@@ -48,12 +40,6 @@ export function bindCodec(spec) {
|
|
|
48
40
|
const schema = spec.schema
|
|
49
41
|
if (!schema) throw CeroError.REQUIRED('spec.schema')
|
|
50
42
|
|
|
51
|
-
const ns = spec.meta?.ns
|
|
52
|
-
const ROWS = ns ? `@${ns}/rows` : null
|
|
53
|
-
const CHANGES = ns ? `@${ns}/changes` : null
|
|
54
|
-
const QUERY = ns ? `@${ns}/query` : null
|
|
55
|
-
const CREATE = ns ? `@${ns}/create` : null
|
|
56
|
-
|
|
57
43
|
spec.codec = {
|
|
58
44
|
encodeRow(type, row) {
|
|
59
45
|
if (row == null) return EMPTY
|
|
@@ -65,61 +51,20 @@ export function bindCodec(spec) {
|
|
|
65
51
|
},
|
|
66
52
|
encodeRows(type, rows) {
|
|
67
53
|
const data = (rows ?? []).map((r) => schema.encode(type, r))
|
|
68
|
-
return
|
|
54
|
+
return c.encode(ROWS, { data })
|
|
69
55
|
},
|
|
70
56
|
decodeRows(type, buf) {
|
|
71
57
|
if (!buf || buf.length === 0) return []
|
|
72
|
-
const
|
|
73
|
-
|
|
74
|
-
return data.map((b) => schema.decode(type, b))
|
|
75
|
-
},
|
|
76
|
-
encodeChanges(type, changes) {
|
|
77
|
-
const prev = changes.map((x) => (x.prev ? schema.encode(type, x.prev) : EMPTY))
|
|
78
|
-
const next = changes.map((x) => (x.next ? schema.encode(type, x.next) : EMPTY))
|
|
79
|
-
return encodeEnvelope(schema, CHANGES, DEFAULT_CHANGES, { prev, next })
|
|
80
|
-
},
|
|
81
|
-
decodeChanges(type, buf) {
|
|
82
|
-
if (!buf || buf.length === 0) return []
|
|
83
|
-
const env = decodeEnvelope(schema, CHANGES, DEFAULT_CHANGES, buf)
|
|
84
|
-
const prev = env?.prev || []
|
|
85
|
-
const next = env?.next || []
|
|
86
|
-
const out = []
|
|
87
|
-
for (let i = 0; i < Math.max(prev.length, next.length); i++) {
|
|
88
|
-
out.push({
|
|
89
|
-
prev: prev[i]?.length ? schema.decode(type, prev[i]) : null,
|
|
90
|
-
next: next[i]?.length ? schema.decode(type, next[i]) : null
|
|
91
|
-
})
|
|
92
|
-
}
|
|
93
|
-
return out
|
|
94
|
-
},
|
|
95
|
-
encodeQuery(q) {
|
|
96
|
-
if (q == null) return encodeEnvelope(schema, QUERY, DEFAULT_QUERY, {})
|
|
97
|
-
const { gt, gte, lt, lte, limit, reverse, ...rest } = q
|
|
98
|
-
const env = { gt, gte, lt, lte, limit, reverse }
|
|
99
|
-
if (Object.keys(rest).length > 0) env.data = rest
|
|
100
|
-
return encodeEnvelope(schema, QUERY, DEFAULT_QUERY, env)
|
|
101
|
-
},
|
|
102
|
-
decodeQuery(buf) {
|
|
103
|
-
if (!buf || buf.length === 0) return undefined
|
|
104
|
-
const env = decodeEnvelope(schema, QUERY, DEFAULT_QUERY, buf)
|
|
105
|
-
const out = {}
|
|
106
|
-
// hyperschema fills optional fields with 0/false, so only truthy fields are recovered; limit: 0 is lost
|
|
107
|
-
if (env.gt) out.gt = env.gt
|
|
108
|
-
if (env.gte) out.gte = env.gte
|
|
109
|
-
if (env.lt) out.lt = env.lt
|
|
110
|
-
if (env.lte) out.lte = env.lte
|
|
111
|
-
if (env.limit) out.limit = env.limit
|
|
112
|
-
if (env.reverse) out.reverse = env.reverse
|
|
113
|
-
if (env.data) Object.assign(out, env.data)
|
|
114
|
-
return Object.keys(out).length === 0 ? undefined : out
|
|
58
|
+
const { data } = c.decode(ROWS, buf)
|
|
59
|
+
return (data || []).map((b) => schema.decode(type, b))
|
|
115
60
|
},
|
|
116
61
|
encodeCreate(row) {
|
|
117
62
|
if (row == null) return EMPTY
|
|
118
|
-
return
|
|
63
|
+
return c.encode(CREATE, row)
|
|
119
64
|
},
|
|
120
65
|
decodeCreate(buf) {
|
|
121
66
|
if (!buf || buf.length === 0) return {}
|
|
122
|
-
return
|
|
67
|
+
return c.decode(CREATE, buf)
|
|
123
68
|
},
|
|
124
69
|
encodeAction(handle, op, data) {
|
|
125
70
|
const ref = handle?.[op]
|
|
@@ -136,23 +81,3 @@ export function bindCodec(spec) {
|
|
|
136
81
|
}
|
|
137
82
|
return spec
|
|
138
83
|
}
|
|
139
|
-
|
|
140
|
-
// the spec's own envelope type first, the built-in @cero encoding as fallback
|
|
141
|
-
function encodeEnvelope(schema, fqn, fallback, value) {
|
|
142
|
-
if (fqn && schemaHas(schema, fqn)) return schema.encode(fqn, value)
|
|
143
|
-
return c.encode(fallback, value)
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
function decodeEnvelope(schema, fqn, fallback, buf) {
|
|
147
|
-
if (fqn && schemaHas(schema, fqn)) return schema.decode(fqn, buf)
|
|
148
|
-
return c.decode(fallback, buf)
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
function schemaHas(schema, name) {
|
|
152
|
-
if (typeof schema.getEncoding !== 'function') return false
|
|
153
|
-
try {
|
|
154
|
-
return schema.getEncoding(name) != null
|
|
155
|
-
} catch {
|
|
156
|
-
return false
|
|
157
|
-
}
|
|
158
|
-
}
|
package/src/rpc/peer.js
CHANGED
|
@@ -11,7 +11,7 @@ import { CeroError } from '../lib/errors.js'
|
|
|
11
11
|
*/
|
|
12
12
|
export class RPCPeer extends ReadyResource {
|
|
13
13
|
/**
|
|
14
|
-
* @param {
|
|
14
|
+
* @param {import('streamx').Duplex} ipc Duplex IPC stream (e.g. a socket or pipe).
|
|
15
15
|
* @param {import('./index.js').Spec} spec Spec object exposing `rpc` and `schema`.
|
|
16
16
|
*/
|
|
17
17
|
constructor(ipc, spec) {
|
|
@@ -22,17 +22,20 @@ export class RPCPeer extends ReadyResource {
|
|
|
22
22
|
|
|
23
23
|
this.ipc = ipc
|
|
24
24
|
this.spec = spec
|
|
25
|
+
/** @type {import('framed-stream')} */
|
|
25
26
|
this.framed = new FramedStream(ipc)
|
|
26
27
|
this.rpc = new spec.rpc(this.framed)
|
|
27
28
|
// pause after hrpc attaches its listener, streamx resumes on attach
|
|
28
29
|
this.framed.pause()
|
|
29
30
|
}
|
|
30
31
|
|
|
32
|
+
/** @private */
|
|
31
33
|
async _open() {
|
|
32
34
|
if (!this.spec.codec) bindCodec(this.spec)
|
|
33
35
|
this.framed.resume()
|
|
34
36
|
}
|
|
35
37
|
|
|
38
|
+
/** @private */
|
|
36
39
|
async _close() {
|
|
37
40
|
if (this.framed && !this.framed.destroyed) {
|
|
38
41
|
try {
|