@dotrino/identity 0.126.0 → 0.126.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 +1 -1
- package/vault/core.js +7 -2
- package/vault/vendor/proxy-client/VERSION.txt +1 -1
- package/vault/vendor/proxy-client/ble/manager.js +480 -0
- package/vault/vendor/proxy-client/ble/wire.js +239 -0
- package/vault/vendor/proxy-client/client.js +116 -9
- package/vault/vendor/proxy-client/index.js +1 -0
- package/vault/vendor/proxy-client/stats-log.js +1 -1
- package/vault/vendor/proxy-client/stats.js +4 -3
- package/vault/vendor/roadmap/VERSION.txt +1 -1
- package/vault/vendor/roadmap/manifests.js +31 -12
- package/vault/vendor/vault/VERSION.txt +3 -2
- package/vault/vendor/vault/core/libVersion.js +1 -1
- package/vault/vendor/vault/core/notices.js +23 -5
- package/vault/vendor/vault/core/transport.js +5 -2
- package/vault/vendor/vault/core/vault.js +43 -9
- package/vault/vendor/vault/enroll.js +47 -9
- package/vault/vendor/vault/invite.js +385 -0
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* EL CABLE DEL BLUETOOTH (docs/bluetooth.md). Módulo PURO: sin red, sin Bluetooth, solo
|
|
3
|
+
* WebCrypto. Lo que aquí se decide lo cumplen igual los puertos de `dotrino-native`: si
|
|
4
|
+
* cambia un byte, cambia en los tres.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const BASE = '0be25149-664d-4d28-b496-3ca98a63fb'
|
|
8
|
+
export const SERVICE_UUID = BASE + '00'
|
|
9
|
+
export const HELLO_UUID = BASE + '01'
|
|
10
|
+
export const BEACON_UUID = BASE + '02'
|
|
11
|
+
export const RX_UUID = BASE + '03'
|
|
12
|
+
export const TX_UUID = BASE + '04'
|
|
13
|
+
|
|
14
|
+
/** Trama de control por el proxio, hermana de la de WebRTC (`__cc_rtc__`). */
|
|
15
|
+
export const BLE_TAG = '__cc_ble__'
|
|
16
|
+
|
|
17
|
+
export const BID_BYTES = 8
|
|
18
|
+
export const BID_ROTATE_MS = 15 * 60 * 1000
|
|
19
|
+
export const BEACON_MAX_BYTES = 512
|
|
20
|
+
export const RECORD_MAX_BYTES = 1024 * 1024
|
|
21
|
+
export const ANSWER_TIMEOUT_MS = 10_000
|
|
22
|
+
export const FIND_TIMEOUT_MS = 20_000
|
|
23
|
+
|
|
24
|
+
export const DIR_TO_PERIPHERAL = 0
|
|
25
|
+
export const DIR_TO_CENTRAL = 1
|
|
26
|
+
|
|
27
|
+
export const TYPE_TEXT = 0
|
|
28
|
+
export const TYPE_BINARY = 1
|
|
29
|
+
export const TYPE_HELLO = 2
|
|
30
|
+
|
|
31
|
+
const LAST = 0x01
|
|
32
|
+
const enc = new TextEncoder()
|
|
33
|
+
const dec = new TextDecoder()
|
|
34
|
+
|
|
35
|
+
function subtle () {
|
|
36
|
+
const s = globalThis.crypto?.subtle
|
|
37
|
+
if (!s) throw Object.assign(new Error('bluetooth: WebCrypto is not available here'), { code: 'no-webcrypto' })
|
|
38
|
+
return s
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function b64u (bytes) {
|
|
42
|
+
let s = ''
|
|
43
|
+
for (const b of bytes) s += String.fromCharCode(b)
|
|
44
|
+
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function unb64u (str) {
|
|
48
|
+
const s = String(str).replace(/-/g, '+').replace(/_/g, '/')
|
|
49
|
+
const bin = atob(s + '='.repeat((4 - s.length % 4) % 4))
|
|
50
|
+
const out = new Uint8Array(bin.length)
|
|
51
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
|
|
52
|
+
return out
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function randomBid () {
|
|
56
|
+
return b64u(globalThis.crypto.getRandomValues(new Uint8Array(BID_BYTES)))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// ---------- características de solo lectura ----------
|
|
60
|
+
|
|
61
|
+
export function encodeHello (bid) { return enc.encode(JSON.stringify({ v: 1, bid })) }
|
|
62
|
+
|
|
63
|
+
/** El `bid` de un `hello` leído, o null si no es de esta versión. */
|
|
64
|
+
export function decodeHello (bytes) {
|
|
65
|
+
try {
|
|
66
|
+
const o = JSON.parse(dec.decode(bytes))
|
|
67
|
+
return o && o.v === 1 && typeof o.bid === 'string' ? o.bid : null
|
|
68
|
+
} catch (_) { return null }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function encodeBeacon (kind, data) {
|
|
72
|
+
if (typeof kind !== 'string' || !kind || typeof data !== 'string') {
|
|
73
|
+
throw Object.assign(new Error('bluetooth: announce needs a kind and a string'), { code: 'bad-beacon' })
|
|
74
|
+
}
|
|
75
|
+
const bytes = enc.encode(JSON.stringify({ kind, data }))
|
|
76
|
+
if (bytes.length > BEACON_MAX_BYTES) {
|
|
77
|
+
throw Object.assign(new Error(`bluetooth: what is announced takes ${bytes.length} bytes; at most ${BEACON_MAX_BYTES}`), { code: 'beacon-too-big' })
|
|
78
|
+
}
|
|
79
|
+
return bytes
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** `{kind, data}` de un `beacon` leído, o null si está vacío o no se entiende. */
|
|
83
|
+
export function decodeBeacon (bytes) {
|
|
84
|
+
if (!bytes || !bytes.length) return null
|
|
85
|
+
try {
|
|
86
|
+
const o = JSON.parse(dec.decode(bytes))
|
|
87
|
+
return o && typeof o.kind === 'string' && typeof o.data === 'string' ? { kind: o.kind, data: o.data } : null
|
|
88
|
+
} catch (_) { return null }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export const KIND_PAIR = 'pair'
|
|
92
|
+
export const KIND_CONTACT = 'contact'
|
|
93
|
+
export const CONTACT_NICK_MAX = 40
|
|
94
|
+
export const CONTACT_NICK_MAX_BYTES = 60
|
|
95
|
+
|
|
96
|
+
/** El apodo recortado a 40 unidades UTF-16 y 60 bytes UTF-8, por puntos de código enteros: así cabe en el beacon. */
|
|
97
|
+
export function trimNick (nickname) {
|
|
98
|
+
let out = ''
|
|
99
|
+
let bytes = 0
|
|
100
|
+
for (const ch of String(nickname)) {
|
|
101
|
+
const b = enc.encode(ch).length
|
|
102
|
+
if (out.length + ch.length > CONTACT_NICK_MAX || bytes + b > CONTACT_NICK_MAX_BYTES) break
|
|
103
|
+
out += ch
|
|
104
|
+
bytes += b
|
|
105
|
+
}
|
|
106
|
+
return out
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* La tarjeta de contacto que se anuncia (`kind: 'contact'`): el mismo fragmento que el enlace
|
|
111
|
+
* `#to=` del messenger, `to=<publickey en base64url>&nick=<apodo>`. La `publickey` es la cadena
|
|
112
|
+
* JWK tal cual la escribe la identidad. El apodo va recortado con `trimNick` y codificado como
|
|
113
|
+
* `encodeURIComponent` (lo que no es `A-Za-z0-9-_.!~*'()` va en %XX de sus bytes UTF-8).
|
|
114
|
+
*/
|
|
115
|
+
export function encodeContact ({ publickey, nickname = '' }) {
|
|
116
|
+
if (typeof publickey !== 'string' || !publickey) {
|
|
117
|
+
throw Object.assign(new Error('bluetooth: a contact needs its publickey'), { code: 'bad-contact' })
|
|
118
|
+
}
|
|
119
|
+
const nick = trimNick(nickname)
|
|
120
|
+
return 'to=' + b64u(enc.encode(publickey)) + (nick ? '&nick=' + encodeURIComponent(nick) : '')
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** `{ publickey, nickname }` de una tarjeta anunciada, o null si no se entiende. */
|
|
124
|
+
export function decodeContact (data) {
|
|
125
|
+
if (typeof data !== 'string') return null
|
|
126
|
+
const param = (k) => { const m = data.match(new RegExp('(?:^|&)' + k + '=([^&]*)')); return m ? m[1] : null }
|
|
127
|
+
try {
|
|
128
|
+
const to = param('to')
|
|
129
|
+
if (!to) return null
|
|
130
|
+
const publickey = dec.decode(unb64u(to))
|
|
131
|
+
const jwk = JSON.parse(publickey)
|
|
132
|
+
if (!jwk || typeof jwk !== 'object' || typeof jwk.x !== 'string' || typeof jwk.y !== 'string') return null
|
|
133
|
+
const nick = param('nick')
|
|
134
|
+
return { publickey, nickname: nick ? trimNick(decodeURIComponent(nick)) : '' }
|
|
135
|
+
} catch (_) { return null }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// ---------- llave del canal ----------
|
|
139
|
+
|
|
140
|
+
export async function makeEphemeral () {
|
|
141
|
+
const kp = await subtle().generateKey({ name: 'ECDH', namedCurve: 'P-256' }, false, ['deriveBits'])
|
|
142
|
+
const raw = new Uint8Array(await subtle().exportKey('raw', kp.publicKey))
|
|
143
|
+
return { privateKey: kp.privateKey, epub: b64u(raw) }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** La llave AES del canal (docs/bluetooth.md §4). El orden de los tokens no depende de quién llama. */
|
|
147
|
+
export async function deriveKey (privateKey, theirEpub, tokenA, tokenB) {
|
|
148
|
+
const s = subtle()
|
|
149
|
+
const pub = await s.importKey('raw', unb64u(theirEpub), { name: 'ECDH', namedCurve: 'P-256' }, false, [])
|
|
150
|
+
const secret = await s.deriveBits({ name: 'ECDH', public: pub }, privateKey, 256)
|
|
151
|
+
const ikm = await s.importKey('raw', secret, 'HKDF', false, ['deriveKey'])
|
|
152
|
+
const [lo, hi] = tokenA < tokenB ? [tokenA, tokenB] : [tokenB, tokenA]
|
|
153
|
+
return s.deriveKey(
|
|
154
|
+
{ name: 'HKDF', hash: 'SHA-256', salt: enc.encode(lo + '|' + hi), info: enc.encode('dotrino-ble-v1') },
|
|
155
|
+
ikm, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// ---------- registros ----------
|
|
159
|
+
|
|
160
|
+
function nonce (dir, counter) {
|
|
161
|
+
const n = new Uint8Array(12)
|
|
162
|
+
n[0] = dir
|
|
163
|
+
new DataView(n.buffer).setBigUint64(4, BigInt(counter))
|
|
164
|
+
return n
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export async function sealRecord (key, dir, counter, type, body) {
|
|
168
|
+
const plain = new Uint8Array(1 + body.length)
|
|
169
|
+
plain[0] = type
|
|
170
|
+
plain.set(body, 1)
|
|
171
|
+
return new Uint8Array(await subtle().encrypt({ name: 'AES-GCM', iv: nonce(dir, counter) }, key, plain))
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** `{type, body}`, o lanza si no lo selló esa llave con ese contador. */
|
|
175
|
+
export async function openRecord (key, dir, counter, record) {
|
|
176
|
+
const plain = new Uint8Array(await subtle().decrypt({ name: 'AES-GCM', iv: nonce(dir, counter) }, key, record))
|
|
177
|
+
if (!plain.length) throw new Error('bluetooth: empty record')
|
|
178
|
+
return { type: plain[0], body: plain.subarray(1) }
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function encodeText (str) { return enc.encode(str) }
|
|
182
|
+
export function decodeText (bytes) { return dec.decode(bytes) }
|
|
183
|
+
|
|
184
|
+
// ---------- trozos ----------
|
|
185
|
+
|
|
186
|
+
export const TAG_BYTES = 4
|
|
187
|
+
|
|
188
|
+
/** La etiqueta de los trozos hacia un central: los 4 primeros bytes de su `bid` (docs §5). */
|
|
189
|
+
export function tagOf (bid) { return unb64u(bid).subarray(0, TAG_BYTES) }
|
|
190
|
+
|
|
191
|
+
/** True si el trozo de `tx` lleva esa etiqueta. */
|
|
192
|
+
export function hasTag (chunk, tag) {
|
|
193
|
+
if (chunk.length < 1 + TAG_BYTES) return false
|
|
194
|
+
for (let i = 0; i < TAG_BYTES; i++) if (chunk[1 + i] !== tag[i]) return false
|
|
195
|
+
return true
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Parte un registro en trozos de `chunk` bytes de valor GATT, cabecera incluida. Con `tag`
|
|
200
|
+
* (hacia un central, `tx`) la cabecera lleva la etiqueta detrás de las banderas.
|
|
201
|
+
*/
|
|
202
|
+
export function toChunks (record, chunk, tag = null) {
|
|
203
|
+
const head = 1 + (tag ? TAG_BYTES : 0)
|
|
204
|
+
const room = Math.max(1, chunk - head)
|
|
205
|
+
const out = []
|
|
206
|
+
let i = 0
|
|
207
|
+
do {
|
|
208
|
+
const part = record.subarray(i, i + room)
|
|
209
|
+
i += room
|
|
210
|
+
const c = new Uint8Array(head + part.length)
|
|
211
|
+
c[0] = i >= record.length ? LAST : 0
|
|
212
|
+
if (tag) c.set(tag, 1)
|
|
213
|
+
c.set(part, head)
|
|
214
|
+
out.push(c)
|
|
215
|
+
} while (i < record.length)
|
|
216
|
+
return out
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Rearma registros de trozos que llegan en orden. `push` devuelve el registro entero, o null. */
|
|
220
|
+
export class Reassembler {
|
|
221
|
+
/** @param {number} [skip] bytes de cabecera tras las banderas (la etiqueta, en `tx`) */
|
|
222
|
+
constructor (skip = 0) { this.skip = skip; this.parts = []; this.size = 0 }
|
|
223
|
+
push (chunk) {
|
|
224
|
+
if (!chunk || chunk.length < 1 + this.skip) return null
|
|
225
|
+
const body = chunk.subarray(1 + this.skip)
|
|
226
|
+
this.size += body.length
|
|
227
|
+
if (this.size > RECORD_MAX_BYTES + 64) {
|
|
228
|
+
this.parts = []; this.size = 0
|
|
229
|
+
throw Object.assign(new Error('bluetooth: record larger than 1 MiB'), { code: 'record-too-big' })
|
|
230
|
+
}
|
|
231
|
+
this.parts.push(body)
|
|
232
|
+
if (!(chunk[0] & LAST)) return null
|
|
233
|
+
const out = new Uint8Array(this.size)
|
|
234
|
+
let o = 0
|
|
235
|
+
for (const p of this.parts) { out.set(p, o); o += p.length }
|
|
236
|
+
this.parts = []; this.size = 0
|
|
237
|
+
return out
|
|
238
|
+
}
|
|
239
|
+
}
|
|
@@ -2,6 +2,8 @@ import { buildSignedChannel, getPublicKeyJwk, signData, samePubkey } from './sig
|
|
|
2
2
|
import { seal, open, isSealed, isBinSealed, BIN_SEALED, makeMessageKey, encryptBytes, decryptBytes } from './sealing.js'
|
|
3
3
|
import { buildEncPubStatement, readEncPubStatement, isEncPub } from './encpub.js'
|
|
4
4
|
import { WebRTCManager, RTC_TAG, DEFAULT_ICE_SERVERS, loadNodePeerConnection, resolvePeerConnection, pinTurnToIPv4 } from './webrtc.js'
|
|
5
|
+
import { BluetoothManager } from './ble/manager.js'
|
|
6
|
+
import { BLE_TAG } from './ble/wire.js'
|
|
5
7
|
import { TrafficStats, utf8Length, registerTransport, unregisterTransport } from './stats.js'
|
|
6
8
|
import { splitParts, splitBinParts, isPart, Reassembler, DIRECT_PART_CHARS, PROXY_PART_CHARS, QUEUE_MAX_CHARS, RELAY_MAX_CHARS, DIRECT_PART_BYTES, PROXY_PART_BYTES, QUEUE_MAX_BYTES, RELAY_MAX_BYTES } from './parts.js'
|
|
7
9
|
import { pack, unpack, hasBinary, encodeFrame, decodeFrame } from './binpack.js'
|
|
@@ -217,6 +219,22 @@ export class WebSocketProxyClient {
|
|
|
217
219
|
if (this._rtc && typeof options.acceptDirectFrom === 'function') {
|
|
218
220
|
this._rtc.acceptFrom = options.acceptDirectFrom
|
|
219
221
|
}
|
|
222
|
+
|
|
223
|
+
// EL BLUETOOTH (docs/bluetooth.md): escalón entre WebRTC directo y TURN. Se enciende a
|
|
224
|
+
// propósito, con `bluetooth: true` (en Node busca BlueZ, solo en Linux) o con un
|
|
225
|
+
// adaptador propio. Encenderlo hace que el aparato anuncie que está ahí, y eso no lo
|
|
226
|
+
// decide un script cualquiera que importe el pilar: lo decide quien monta el cliente.
|
|
227
|
+
this._bleOption = options.bluetooth || null
|
|
228
|
+
this._ble = this._bleOption ? new BluetoothManager({
|
|
229
|
+
getSelfToken: () => this.token,
|
|
230
|
+
signalSend: (to, payload) => this._proxySendOne(to, payload),
|
|
231
|
+
deliverMessage: (from, parsed, meta) => this._deliver(from, parsed, meta),
|
|
232
|
+
emit: (event, ...args) => this._emit(event, ...args),
|
|
233
|
+
count: (dir, token, bytes, route) =>
|
|
234
|
+
this._traffic.peer(dir, route, { token, pubkey: this._tokenPubkeys.get(token) || null }, bytes),
|
|
235
|
+
}) : null
|
|
236
|
+
if (this._ble && typeof options.acceptDirectFrom === 'function') this._ble.acceptFrom = options.acceptDirectFrom
|
|
237
|
+
this._bleStarting = null
|
|
220
238
|
}
|
|
221
239
|
|
|
222
240
|
// ---------- public API ----------
|
|
@@ -234,7 +252,55 @@ export class WebSocketProxyClient {
|
|
|
234
252
|
await loadNodePeerConnection()
|
|
235
253
|
}
|
|
236
254
|
|
|
255
|
+
/**
|
|
256
|
+
* ENCIENDE EL BLUETOOTH, una vez. Corre por detrás desde `connect()`: tiene que estar
|
|
257
|
+
* anunciando antes de que el otro quiera subir de escalón. Que no haya Bluetooth es el caso
|
|
258
|
+
* normal y no se dice; que lo haya y no arranque, sí (`bluetooth_unavailable`).
|
|
259
|
+
*/
|
|
260
|
+
_prepareBluetooth () {
|
|
261
|
+
if (!this._ble || this._ble.available || this._bleStarting) return this._bleStarting
|
|
262
|
+
this._bleStarting = (async () => {
|
|
263
|
+
let adapter = this._bleOption
|
|
264
|
+
if (adapter === true) {
|
|
265
|
+
const mod = './ble/bluez.js'
|
|
266
|
+
const { openBluez } = await import(/* @vite-ignore */ mod)
|
|
267
|
+
adapter = await openBluez()
|
|
268
|
+
if (!adapter) return
|
|
269
|
+
}
|
|
270
|
+
await this._ble.start(adapter)
|
|
271
|
+
})().catch((e) => {
|
|
272
|
+
this._emit('error', { type: 'bluetooth_unavailable', error: e, code: e?.code || null })
|
|
273
|
+
}).finally(() => { this._bleStarting = null })
|
|
274
|
+
return this._bleStarting
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Hay Bluetooth encendido en este cliente. */
|
|
278
|
+
get bluetoothAvailable () { return !!this._ble?.available }
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Anuncia `{kind, data}` por Bluetooth hasta que se llame a lo que devuelve
|
|
282
|
+
* (docs/bluetooth.md §3). `kind: 'pair'` es la invitación de emparejar; `'contact'`, la
|
|
283
|
+
* tarjeta de contacto. Lanza `no-bluetooth` si aquí no lo hay.
|
|
284
|
+
* @returns {() => void}
|
|
285
|
+
*/
|
|
286
|
+
announceBluetooth (kind, data) {
|
|
287
|
+
if (!this._ble) throw errorWithCode('bluetooth: this client was made without it (option `bluetooth`)', 'no-bluetooth')
|
|
288
|
+
return this._ble.announce(kind, data)
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Lo que anuncian por Bluetooth los aparatos de alrededor con ese `kind`. No necesita el
|
|
293
|
+
* proxio. `onFound` avisa de cada uno según aparece.
|
|
294
|
+
* @returns {Promise<{kind: string, data: string}[]>}
|
|
295
|
+
*/
|
|
296
|
+
async discoverBluetooth ({ kind, timeoutMs, onFound } = /** @type {any} */ ({})) {
|
|
297
|
+
if (!this._ble) throw errorWithCode('bluetooth: this client was made without it (option `bluetooth`)', 'no-bluetooth')
|
|
298
|
+
await this._prepareBluetooth()
|
|
299
|
+
return this._ble.discover({ kind, timeoutMs, onFound })
|
|
300
|
+
}
|
|
301
|
+
|
|
237
302
|
connect () {
|
|
303
|
+
this._prepareBluetooth()
|
|
238
304
|
return new Promise((resolve, reject) => {
|
|
239
305
|
if (this._connected) return resolve(this.token)
|
|
240
306
|
// Un reintento que estaba esperando su turno sobra: este `connect()` ya abre uno.
|
|
@@ -257,6 +323,7 @@ export class WebSocketProxyClient {
|
|
|
257
323
|
this._turnTimer = null
|
|
258
324
|
}
|
|
259
325
|
if (this._rtc) this._rtc.closeAll()
|
|
326
|
+
if (this._ble) this._ble.stop().catch(() => {})
|
|
260
327
|
if (this.ws) {
|
|
261
328
|
try { this.ws.close(1000) } catch (_) {}
|
|
262
329
|
}
|
|
@@ -342,13 +409,13 @@ export class WebSocketProxyClient {
|
|
|
342
409
|
}
|
|
343
410
|
const tokens = Array.isArray(to) ? to : [to]
|
|
344
411
|
const messageStr = this._wire(payload)
|
|
345
|
-
if (!this._rtc) {
|
|
412
|
+
if (!this._rtc && !this._ble) {
|
|
346
413
|
this._sendRaw({ to: tokens, message: messageStr })
|
|
347
414
|
return
|
|
348
415
|
}
|
|
349
416
|
const proxyTokens = []
|
|
350
417
|
for (const t of tokens) {
|
|
351
|
-
if (!this.
|
|
418
|
+
if (!this._tryDirect(t, messageStr)) proxyTokens.push(t)
|
|
352
419
|
}
|
|
353
420
|
if (proxyTokens.length) {
|
|
354
421
|
this._sendRaw({ to: proxyTokens, message: messageStr })
|
|
@@ -374,6 +441,8 @@ export class WebSocketProxyClient {
|
|
|
374
441
|
* el siguiente mensaje vuelve a intentarlo.
|
|
375
442
|
*/
|
|
376
443
|
_upgradeDirect (tokens) {
|
|
444
|
+
// El Bluetooth negocia en paralelo con WebRTC y deduplica solo (ble/manager.js).
|
|
445
|
+
if (this._ble?.available) for (const t of tokens) if (!this._ble.isOpen(t)) this._ble.upgrade(t)
|
|
377
446
|
if (!this._rtc) return
|
|
378
447
|
this._rtcTried = this._rtcTried || new Set()
|
|
379
448
|
for (const t of tokens) {
|
|
@@ -404,6 +473,25 @@ export class WebSocketProxyClient {
|
|
|
404
473
|
return !!(this._rtc && this._rtc.isOpen(token))
|
|
405
474
|
}
|
|
406
475
|
|
|
476
|
+
/**
|
|
477
|
+
* EL MEJOR CANAL ABIERTO, en el orden de la escalera (docs/bluetooth.md §1): WebRTC si va
|
|
478
|
+
* directo, si no Bluetooth, si no WebRTC por TURN. False = por el proxio.
|
|
479
|
+
*/
|
|
480
|
+
_directFor (token) {
|
|
481
|
+
const rtcOpen = !!this._rtc?.isOpen(token)
|
|
482
|
+
if (rtcOpen && this._rtc.peers?.get(token)?.route !== 'turn') return this._rtc
|
|
483
|
+
if (this._ble?.isOpen(token)) return this._ble
|
|
484
|
+
if (rtcOpen) return this._rtc
|
|
485
|
+
return null
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/** Manda por el mejor canal abierto; si no hay, deja que WebRTC empiece a negociar y da false. */
|
|
489
|
+
_tryDirect (token, wire) {
|
|
490
|
+
const d = this._directFor(token)
|
|
491
|
+
if (d) return d.trySend(token, wire)
|
|
492
|
+
return this._rtc ? this._rtc.trySend(token, wire) : false
|
|
493
|
+
}
|
|
494
|
+
|
|
407
495
|
_proxySendOne (to, payload) {
|
|
408
496
|
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return
|
|
409
497
|
this._sendRaw({
|
|
@@ -576,7 +664,7 @@ export class WebSocketProxyClient {
|
|
|
576
664
|
// mensaje del camino que toca sale en partes. El tamaño de parte lo decide el camino
|
|
577
665
|
// de ahora: el canal directo admite mucho menos por mensaje que el proxio.
|
|
578
666
|
const m = this._measure(payload)
|
|
579
|
-
const direct = tokens.length === 1 && !!this.
|
|
667
|
+
const direct = tokens.length === 1 && !!this._directFor(tokens[0])
|
|
580
668
|
const size = m.bin ? (direct ? DIRECT_PART_BYTES : PROXY_PART_BYTES) : (direct ? DIRECT_PART_CHARS : PROXY_PART_CHARS)
|
|
581
669
|
const relayMax = m.bin ? RELAY_MAX_BYTES : RELAY_MAX_CHARS
|
|
582
670
|
const queueMax = m.bin ? QUEUE_MAX_BYTES : QUEUE_MAX_CHARS
|
|
@@ -619,12 +707,14 @@ export class WebSocketProxyClient {
|
|
|
619
707
|
* existe esto: que la app lo enseñe antes de que el usuario intente algo que no cabe.
|
|
620
708
|
* `webrtc` es un canal directo abierto del que todavía no se sabe si va por TURN.
|
|
621
709
|
* @param {string|null} token
|
|
622
|
-
* @returns {Promise<'socket'|'direct'|'turn'|'webrtc'|'proxy'|'offline'>}
|
|
710
|
+
* @returns {Promise<'socket'|'direct'|'turn'|'webrtc'|'bluetooth'|'proxy'|'offline'>}
|
|
623
711
|
*/
|
|
624
712
|
async routeTo (token) {
|
|
625
713
|
if (!this._connected) return 'offline'
|
|
626
714
|
if (!token) return 'offline'
|
|
627
|
-
|
|
715
|
+
const d = this._directFor(token)
|
|
716
|
+
if (d && d === this._ble) return 'bluetooth'
|
|
717
|
+
if (d) {
|
|
628
718
|
const peer = this._rtc.peers.get(token)
|
|
629
719
|
try { return (await this._rtc.probeRoute(peer)) || 'webrtc' } catch (_) { return 'webrtc' }
|
|
630
720
|
}
|
|
@@ -637,7 +727,8 @@ export class WebSocketProxyClient {
|
|
|
637
727
|
* una pausa corta entre partes, para no chocar con su límite de mensajes por segundo.
|
|
638
728
|
*/
|
|
639
729
|
async _sendPiece (token, envelope, peerPubkey, queueFallback, relayFallback = true) {
|
|
640
|
-
|
|
730
|
+
const d = this._directFor(token)
|
|
731
|
+
if (d && await d.sendDirect(token, this._wire(envelope))) return
|
|
641
732
|
if (!relayFallback) {
|
|
642
733
|
throw errorWithCode('the direct channel closed in the middle of a message too big for the proxy', 'direct-lost')
|
|
643
734
|
}
|
|
@@ -683,7 +774,7 @@ export class WebSocketProxyClient {
|
|
|
683
774
|
throw errorWithCode('requireSealed: refusing to send a directed message in the clear — use sendSealedTo()', 'unsealed')
|
|
684
775
|
}
|
|
685
776
|
const messageStr = this._wire(envelope)
|
|
686
|
-
if (!skipDirect && this.
|
|
777
|
+
if (!skipDirect && this._tryDirect(token, messageStr)) return
|
|
687
778
|
const id = `msg_${this._nextId++}`
|
|
688
779
|
const timer = setTimeout(() => this._tokenWatch.delete(id), 15000)
|
|
689
780
|
timer.unref?.()
|
|
@@ -1453,7 +1544,9 @@ export class WebSocketProxyClient {
|
|
|
1453
1544
|
spec.fireAt = fireAt
|
|
1454
1545
|
}
|
|
1455
1546
|
if (payload) spec.payload = payload
|
|
1456
|
-
|
|
1547
|
+
// La app va firmada, como en enablePush: el recordatorio suena solo en ella (proxio ≥ 1.9.0;
|
|
1548
|
+
// uno más viejo la ignora y suena en todas, como antes).
|
|
1549
|
+
const data = { op: 'schedule-push', publickey: publicKey, spec: JSON.stringify(spec), ts: Date.now(), ...this._appField() }
|
|
1457
1550
|
const signature = await normalizeSignature(sign, data)
|
|
1458
1551
|
const res = await this._request({ type: 'schedule-push', data, signature }, 'push-scheduled')
|
|
1459
1552
|
return { jobId: res.jobId, nextFire: res.nextFire }
|
|
@@ -1476,7 +1569,7 @@ export class WebSocketProxyClient {
|
|
|
1476
1569
|
|
|
1477
1570
|
/**
|
|
1478
1571
|
* Listar los push programados propios.
|
|
1479
|
-
* @returns {Promise<Array<{ jobId:number, nextFire:number, cron:string|null, tz:string|null, payload:object|null }>>}
|
|
1572
|
+
* @returns {Promise<Array<{ jobId:number, app:string|null, nextFire:number, cron:string|null, tz:string|null, payload:object|null }>>}
|
|
1480
1573
|
*/
|
|
1481
1574
|
async listScheduledPushes ({ publicKey, sign } = {}) {
|
|
1482
1575
|
if (!publicKey || typeof sign !== 'function') throw new Error('listScheduledPushes requires { publicKey, sign }')
|
|
@@ -1712,6 +1805,11 @@ export class WebSocketProxyClient {
|
|
|
1712
1805
|
this._rtc.handleIncoming(from, parsed)
|
|
1713
1806
|
break
|
|
1714
1807
|
}
|
|
1808
|
+
// La señalización del Bluetooth tampoco sube a la app, haya Bluetooth o no.
|
|
1809
|
+
if (parsed && parsed.t === BLE_TAG) {
|
|
1810
|
+
this._ble?.handleIncoming(from, parsed)
|
|
1811
|
+
break
|
|
1812
|
+
}
|
|
1715
1813
|
// El saludo se atiende AQUÍ, antes de `_deliver`: es del transporte y no sube a
|
|
1716
1814
|
// la app, así que `requireSealed` no lo ve pasar ni tiene que hacerle una
|
|
1717
1815
|
// excepción.
|
|
@@ -1733,6 +1831,7 @@ export class WebSocketProxyClient {
|
|
|
1733
1831
|
this.forgetToken(data.token)
|
|
1734
1832
|
this._emit('peer_disconnected', data.token, data.channel || null)
|
|
1735
1833
|
if (this._rtc && data.token) this._rtc.closePeer(data.token)
|
|
1834
|
+
if (this._ble && data.token) this._ble.closePeer(data.token)
|
|
1736
1835
|
this._resolvePending(data, 'token')
|
|
1737
1836
|
break
|
|
1738
1837
|
case 'joined':
|
|
@@ -1842,6 +1941,13 @@ export class WebSocketProxyClient {
|
|
|
1842
1941
|
async stats () {
|
|
1843
1942
|
const t = this._traffic
|
|
1844
1943
|
const routes = this._rtc ? await this._rtc.describe() : new Map()
|
|
1944
|
+
// Un canal de Bluetooth abierto manda sobre un WebRTC que no salió o va por TURN (§1).
|
|
1945
|
+
if (this._ble) {
|
|
1946
|
+
for (const [tok, r] of this._ble.describe()) {
|
|
1947
|
+
const cur = routes.get(tok)
|
|
1948
|
+
if (r === 'bluetooth' ? cur !== 'direct' : !cur) routes.set(tok, r)
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1845
1951
|
const peers = [...t.peers.values()].map((p) => {
|
|
1846
1952
|
const pubkey = p.pubkey || (p.token && this._tokenPubkeys.get(p.token)) || null
|
|
1847
1953
|
const rtc = p.token ? routes.get(p.token) : null
|
|
@@ -1865,6 +1971,7 @@ export class WebSocketProxyClient {
|
|
|
1865
1971
|
publickey: this.myPublickey,
|
|
1866
1972
|
connected: this._connected,
|
|
1867
1973
|
webrtc: !!this._rtc,
|
|
1974
|
+
bluetooth: !!this._ble?.available,
|
|
1868
1975
|
// El relevo: null si nunca se pidió; si no, activo o por qué no (`code`, `retryAt`).
|
|
1869
1976
|
turn: this._turn ? { ...this._turn } : null,
|
|
1870
1977
|
since: t.since,
|
|
@@ -14,6 +14,7 @@ export { listTransports, routeOf } from './stats.js'
|
|
|
14
14
|
export { PART_TAG, DIRECT_PART_CHARS, PROXY_PART_CHARS, QUEUE_MAX_CHARS, RELAY_MAX_CHARS, DIRECT_PART_BYTES, PROXY_PART_BYTES, QUEUE_MAX_BYTES, RELAY_MAX_BYTES } from './parts.js'
|
|
15
15
|
export { pack, unpack, hasBinary, encodeFrame, decodeFrame } from './binpack.js'
|
|
16
16
|
export { logStats, formatStats, netReport, splitPeers } from './stats-log.js'
|
|
17
|
+
export { encodeContact, decodeContact, KIND_PAIR, KIND_CONTACT } from './ble/wire.js'
|
|
17
18
|
|
|
18
19
|
import { WebSocketProxyClient } from './client.js'
|
|
19
20
|
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
import { listTransports, PATHS } from './stats.js'
|
|
21
21
|
|
|
22
22
|
const sum = (peers, dir) => {
|
|
23
|
-
const t = { proxy: 0, direct: 0, turn: 0, webrtc: 0 }
|
|
23
|
+
const t = { proxy: 0, direct: 0, turn: 0, webrtc: 0, bluetooth: 0 }
|
|
24
24
|
for (const p of peers) for (const k of PATHS) t[k] += p[dir][k]
|
|
25
25
|
return t
|
|
26
26
|
}
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* direct WebRTC sin relevo
|
|
16
16
|
* turn WebRTC por un relevo TURN
|
|
17
17
|
* webrtc WebRTC sin saber todavía cuál de los dos (getStats no contestó)
|
|
18
|
+
* bluetooth el escalón del Bluetooth (docs/bluetooth.md)
|
|
18
19
|
*/
|
|
19
20
|
|
|
20
21
|
/** Longitud en bytes UTF-8 de un string, sin reservar un buffer por mensaje. */
|
|
@@ -35,9 +36,9 @@ export function utf8Length (s) {
|
|
|
35
36
|
return n
|
|
36
37
|
}
|
|
37
38
|
|
|
38
|
-
export const PATHS = ['proxy', 'direct', 'turn', 'webrtc']
|
|
39
|
+
export const PATHS = ['proxy', 'direct', 'turn', 'webrtc', 'bluetooth']
|
|
39
40
|
|
|
40
|
-
const zeros = () => ({ proxy: 0, direct: 0, turn: 0, webrtc: 0 })
|
|
41
|
+
const zeros = () => ({ proxy: 0, direct: 0, turn: 0, webrtc: 0, bluetooth: 0 })
|
|
41
42
|
|
|
42
43
|
export class TrafficStats {
|
|
43
44
|
constructor () {
|
|
@@ -55,7 +56,7 @@ export class TrafficStats {
|
|
|
55
56
|
/**
|
|
56
57
|
* Un mensaje dirigido a (o venido de) una conexión.
|
|
57
58
|
* @param {'in'|'out'} dir
|
|
58
|
-
* @param {'proxy'|'direct'|'turn'|'webrtc'} path
|
|
59
|
+
* @param {'proxy'|'direct'|'turn'|'webrtc'|'bluetooth'} path
|
|
59
60
|
* @param {{ token?: string|null, pubkey?: string|null }} who
|
|
60
61
|
* @param {number} bytes
|
|
61
62
|
*/
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
Copia vendorizada de @dotrino/roadmap@0.4.
|
|
1
|
+
Copia vendorizada de @dotrino/roadmap@0.4.57 (dotrino-roadmap/src/{index,manifests}.js).
|
|
2
2
|
NO se edita a mano: la escribe `node vendor.mjs` y la vigila test/vendor-up-to-date.test.mjs.
|
|
3
3
|
El registro de versiones rotas que viaja con cada versión. Importa @dotrino/compat/ranges.
|
|
@@ -31,7 +31,7 @@ export const MANIFESTS = Object.freeze({
|
|
|
31
31
|
"identity": {
|
|
32
32
|
"repo": "imdotrino/dotrino-identity",
|
|
33
33
|
"npm": "@dotrino/identity",
|
|
34
|
-
"current": "0.
|
|
34
|
+
"current": "0.126.1",
|
|
35
35
|
"protocol": 1,
|
|
36
36
|
"requires": {
|
|
37
37
|
"proxy-client": ">=0.13.1"
|
|
@@ -109,7 +109,7 @@ export const MANIFESTS = Object.freeze({
|
|
|
109
109
|
},
|
|
110
110
|
"proxy": {
|
|
111
111
|
"repo": "imdotrino/dotrino-proxy",
|
|
112
|
-
"current": "1.
|
|
112
|
+
"current": "1.9.0",
|
|
113
113
|
"protocol": 2,
|
|
114
114
|
"requires": {
|
|
115
115
|
"vault": ">=0.87.0",
|
|
@@ -121,7 +121,7 @@ export const MANIFESTS = Object.freeze({
|
|
|
121
121
|
"proxy-client": {
|
|
122
122
|
"repo": "imdotrino/dotrino-proxy-client",
|
|
123
123
|
"npm": "@dotrino/proxy-client",
|
|
124
|
-
"current": "0.
|
|
124
|
+
"current": "0.42.1",
|
|
125
125
|
"protocol": 2,
|
|
126
126
|
"requires": {
|
|
127
127
|
"identity": ">=0.53.0",
|
|
@@ -253,12 +253,12 @@ export const MANIFESTS = Object.freeze({
|
|
|
253
253
|
"vault": {
|
|
254
254
|
"repo": "imdotrino/dotrino-vault",
|
|
255
255
|
"npm": "@dotrino/vault",
|
|
256
|
-
"current": "0.
|
|
256
|
+
"current": "0.100.0",
|
|
257
257
|
"protocol": 1,
|
|
258
258
|
"requires": {
|
|
259
259
|
"vaultd": ">=0.105.0",
|
|
260
|
-
"proxy-client": ">=0.
|
|
261
|
-
"identity": ">=0.
|
|
260
|
+
"proxy-client": ">=0.41.0",
|
|
261
|
+
"identity": ">=0.126.0",
|
|
262
262
|
"opaque": ">=0.1.0",
|
|
263
263
|
"compat": ">=0.4.0",
|
|
264
264
|
"roadmap": ">=0.4.26",
|
|
@@ -269,11 +269,11 @@ export const MANIFESTS = Object.freeze({
|
|
|
269
269
|
"vaultd": {
|
|
270
270
|
"repo": "imdotrino/dotrino-vault",
|
|
271
271
|
"npm": "@dotrino/vaultd",
|
|
272
|
-
"current": "0.
|
|
272
|
+
"current": "0.172.0",
|
|
273
273
|
"protocol": 1,
|
|
274
274
|
"requires": {
|
|
275
|
-
"identity": ">=0.
|
|
276
|
-
"proxy-client": ">=0.
|
|
275
|
+
"identity": ">=0.126.0",
|
|
276
|
+
"proxy-client": ">=0.41.0",
|
|
277
277
|
"store": ">=0.11.0",
|
|
278
278
|
"passmanager": ">=0.18.4",
|
|
279
279
|
"compat": ">=0.4.0",
|
|
@@ -320,7 +320,7 @@ export const MANIFESTS = Object.freeze({
|
|
|
320
320
|
},
|
|
321
321
|
"passmanager-extension": {
|
|
322
322
|
"repo": "imdotrino/dotrino-passmanager",
|
|
323
|
-
"current": "0.
|
|
323
|
+
"current": "0.57.0",
|
|
324
324
|
"protocol": 1,
|
|
325
325
|
"requires": {
|
|
326
326
|
"identity": ">=0.118.0",
|
|
@@ -332,7 +332,7 @@ export const MANIFESTS = Object.freeze({
|
|
|
332
332
|
},
|
|
333
333
|
"app": {
|
|
334
334
|
"repo": "imdotrino/dotrino-app",
|
|
335
|
-
"current": "0.4.
|
|
335
|
+
"current": "0.4.26",
|
|
336
336
|
"protocol": 1,
|
|
337
337
|
"requires": {
|
|
338
338
|
"proxy": "1.6.0+",
|
|
@@ -342,7 +342,7 @@ export const MANIFESTS = Object.freeze({
|
|
|
342
342
|
},
|
|
343
343
|
"app-ios": {
|
|
344
344
|
"repo": "imdotrino/dotrino-app",
|
|
345
|
-
"current": "0.4.
|
|
345
|
+
"current": "0.4.16",
|
|
346
346
|
"protocol": 1,
|
|
347
347
|
"requires": {
|
|
348
348
|
"proxy": "1.6.0+",
|
|
@@ -388,12 +388,31 @@ export const MANIFESTS = Object.freeze({
|
|
|
388
388
|
"protocol": 1,
|
|
389
389
|
"requires": {}
|
|
390
390
|
},
|
|
391
|
+
"expenses-agent": {
|
|
392
|
+
"repo": "imdotrino/dotrino-expenses-agent",
|
|
393
|
+
"npm": "@dotrino/expenses-agent",
|
|
394
|
+
"current": "0.1.2",
|
|
395
|
+
"protocol": 1,
|
|
396
|
+
"requires": {
|
|
397
|
+
"remote-agent": ">=0.23.1",
|
|
398
|
+
"vault": ">=0.96.0",
|
|
399
|
+
"update": ">=0.9.2",
|
|
400
|
+
"vaultd": ">=0.154.0"
|
|
401
|
+
}
|
|
402
|
+
},
|
|
391
403
|
"pay": {
|
|
392
404
|
"repo": "imdotrino/dotrino-pay",
|
|
393
405
|
"npm": "@dotrino/pay",
|
|
394
406
|
"current": "0.2.0",
|
|
395
407
|
"protocol": 1,
|
|
396
408
|
"requires": {}
|
|
409
|
+
},
|
|
410
|
+
"update": {
|
|
411
|
+
"repo": "imdotrino/dotrino-update",
|
|
412
|
+
"npm": "@dotrino/update",
|
|
413
|
+
"current": "0.9.2",
|
|
414
|
+
"protocol": 1,
|
|
415
|
+
"requires": {}
|
|
397
416
|
}
|
|
398
417
|
},
|
|
399
418
|
"broken": [
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
Copia vendorizada de @dotrino/vault@0.
|
|
1
|
+
Copia vendorizada de @dotrino/vault@0.100.0 (dotrino-vault/lib/src/{admin,b64,browser,core/approvals,core/backup,core/blocked,core/browserDisk,core/commKey,core/disk,core/exNotices,core/gate,core/libVersion,core/machines,core/notices,core/notifiable,core/passwords,core/sealKey,core/sealer,core/sealers,core/secretsStore,core/sha256,core/store,core/subacta,core/threadStore,core/transport,core/vault,enroll,index,invite,loginClient,passwordLogins,procContext,protocol,revocation,sealed}.js).
|
|
2
2
|
NO se edita a mano: la escribe `node vendor.mjs` y la vigila test/vendor-up-to-date.test.mjs.
|
|
3
3
|
browser.js es la bóveda de esta pestaña: el MISMO núcleo que el binario (core/), con
|
|
4
4
|
el disco en IndexedDB. Importa @dotrino/{compat,roadmap,passmanager,store/core} y
|
|
5
5
|
@dotrino/identity/{facade,machine,content}, todos por el import map de index.html.
|
|
6
|
-
index.js importa ./enroll.js y ./protocol.js (relativos, van en esta misma copia)
|
|
6
|
+
index.js importa ./enroll.js y ./protocol.js (relativos, van en esta misma copia);
|
|
7
|
+
enroll.js importa ./invite.js para anunciar la invitación por Bluetooth.
|
|
7
8
|
@dotrino/identity/{capabilities,acta} (= ../../{capabilities,acta}.js) y
|
|
8
9
|
@dotrino/proxy-client (= ../proxy-client/), todos por el import map de index.html.
|
|
9
10
|
passwordLogins.js es el aparato que se abre con usuario y contraseña: lo carga
|