@dotrino/identity 0.136.0 → 0.136.2
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 +3 -2
- package/src/index.d.ts +60 -2
- package/src/index.js +364 -81
- package/src/node.js +29 -5
- package/types/acta.d.ts +397 -175
- package/types/assertion.d.ts +25 -18
- package/types/avatar.d.ts +14 -3
- package/types/capabilities.d.ts +110 -61
- package/types/content.d.ts +88 -45
- package/types/core.d.ts +578 -383
- package/types/keyid.d.ts +10 -3
- package/types/machine.d.ts +5 -1
- package/types/peerStore.d.ts +80 -0
- package/types/peerSync.d.ts +20 -6
- package/types/remote.d.ts +170 -42
- package/types/session.d.ts +74 -81
- package/types/sessionFlow.d.ts +108 -33
- package/types/vaultSeal.d.ts +21 -9
- package/vault/acta.js +245 -29
- package/vault/assertion.js +13 -4
- package/vault/avatar.js +12 -1
- package/vault/capabilities.js +56 -6
- package/vault/channel.js +18 -2
- package/vault/content.js +60 -6
- package/vault/core.js +419 -88
- package/vault/externalKeys.js +34 -2
- package/vault/facade.js +182 -24
- package/vault/globals.d.ts +60 -0
- package/vault/keyid.js +10 -1
- package/vault/machine.js +7 -1
- package/vault/nativeStore.js +21 -4
- package/vault/originPolicy.js +13 -2
- package/vault/peerStore.js +57 -10
- package/vault/peerSync.js +23 -4
- package/vault/remote.js +132 -32
- package/vault/session.js +24 -7
- package/vault/sessionFlow.js +43 -9
- package/vault/sync.js +59 -15
- package/vault/vault.js +78 -49
- package/vault/vaultSeal.js +18 -7
- package/vault/vendor/compat/VERSION.txt +1 -1
- package/vault/vendor/compat/advisory.js +58 -8
- package/vault/vendor/compat/index.js +57 -6
- package/vault/vendor/compat/ranges.js +12 -2
- package/vault/vendor/proxy-client/VERSION.txt +1 -1
- package/vault/vendor/proxy-client/client.js +41 -19
- package/vault/vendor/roadmap/manifests.js +23 -23
- package/vault/vendor/store/VERSION.txt +1 -1
- package/vault/vendor/vault/VERSION.txt +1 -1
- package/vault/vendor/vault/core/libVersion.js +1 -1
- package/vault/vendor/vault/core/transport.js +15 -3
- package/vault/vendor/vault/core/vault.js +71 -1
- package/vault/vendor/vault/protocol.js +25 -0
package/vault/nativeStore.js
CHANGED
|
@@ -23,7 +23,11 @@ const KV = 'kv:'
|
|
|
23
23
|
const KEY = 'key:'
|
|
24
24
|
const PEERS = 'peers:'
|
|
25
25
|
|
|
26
|
-
/**
|
|
26
|
+
/**
|
|
27
|
+
* El asa de una llave no se puede guardar en la app: solo su registro, que no tiene nada secreto.
|
|
28
|
+
* @param {any} rec
|
|
29
|
+
* @returns {{ external: string, kind: 'sign' | 'enc', publicJwk: JsonWebKey }}
|
|
30
|
+
*/
|
|
27
31
|
function plainKeyRecord (rec) {
|
|
28
32
|
if (rec && typeof rec.external === 'string' && rec.publicJwk && (rec.kind === 'sign' || rec.kind === 'enc')) {
|
|
29
33
|
return { external: rec.external, kind: rec.kind, publicJwk: rec.publicJwk }
|
|
@@ -34,6 +38,10 @@ function plainKeyRecord (rec) {
|
|
|
34
38
|
throw Object.assign(new Error('this app keeps keys in the phone chip only: a software key cannot be stored here'), { code: 'native-no-import' })
|
|
35
39
|
}
|
|
36
40
|
|
|
41
|
+
/**
|
|
42
|
+
* @param {{ call (method: string, params: any): Promise<any> }} bridge
|
|
43
|
+
* @returns {Promise<{ kv: import('./core.js').Kv, keyStore: import('./core.js').KeyStore, peers: import('./peerStore.js').PeerBackend, flush: () => Promise<void> }>}
|
|
44
|
+
*/
|
|
37
45
|
export async function nativeBackends (bridge) {
|
|
38
46
|
const { items } = await bridge.call('storeLoad', {})
|
|
39
47
|
if (!items || typeof items !== 'object') {
|
|
@@ -43,37 +51,46 @@ export async function nativeBackends (bridge) {
|
|
|
43
51
|
|
|
44
52
|
// Escrituras EN ORDEN: un `remove` que adelantara a su `set` resucitaría el dato. Una que
|
|
45
53
|
// falla se dice en la consola con su código (sin tragársela) y no frena a las siguientes.
|
|
54
|
+
/** @type {Promise<void>} */
|
|
46
55
|
let chain = Promise.resolve()
|
|
56
|
+
/** @param {string} method @param {any} params */
|
|
47
57
|
const write = (method, params) => {
|
|
48
58
|
chain = chain.then(() => bridge.call(method, params)).catch((e) => {
|
|
49
59
|
console.error(`[cc-identity] native store ${method} failed (${e?.code || 'error'}): ${e?.message}`)
|
|
50
60
|
})
|
|
51
61
|
return chain
|
|
52
62
|
}
|
|
63
|
+
/** @param {string} k @param {string} v */
|
|
53
64
|
const set = (k, v) => { mem.set(k, v); return write('storeSet', { k, v }) }
|
|
65
|
+
/** @param {string} k */
|
|
54
66
|
const del = (k) => { mem.delete(k); return write('storeRemove', { k }) }
|
|
55
67
|
|
|
56
68
|
const kv = {
|
|
57
|
-
getItem: (k) => (mem.has(KV + k) ? mem.get(KV + k) : null),
|
|
58
|
-
setItem: (k, v) => { set(KV + k, String(v)) },
|
|
59
|
-
removeItem: (k) => { del(KV + k) }
|
|
69
|
+
getItem: (/** @type {string} */ k) => (mem.has(KV + k) ? /** @type {string} */ (mem.get(KV + k)) : null),
|
|
70
|
+
setItem: (/** @type {string} */ k, /** @type {string} */ v) => { set(KV + k, String(v)) },
|
|
71
|
+
removeItem: (/** @type {string} */ k) => { del(KV + k) }
|
|
60
72
|
}
|
|
61
73
|
|
|
62
74
|
const keyStore = {
|
|
75
|
+
/** @param {string} name */
|
|
63
76
|
async get (name) {
|
|
64
77
|
const raw = mem.get(KEY + name)
|
|
65
78
|
return raw ? JSON.parse(raw) : null
|
|
66
79
|
},
|
|
80
|
+
/** @param {string} name @param {any} rec */
|
|
67
81
|
async set (name, rec) { await set(KEY + name, JSON.stringify(plainKeyRecord(rec))) },
|
|
82
|
+
/** @param {string} name */
|
|
68
83
|
async remove (name) { await del(KEY + name) }
|
|
69
84
|
}
|
|
70
85
|
|
|
71
86
|
// El libro de contactos por perfil (`peerStore.useBackend`).
|
|
72
87
|
const peers = {
|
|
88
|
+
/** @param {string} key */
|
|
73
89
|
async get (key) {
|
|
74
90
|
const raw = mem.get(PEERS + key)
|
|
75
91
|
return raw ? JSON.parse(raw) : null
|
|
76
92
|
},
|
|
93
|
+
/** @param {string} key @param {any} val */
|
|
77
94
|
async put (key, val) { await set(PEERS + key, JSON.stringify(val)) }
|
|
78
95
|
}
|
|
79
96
|
|
package/vault/originPolicy.js
CHANGED
|
@@ -35,26 +35,37 @@ const ALSO = Object.freeze({
|
|
|
35
35
|
rewrapFor: /^https:\/\/pass\.dotrino\.com$/
|
|
36
36
|
})
|
|
37
37
|
|
|
38
|
+
/**
|
|
39
|
+
* @param {{ selfOrigin?: string | null }} args
|
|
40
|
+
*/
|
|
38
41
|
export function originPolicy ({ selfOrigin }) {
|
|
39
42
|
const selfIsLocal = LOCAL.test(String(selfOrigin || ''))
|
|
43
|
+
/** @param {unknown} origin @returns {boolean} */
|
|
40
44
|
const isConsole = (origin) => CONSOLE.test(String(origin || '')) || (selfIsLocal && LOCAL.test(String(origin || '')))
|
|
41
45
|
const only = new Set(CONSOLE_ONLY)
|
|
42
46
|
|
|
43
47
|
/**
|
|
44
48
|
* Lanza `console-only` si `origin` no puede pedir `method` con estos parámetros. Lo demás pasa.
|
|
45
49
|
* `me` es la llave pública del perfil activo (para el certificado de uno mismo).
|
|
50
|
+
*
|
|
51
|
+
* @param {string} method
|
|
52
|
+
* @param {any} params
|
|
53
|
+
* @param {unknown} origin
|
|
54
|
+
* @param {{ me?: string | null }} [opts]
|
|
46
55
|
*/
|
|
47
56
|
function check (method, params, origin, { me = null } = {}) {
|
|
48
57
|
if (isConsole(origin)) return
|
|
58
|
+
/** @param {string} why @returns {never} */
|
|
49
59
|
const deny = (why) => { throw Object.assign(new Error(`${method}: ${why}`), { code: 'console-only' }) }
|
|
50
60
|
if (only.has(method)) deny('only the vault console (vault.dotrino.com, profile.dotrino.com) can ask for this')
|
|
51
|
-
|
|
61
|
+
const also = /** @type {Record<string, RegExp | undefined>} */ (ALSO)[method]
|
|
62
|
+
if (also && !also.test(String(origin || ''))) deny('this origin cannot ask for this')
|
|
52
63
|
if (method === 'signDelegation') {
|
|
53
64
|
// Un certificado con poder sobre la bóveda (`vault:*`) es meter un aparato: eso es de la
|
|
54
65
|
// consola, con su invitación. Una app sí firma lo suyo (geo: los aparatos de here) y su
|
|
55
66
|
// propio certificado (`sub` = el perfil: el de terminal y el de ia).
|
|
56
67
|
const scopes = Array.isArray(params?.scope) ? params.scope : [params?.scope]
|
|
57
|
-
const vaultPower = scopes.some((s) => typeof s !== 'string' || s.startsWith('vault:'))
|
|
68
|
+
const vaultPower = scopes.some((/** @type {unknown} */ s) => typeof s !== 'string' || s.startsWith('vault:'))
|
|
58
69
|
if (vaultPower && !(me && params?.sub === me)) deny('a certificate with vault powers is issued from the vault console, with an invitation')
|
|
59
70
|
}
|
|
60
71
|
}
|
package/vault/peerStore.js
CHANGED
|
@@ -26,11 +26,26 @@ const IDB_PEERS_KEY = 'peers.v1'
|
|
|
26
26
|
// perdiendo contactos que SIGUEN intactos en el localStorage viejo.
|
|
27
27
|
const IDB_MIGRATED_KEY = 'peers.migrated.v1'
|
|
28
28
|
|
|
29
|
+
/**
|
|
30
|
+
* La ficha de un contacto: `publickey` y lo que sus pantallas apunten (apodo, avatar, fechas).
|
|
31
|
+
* @typedef {{ publickey: string, firstSeen?: number, lastSeen?: number, changedAt?: number } & Record<string, any>} PeerRecord
|
|
32
|
+
*/
|
|
33
|
+
/** El libro de contactos: pubkey → ficha. @typedef {Record<string, PeerRecord>} PeerBook */
|
|
34
|
+
/**
|
|
35
|
+
* Dónde guarda la app el libro (el almacén de la app nativa).
|
|
36
|
+
* @typedef {{ get (key: string): Promise<any>, put (key: string, val: any): Promise<void> }} PeerBackend
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
/** @type {PeerBook} */
|
|
29
40
|
let _peers = {}
|
|
30
41
|
let _fallback = false
|
|
42
|
+
/** @type {IDBDatabase | null} */
|
|
31
43
|
let _idb = null
|
|
44
|
+
/** @type {Promise<void>} */
|
|
32
45
|
let _writeChain = Promise.resolve()
|
|
46
|
+
/** @type {(() => void) | null} */
|
|
33
47
|
let _markDirty = null
|
|
48
|
+
/** @type {string | null} */
|
|
34
49
|
let _pid = null
|
|
35
50
|
/**
|
|
36
51
|
* La cuenta abierta es VOLÁTIL (se entró con usuario y contraseña sin «Recordar»): sus
|
|
@@ -45,13 +60,22 @@ let _volatile = false
|
|
|
45
60
|
* (`nativeStore.js`), que es uno para todas las páginas. `{ get(key), put(key, val) }`.
|
|
46
61
|
* Se pone antes de `initPeerStorage`.
|
|
47
62
|
*/
|
|
63
|
+
/** @type {PeerBackend | null} */
|
|
48
64
|
let _backend = null
|
|
65
|
+
/** @param {PeerBackend | null | undefined} b */
|
|
49
66
|
export function useBackend (b) { _backend = b || null }
|
|
50
67
|
|
|
51
|
-
/**
|
|
68
|
+
/**
|
|
69
|
+
* Registra el callback que marca el estado como "sucio" para el sync.
|
|
70
|
+
* @param {(() => void) | null} fn
|
|
71
|
+
*/
|
|
52
72
|
export function onDirty (fn) { _markDirty = fn }
|
|
53
73
|
|
|
54
|
-
/**
|
|
74
|
+
/**
|
|
75
|
+
* Multi-perfil: namespacea el peer book por perfil. El core lo llama antes de initPeerStorage.
|
|
76
|
+
* @param {string | null | undefined} pid
|
|
77
|
+
* @param {{ volatile?: boolean }} [opts]
|
|
78
|
+
*/
|
|
55
79
|
export function setProfile (pid, { volatile: esVolatil = false } = {}) {
|
|
56
80
|
_pid = pid || null
|
|
57
81
|
_volatile = !!esVolatil
|
|
@@ -59,7 +83,10 @@ export function setProfile (pid, { volatile: esVolatil = false } = {}) {
|
|
|
59
83
|
}
|
|
60
84
|
function peersKey () { return _pid ? `peers.${_pid}.v1` : IDB_PEERS_KEY }
|
|
61
85
|
|
|
62
|
-
/**
|
|
86
|
+
/**
|
|
87
|
+
* Migración: copia el peer book VIEJO (pre-multi-perfil, sin namespace) al perfil `pid`.
|
|
88
|
+
* @param {string} pid
|
|
89
|
+
*/
|
|
63
90
|
export async function adoptLegacy (pid) {
|
|
64
91
|
if (_backend) return // el almacén de la app nació después: no hay libro viejo que adoptar
|
|
65
92
|
try {
|
|
@@ -74,8 +101,10 @@ export async function adoptLegacy (pid) {
|
|
|
74
101
|
} catch (_) { /* sin peers viejos que adoptar */ }
|
|
75
102
|
}
|
|
76
103
|
|
|
104
|
+
/** @returns {Promise<IDBDatabase>} */
|
|
77
105
|
function openIdb () {
|
|
78
106
|
return new Promise((resolve, reject) => {
|
|
107
|
+
/** @type {IDBOpenDBRequest} */
|
|
79
108
|
let req
|
|
80
109
|
try { req = indexedDB.open(IDB_NAME, 1) } catch (e) { reject(e); return }
|
|
81
110
|
req.onupgradeneeded = () => {
|
|
@@ -86,6 +115,7 @@ function openIdb () {
|
|
|
86
115
|
req.onerror = () => reject(req.error)
|
|
87
116
|
})
|
|
88
117
|
}
|
|
118
|
+
/** @param {IDBDatabase} db @param {string} key @returns {Promise<any>} */
|
|
89
119
|
function idbGet (db, key) {
|
|
90
120
|
return new Promise((resolve, reject) => {
|
|
91
121
|
const tx = db.transaction(IDB_STORE, 'readonly')
|
|
@@ -94,8 +124,9 @@ function idbGet (db, key) {
|
|
|
94
124
|
r.onerror = () => reject(r.error)
|
|
95
125
|
})
|
|
96
126
|
}
|
|
127
|
+
/** @param {IDBDatabase} db @param {string} key @param {any} val @returns {Promise<void>} */
|
|
97
128
|
function idbPut (db, key, val) {
|
|
98
|
-
return new Promise((resolve, reject) => {
|
|
129
|
+
return new Promise(/** @param {(v?: void) => void} resolve @param {(e: unknown) => void} reject */ (resolve, reject) => {
|
|
99
130
|
const tx = db.transaction(IDB_STORE, 'readwrite')
|
|
100
131
|
tx.objectStore(IDB_STORE).put(val, key)
|
|
101
132
|
tx.oncomplete = () => resolve()
|
|
@@ -103,11 +134,13 @@ function idbPut (db, key, val) {
|
|
|
103
134
|
})
|
|
104
135
|
}
|
|
105
136
|
|
|
137
|
+
/** @returns {PeerBook} */
|
|
106
138
|
function readLocalPeers () {
|
|
107
139
|
try { const raw = localStorage.getItem(PEERS_STORAGE); return raw ? (JSON.parse(raw) || {}) : {} }
|
|
108
140
|
catch (_) { return {} }
|
|
109
141
|
}
|
|
110
142
|
|
|
143
|
+
/** @returns {Promise<PeerBook>} */
|
|
111
144
|
export async function initPeerStorage () {
|
|
112
145
|
try { if (typeof navigator !== 'undefined' && navigator.storage?.persist) await navigator.storage.persist() }
|
|
113
146
|
catch (_) { /* best-effort */ }
|
|
@@ -122,7 +155,7 @@ export async function initPeerStorage () {
|
|
|
122
155
|
const stored = await idbGet(_idb, peersKey()) // peer book DEL perfil activo (namespaceado)
|
|
123
156
|
_peers = (stored && typeof stored === 'object') ? stored : {}
|
|
124
157
|
} catch (e) {
|
|
125
|
-
console.warn('[cc-identity] IndexedDB unavailable, falling back to localStorage:', e?.message)
|
|
158
|
+
console.warn('[cc-identity] IndexedDB unavailable, falling back to localStorage:', /** @type {{ message?: string } | null} */ (e)?.message)
|
|
126
159
|
_fallback = true
|
|
127
160
|
_idb = null
|
|
128
161
|
try { const raw = localStorage.getItem(peersKey()); _peers = raw ? (JSON.parse(raw) || {}) : {} }
|
|
@@ -131,45 +164,59 @@ export async function initPeerStorage () {
|
|
|
131
164
|
return _peers
|
|
132
165
|
}
|
|
133
166
|
|
|
167
|
+
/** @returns {Promise<void>} */
|
|
134
168
|
function persistPeers () {
|
|
135
169
|
if (_volatile) return _writeChain // cuenta volátil: en memoria y en ningún disco
|
|
136
170
|
const key = peersKey()
|
|
137
171
|
if (_backend) {
|
|
138
172
|
const snapshot = _peers
|
|
139
173
|
_writeChain = _writeChain
|
|
140
|
-
.then(() => _backend.put(key, snapshot))
|
|
174
|
+
.then(() => /** @type {PeerBackend} */ (_backend).put(key, snapshot))
|
|
141
175
|
.catch(e => console.warn('[cc-identity] persist (app) failed:', e?.message))
|
|
142
176
|
return _writeChain
|
|
143
177
|
}
|
|
144
178
|
if (_fallback || !_idb) {
|
|
145
179
|
try { localStorage.setItem(key, JSON.stringify(_peers)) }
|
|
146
|
-
catch (e) { console.warn('[cc-identity] persist (ls) failed:', e?.message) }
|
|
180
|
+
catch (e) { console.warn('[cc-identity] persist (ls) failed:', /** @type {{ message?: string } | null} */ (e)?.message) }
|
|
147
181
|
return _writeChain
|
|
148
182
|
}
|
|
149
183
|
const snapshot = _peers
|
|
150
184
|
_writeChain = _writeChain
|
|
151
|
-
.then(() => idbPut(_idb, key, snapshot))
|
|
185
|
+
.then(() => idbPut(/** @type {IDBDatabase} */ (_idb), key, snapshot))
|
|
152
186
|
.catch(e => console.warn('[cc-identity] persist (idb) failed:', e?.message))
|
|
153
187
|
return _writeChain
|
|
154
188
|
}
|
|
155
189
|
|
|
156
|
-
/**
|
|
190
|
+
/**
|
|
191
|
+
* Promesa que resuelve cuando se completaron los write-through pendientes (tests).
|
|
192
|
+
* @returns {Promise<void>}
|
|
193
|
+
*/
|
|
157
194
|
export function flushPeers () { return _writeChain }
|
|
158
195
|
|
|
196
|
+
/** @returns {PeerBook} */
|
|
159
197
|
export function loadPeers () { return _peers }
|
|
160
198
|
|
|
199
|
+
/** @param {PeerBook} peers */
|
|
161
200
|
export function savePeers (peers) {
|
|
162
201
|
_peers = peers
|
|
163
202
|
persistPeers()
|
|
164
203
|
if (_markDirty) _markDirty()
|
|
165
204
|
}
|
|
166
205
|
|
|
167
|
-
/**
|
|
206
|
+
/**
|
|
207
|
+
* Escritura directa (merge del sync): persiste sin marcar dirty.
|
|
208
|
+
* @param {PeerBook} peers
|
|
209
|
+
*/
|
|
168
210
|
export function setPeersDirect (peers) {
|
|
169
211
|
_peers = peers
|
|
170
212
|
persistPeers()
|
|
171
213
|
}
|
|
172
214
|
|
|
215
|
+
/**
|
|
216
|
+
* @param {string} publickey
|
|
217
|
+
* @param {Record<string, any>} patch
|
|
218
|
+
* @returns {PeerRecord}
|
|
219
|
+
*/
|
|
173
220
|
export function upsertPeer (publickey, patch) {
|
|
174
221
|
const peers = loadPeers()
|
|
175
222
|
const existing = peers[publickey] || { publickey, firstSeen: Date.now() }
|
package/vault/peerSync.js
CHANGED
|
@@ -20,12 +20,20 @@ export const PEERS_THREAD = 'identity.peers'
|
|
|
20
20
|
/** Tope de una tanda de subida (cifrada, con su sobre, queda bajo el 1 MB del proxio). */
|
|
21
21
|
const PUSH_BYTES = 350_000
|
|
22
22
|
|
|
23
|
-
/**
|
|
23
|
+
/**
|
|
24
|
+
* La última vez que la ficha cambió: la vio (`lastSeen`) o la tocaste (`changedAt`).
|
|
25
|
+
* @param {{ lastSeen?: unknown, changedAt?: unknown } | null | undefined} rec
|
|
26
|
+
* @returns {number}
|
|
27
|
+
*/
|
|
24
28
|
export function stampOf (rec) {
|
|
25
29
|
return Math.max(Number(rec?.lastSeen) || 0, Number(rec?.changedAt) || 0)
|
|
26
30
|
}
|
|
27
31
|
|
|
28
|
-
/**
|
|
32
|
+
/**
|
|
33
|
+
* El id de la entrada: de su llave, estable y sin comillas (sha-256, 32 hex).
|
|
34
|
+
* @param {unknown} publickey
|
|
35
|
+
* @returns {Promise<string>}
|
|
36
|
+
*/
|
|
29
37
|
export async function peerIdOf (publickey) {
|
|
30
38
|
const d = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(String(publickey)))
|
|
31
39
|
return [...new Uint8Array(d)].slice(0, 16).map((b) => b.toString(16).padStart(2, '0')).join('')
|
|
@@ -35,17 +43,24 @@ export async function peerIdOf (publickey) {
|
|
|
35
43
|
* Reconciliar el libro con la bóveda. `peers` es el libro de aquí (`{ publickey: ficha }`),
|
|
36
44
|
* `call(method, args)` habla con el almacén de la bóveda. Devuelve las fichas que llegaron (para
|
|
37
45
|
* fundirlas aquí) y cuántas subieron.
|
|
46
|
+
*
|
|
47
|
+
* @param {{ peers: Record<string, any> | null | undefined, call: (method: string, args: any) => Promise<any> }} args
|
|
48
|
+
* @returns {Promise<{ incoming: any[], pushed: number }>}
|
|
38
49
|
*/
|
|
39
50
|
export async function syncPeers ({ peers, call }) {
|
|
51
|
+
/** @type {Map<string, number>} */
|
|
40
52
|
const remote = new Map()
|
|
53
|
+
/** @type {unknown} */
|
|
41
54
|
let cursor = null
|
|
42
55
|
do {
|
|
56
|
+
/** @type {any} */
|
|
43
57
|
const page = await call('getThreadIndexes', { keys: [PEERS_THREAD], cursor })
|
|
44
58
|
const idx = page?.indexes?.[PEERS_THREAD]
|
|
45
59
|
for (const [id, ts] of idx?.items || []) remote.set(String(id), Number(ts) || 0)
|
|
46
60
|
cursor = page?.next ?? null
|
|
47
61
|
} while (cursor != null)
|
|
48
62
|
|
|
63
|
+
/** @type {Map<string, { pk: string, rec: any, ts: number }>} */
|
|
49
64
|
const local = new Map()
|
|
50
65
|
for (const [pk, rec] of Object.entries(peers || {})) {
|
|
51
66
|
if (!rec || typeof rec !== 'object') continue
|
|
@@ -53,7 +68,8 @@ export async function syncPeers ({ peers, call }) {
|
|
|
53
68
|
}
|
|
54
69
|
|
|
55
70
|
// SUBIR primero lo que aquí es más nuevo, en tandas.
|
|
56
|
-
const up = [...local.entries()].filter(([id, l]) => !remote.has(id) || l.ts > remote.get(id))
|
|
71
|
+
const up = [...local.entries()].filter(([id, l]) => !remote.has(id) || l.ts > /** @type {number} */ (remote.get(id)))
|
|
72
|
+
/** @type {Array<{ id: string, ts: number, peer: any }>} */
|
|
57
73
|
let batch = []; let bytes = 0; let pushed = 0
|
|
58
74
|
const flush = async () => {
|
|
59
75
|
if (!batch.length) return
|
|
@@ -69,10 +85,13 @@ export async function syncPeers ({ peers, call }) {
|
|
|
69
85
|
await flush()
|
|
70
86
|
|
|
71
87
|
// TRAER lo que allí es más nuevo.
|
|
72
|
-
const down = [...remote.entries()].filter(([id, ts]) => !local.has(id) || ts > local.get(id).ts).map(([id]) => id)
|
|
88
|
+
const down = [...remote.entries()].filter(([id, ts]) => !local.has(id) || ts > /** @type {{ ts: number }} */ (local.get(id)).ts).map(([id]) => id)
|
|
89
|
+
/** @type {any[]} */
|
|
73
90
|
const incoming = []
|
|
91
|
+
/** @type {Record<string, string[]> | null} */
|
|
74
92
|
let refs = down.length ? { [PEERS_THREAD]: down } : null
|
|
75
93
|
while (refs) {
|
|
94
|
+
/** @type {any} */
|
|
76
95
|
const page = await call('getEntries', { refs })
|
|
77
96
|
for (const e of page?.threads?.[PEERS_THREAD] || []) if (e?.peer?.publickey) incoming.push(e.peer)
|
|
78
97
|
refs = page?.rest && Object.keys(page.rest).length ? page.rest : null
|