@dotrino/identity 0.136.2 → 0.136.3
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/vendor/opaque/VERSION.txt +1 -1
- package/vault/vendor/opaque/src/index.js +90 -13
- package/vault/vendor/proxy-client/VERSION.txt +1 -1
- package/vault/vendor/proxy-client/binpack.js +38 -7
- package/vault/vendor/proxy-client/ble/manager.js +148 -36
- package/vault/vendor/proxy-client/ble/wire.js +74 -9
- package/vault/vendor/proxy-client/canonical.js +6 -2
- package/vault/vendor/proxy-client/client.js +439 -130
- package/vault/vendor/proxy-client/encpub.js +9 -1
- package/vault/vendor/proxy-client/index.js +4 -0
- package/vault/vendor/proxy-client/parts.js +22 -2
- package/vault/vendor/proxy-client/sealing.js +60 -9
- package/vault/vendor/proxy-client/signature.js +38 -1
- package/vault/vendor/proxy-client/stats-log.js +29 -9
- package/vault/vendor/proxy-client/stats.js +36 -8
- package/vault/vendor/proxy-client/webrtc.js +95 -16
- package/vault/vendor/roadmap/VERSION.txt +1 -1
- package/vault/vendor/roadmap/index.js +85 -9
- package/vault/vendor/roadmap/manifests.js +25 -24
- package/vault/vendor/vault/VERSION.txt +1 -1
- package/vault/vendor/vault/admin.js +4 -1
- package/vault/vendor/vault/core/libVersion.js +1 -1
- package/vault/vendor/vault/core/secretsStore.js +4 -1
- package/vault/vendor/vault/core/vault.js +14 -3
- package/vault/vendor/vault/passwordLogins.js +4 -2
|
@@ -25,6 +25,35 @@ const HELLO_TAG = '__cc_hello__'
|
|
|
25
25
|
*/
|
|
26
26
|
const SPEAKS = ['binary']
|
|
27
27
|
|
|
28
|
+
/** @typedef {import('./index.js').WebSocketProxyClientOptions} WebSocketProxyClientOptions */
|
|
29
|
+
/** @typedef {import('./index.js').SignFn} SignFn */
|
|
30
|
+
/** @typedef {import('./index.js').TransportStats} TransportStats */
|
|
31
|
+
/**
|
|
32
|
+
* Una trama JSON del proxio, de ida o de vuelta. Llega de la red: su forma la decide `type`.
|
|
33
|
+
* @typedef {Record<string, any>} Frame
|
|
34
|
+
*/
|
|
35
|
+
/**
|
|
36
|
+
* Lo que acompaña a un mensaje entregado a la app (`via`, `fromPubkey`, `sealed`…).
|
|
37
|
+
* @typedef {Record<string, any>} MessageMeta
|
|
38
|
+
*/
|
|
39
|
+
/** @typedef {(...args: any[]) => void} Handler */
|
|
40
|
+
/**
|
|
41
|
+
* Una petición que espera su respuesta del proxio.
|
|
42
|
+
* @typedef {{ resolve: (data: Frame) => void, reject: (e: unknown) => void,
|
|
43
|
+
* timer: ReturnType<typeof setTimeout>, expectedType: string, channelKey?: string }} PendingRequest
|
|
44
|
+
*/
|
|
45
|
+
/**
|
|
46
|
+
* Un mensaje por token que, si el token murió, sale por pubkey (`_tokenFailed`).
|
|
47
|
+
* @typedef {{ token: string, envelope: any, peerPubkey: string,
|
|
48
|
+
* timer: ReturnType<typeof setTimeout>, queueFallback: boolean }} TokenWatch
|
|
49
|
+
*/
|
|
50
|
+
/**
|
|
51
|
+
* Un mensaje medido para sus topes: su paquete si lleva bytes, su JSON si no.
|
|
52
|
+
* @typedef {{ bin: true, whole: Uint8Array, len: number } | { bin: false, whole: string, len: number }} Measured
|
|
53
|
+
*/
|
|
54
|
+
/** El relevo TURN en `stats()`. @typedef {NonNullable<TransportStats['turn']>} TurnState */
|
|
55
|
+
/** Un canal directo (WebRTC o Bluetooth): los dos tienen la misma forma. @typedef {WebRTCManager | BluetoothManager} DirectChannel */
|
|
56
|
+
|
|
28
57
|
/**
|
|
29
58
|
* Dotrino WebSocket proxy client.
|
|
30
59
|
* Minimal API: connection + token + messages + channels (publish/list/count/disconnect)
|
|
@@ -48,6 +77,9 @@ const APP_RE = /^[a-z0-9][a-z0-9-]{0,31}$/
|
|
|
48
77
|
/**
|
|
49
78
|
* Valida un nombre de app (`messenger`, `vault`…). Lo que no tiene forma LANZA: un nombre mal
|
|
50
79
|
* escrito haría que el timbre no sonara nunca en esa app, y eso no se ve.
|
|
80
|
+
*
|
|
81
|
+
* @param {unknown} app
|
|
82
|
+
* @returns {string | null}
|
|
51
83
|
*/
|
|
52
84
|
function checkApp (app) {
|
|
53
85
|
if (app == null) return null
|
|
@@ -58,6 +90,7 @@ function checkApp (app) {
|
|
|
58
90
|
}
|
|
59
91
|
|
|
60
92
|
export class WebSocketProxyClient {
|
|
93
|
+
/** @param {WebSocketProxyClientOptions} [options] */
|
|
61
94
|
constructor (options = {}) {
|
|
62
95
|
this.url = options.url || 'wss://proxy.dotrino.com'
|
|
63
96
|
this.autoReconnect = options.autoReconnect !== false
|
|
@@ -121,7 +154,9 @@ export class WebSocketProxyClient {
|
|
|
121
154
|
* pasó por `readEncPubStatement`, así que lo de dentro está atado a su identidad.
|
|
122
155
|
* No se cachean los fallos: «hoy no la tengo» no es un hecho, es un momento.
|
|
123
156
|
*/
|
|
157
|
+
/** @type {Map<string, string>} */
|
|
124
158
|
this._encPubs = new Map()
|
|
159
|
+
/** @type {Map<string, Promise<string>>} */
|
|
125
160
|
this._encPubInflight = new Map()
|
|
126
161
|
|
|
127
162
|
/**
|
|
@@ -135,14 +170,21 @@ export class WebSocketProxyClient {
|
|
|
135
170
|
* Se vacía al reconectar: los tokens se reparten por conexión y los de antes ya no
|
|
136
171
|
* son de nadie.
|
|
137
172
|
*/
|
|
173
|
+
/** @type {Map<string, string>} */
|
|
138
174
|
this._tokenPubkeys = new Map()
|
|
139
175
|
// Lo que dijo entender cada token en su saludo, y cada identidad (para lo que va por
|
|
140
176
|
// pubkey). Sin saludo no se sabe, y entonces no se frena nada.
|
|
177
|
+
/** @type {Map<string, Set<string>>} */
|
|
141
178
|
this._tokenSpeaks = new Map()
|
|
179
|
+
/** @type {Map<string, Set<string>>} */
|
|
142
180
|
this._pubkeySpeaks = new Map()
|
|
181
|
+
/** @type {Set<string>} */
|
|
143
182
|
this._helloSent = new Set()
|
|
144
183
|
|
|
145
|
-
/**
|
|
184
|
+
/**
|
|
185
|
+
* Mi propia identidad en el cable, la que `identify` dejó atada a este token.
|
|
186
|
+
* @type {string | null}
|
|
187
|
+
*/
|
|
146
188
|
this.myPublickey = null
|
|
147
189
|
|
|
148
190
|
/**
|
|
@@ -174,6 +216,8 @@ export class WebSocketProxyClient {
|
|
|
174
216
|
* own messages with `sealing` and still has to open what the ecosystem seals to its
|
|
175
217
|
* transport key with the pilar's envelope. With `myEncPrivateKey` next to `sealing`,
|
|
176
218
|
* the pilar envelope is opened too, and `sendSealed*(…, { pilar: true })` seals with it.
|
|
219
|
+
*
|
|
220
|
+
* @type {import('./index.js').SealingBridge | null}
|
|
177
221
|
*/
|
|
178
222
|
this.sealing = options.sealing || null
|
|
179
223
|
|
|
@@ -186,18 +230,26 @@ export class WebSocketProxyClient {
|
|
|
186
230
|
this.enableHeartbeat = options.enableHeartbeat !== false
|
|
187
231
|
this.heartbeatInterval = options.heartbeatInterval ?? 20000
|
|
188
232
|
this.heartbeatTimeout = options.heartbeatTimeout ?? 8000
|
|
233
|
+
/** @type {ReturnType<typeof setInterval> | null} */
|
|
189
234
|
this._hbTimer = null
|
|
235
|
+
/** @type {ReturnType<typeof setTimeout> | null} */
|
|
190
236
|
this._hbDeadTimer = null
|
|
191
237
|
|
|
238
|
+
/** @type {WebSocket | null} */
|
|
192
239
|
this.ws = null
|
|
240
|
+
/** @type {string | null} */
|
|
193
241
|
this.token = null
|
|
194
242
|
this._connected = false
|
|
195
243
|
this._reconnectAttempts = 0
|
|
244
|
+
/** @type {ReturnType<typeof setTimeout> | null} */
|
|
196
245
|
this._reconnectTimer = null
|
|
246
|
+
/** @type {Map<string, Set<Handler>>} */
|
|
197
247
|
this._handlers = new Map()
|
|
198
|
-
|
|
248
|
+
/** @type {Map<string, PendingRequest>} messageId -> { resolve, reject, timer } */
|
|
249
|
+
this._pending = new Map()
|
|
199
250
|
this._nextId = 1
|
|
200
|
-
|
|
251
|
+
/** @type {Map<string, TokenWatch>} messageId -> { token, sobre, peerPubkey, timer, queueFallback } */
|
|
252
|
+
this._tokenWatch = new Map()
|
|
201
253
|
// Mensajes grandes que llegan en partes (parts.js). Uno que se queda a medias se DICE:
|
|
202
254
|
// con él se pierde el mensaje entero, y eso no puede pasar callado.
|
|
203
255
|
this._parts = new Reassembler({
|
|
@@ -205,9 +257,37 @@ export class WebSocketProxyClient {
|
|
|
205
257
|
})
|
|
206
258
|
// Las CEK de los mensajes con bytes ya abiertas, por su sobre: todas las partes de un
|
|
207
259
|
// mensaje traen la misma, y abrirla es una vuelta a la bóveda. Pocas: un mensaje vivo.
|
|
260
|
+
/** @type {Map<string, Promise<string>>} */
|
|
208
261
|
this._msgKeys = new Map()
|
|
209
262
|
this._traffic = new TrafficStats()
|
|
210
263
|
|
|
264
|
+
// Lo que se rellena después (al conectar, al pedir TURN…). Declarado aquí para el
|
|
265
|
+
// chequeo de tipos; leerlo no cambia nada.
|
|
266
|
+
/** @type {boolean | undefined} */
|
|
267
|
+
this._closed // eslint-disable-line no-unused-expressions
|
|
268
|
+
/** @type {Set<string> | undefined} */
|
|
269
|
+
this._rtcTried // eslint-disable-line no-unused-expressions
|
|
270
|
+
/** @type {ReturnType<typeof setTimeout> | null | undefined} */
|
|
271
|
+
this._turnTimer // eslint-disable-line no-unused-expressions
|
|
272
|
+
/** @type {TurnState | undefined} */
|
|
273
|
+
this._turn // eslint-disable-line no-unused-expressions
|
|
274
|
+
/** @type {((token: string) => void) | null | undefined} */
|
|
275
|
+
this._connectResolve // eslint-disable-line no-unused-expressions
|
|
276
|
+
/** @type {((e: unknown) => void) | null | undefined} */
|
|
277
|
+
this._connectReject // eslint-disable-line no-unused-expressions
|
|
278
|
+
/** @type {string | undefined} */
|
|
279
|
+
this.instance // eslint-disable-line no-unused-expressions
|
|
280
|
+
/** @type {string | null | undefined} The proxy node this connection landed on (set on `connected`). */
|
|
281
|
+
this.node // eslint-disable-line no-unused-expressions
|
|
282
|
+
/** @type {string[] | undefined} */
|
|
283
|
+
this.peers // eslint-disable-line no-unused-expressions
|
|
284
|
+
/** @type {string[] | undefined} */
|
|
285
|
+
this.knownNodes // eslint-disable-line no-unused-expressions
|
|
286
|
+
/** @type {number | null | undefined} */
|
|
287
|
+
this.protocol // eslint-disable-line no-unused-expressions
|
|
288
|
+
/** @type {string[] | null | undefined} */
|
|
289
|
+
this.caps // eslint-disable-line no-unused-expressions
|
|
290
|
+
|
|
211
291
|
this._rtc = this.enableWebRTC ? new WebRTCManager({
|
|
212
292
|
getSelfToken: () => this.token,
|
|
213
293
|
signalSend: (to, payload) => this._proxySendOne(to, payload),
|
|
@@ -273,20 +353,24 @@ export class WebSocketProxyClient {
|
|
|
273
353
|
*/
|
|
274
354
|
_prepareBluetooth () {
|
|
275
355
|
if (!this._ble || this._ble.available || this._bleStarting) return this._bleStarting
|
|
356
|
+
const ble = this._ble
|
|
276
357
|
this._bleStarting = (async () => {
|
|
277
|
-
|
|
278
|
-
|
|
358
|
+
/** @type {import('./index.js').BluetoothAdapter | null} */
|
|
359
|
+
let adapter
|
|
360
|
+
if (this._bleOption === true) {
|
|
279
361
|
const mod = './ble/bluez.js'
|
|
280
|
-
const { openBluez } = await import(/* @vite-ignore */ mod)
|
|
362
|
+
const { openBluez } = /** @type {typeof import('./ble/bluez.js')} */ (await import(/* @vite-ignore */ mod))
|
|
281
363
|
adapter = await openBluez()
|
|
282
364
|
if (!adapter) return
|
|
365
|
+
} else {
|
|
366
|
+
adapter = this._bleOption
|
|
283
367
|
}
|
|
284
368
|
// Cerrado mientras se abría el bus: el stop() de close() no lo vio, así que se cierra aquí.
|
|
285
|
-
if (this._closed) { if (this._bleOption === true) await adapter.stop().catch(() => {}); return }
|
|
286
|
-
await
|
|
287
|
-
if (this._closed) await
|
|
369
|
+
if (this._closed) { if (this._bleOption === true) await /** @type {import('./index.js').BluetoothAdapter} */ (adapter).stop().catch(() => {}); return }
|
|
370
|
+
await ble.start(/** @type {import('./index.js').BluetoothAdapter} */ (adapter))
|
|
371
|
+
if (this._closed) await ble.stop().catch(() => {})
|
|
288
372
|
})().catch((e) => {
|
|
289
|
-
this._emit('error', { type: 'bluetooth_unavailable', error: e, code: e
|
|
373
|
+
this._emit('error', { type: 'bluetooth_unavailable', error: e, code: codeOf(e) })
|
|
290
374
|
}).finally(() => { this._bleStarting = null })
|
|
291
375
|
return this._bleStarting
|
|
292
376
|
}
|
|
@@ -298,6 +382,8 @@ export class WebSocketProxyClient {
|
|
|
298
382
|
* Anuncia `{kind, data}` por Bluetooth hasta que se llame a lo que devuelve
|
|
299
383
|
* (docs/bluetooth.md §3). `kind: 'pair'` es la invitación de emparejar; `'contact'`, la
|
|
300
384
|
* tarjeta de contacto. Lanza `no-bluetooth` si aquí no lo hay.
|
|
385
|
+
* @param {string} kind
|
|
386
|
+
* @param {string} data
|
|
301
387
|
* @returns {() => void}
|
|
302
388
|
*/
|
|
303
389
|
announceBluetooth (kind, data) {
|
|
@@ -308,6 +394,7 @@ export class WebSocketProxyClient {
|
|
|
308
394
|
/**
|
|
309
395
|
* Lo que anuncian por Bluetooth los aparatos de alrededor con ese `kind`. No necesita el
|
|
310
396
|
* proxio. `onFound` avisa de cada uno según aparece.
|
|
397
|
+
* @param {{ kind: string, timeoutMs?: number, onFound?: (b: import('./index.js').BluetoothBeacon) => void }} opts
|
|
311
398
|
* @returns {Promise<{kind: string, data: string}[]>}
|
|
312
399
|
*/
|
|
313
400
|
async discoverBluetooth ({ kind, timeoutMs, onFound } = /** @type {any} */ ({})) {
|
|
@@ -316,7 +403,10 @@ export class WebSocketProxyClient {
|
|
|
316
403
|
return this._ble.discover({ kind, timeoutMs, onFound })
|
|
317
404
|
}
|
|
318
405
|
|
|
319
|
-
/**
|
|
406
|
+
/**
|
|
407
|
+
* La red local (docs/lan.md), cargada una vez y solo si se pidió (`lan: true`, Node).
|
|
408
|
+
* @returns {Promise<typeof import('./lan/mdns.js') | null>}
|
|
409
|
+
*/
|
|
320
410
|
async _lanModule () {
|
|
321
411
|
if (!this._lanOption) return null
|
|
322
412
|
const mod = './lan/mdns.js'
|
|
@@ -327,9 +417,12 @@ export class WebSocketProxyClient {
|
|
|
327
417
|
* ANUNCIA CERCA: `{kind, data}` por cada medio que este cliente tenga, el Bluetooth y la red
|
|
328
418
|
* local, hasta que se llame a lo que devuelve. Un medio que falla no tumba a los otros; si no
|
|
329
419
|
* queda ninguno, lanza `no-nearby`.
|
|
420
|
+
* @param {string} kind
|
|
421
|
+
* @param {string} data
|
|
330
422
|
* @returns {Promise<() => void>}
|
|
331
423
|
*/
|
|
332
424
|
async announceNearby (kind, data) {
|
|
425
|
+
/** @type {Array<() => void>} */
|
|
333
426
|
const stops = []
|
|
334
427
|
if (this._ble) {
|
|
335
428
|
await this._prepareBluetooth()
|
|
@@ -338,7 +431,7 @@ export class WebSocketProxyClient {
|
|
|
338
431
|
const lan = await this._lanModule()
|
|
339
432
|
if (lan) {
|
|
340
433
|
try { stops.push(await lan.announceLan(kind, data)) } catch (e) {
|
|
341
|
-
this._emit('error', { type: 'lan_unavailable', error: e, code: e
|
|
434
|
+
this._emit('error', { type: 'lan_unavailable', error: e, code: codeOf(e) })
|
|
342
435
|
}
|
|
343
436
|
}
|
|
344
437
|
if (!stops.length) throw errorWithCode('nearby: neither Bluetooth nor the local network is available here', 'no-nearby')
|
|
@@ -348,16 +441,20 @@ export class WebSocketProxyClient {
|
|
|
348
441
|
/**
|
|
349
442
|
* BUSCA CERCA, por los mismos medios y a la vez. Cada hallazgo lleva `via` (`'bluetooth'` o
|
|
350
443
|
* `'lan'`); lo mismo visto por los dos medios sale una vez. Sin ningún medio, `no-nearby`.
|
|
444
|
+
* @param {{ kind: string, timeoutMs?: number, onFound?: (b: import('./index.js').NearbyBeacon) => void }} opts
|
|
351
445
|
* @returns {Promise<{kind: string, data: string, via: 'bluetooth'|'lan'}[]>}
|
|
352
446
|
*/
|
|
353
447
|
async discoverNearby ({ kind, timeoutMs = 8000, onFound } = /** @type {any} */ ({})) {
|
|
448
|
+
/** @type {import('./index.js').NearbyBeacon[]} */
|
|
354
449
|
const found = []
|
|
355
|
-
|
|
450
|
+
/** @param {'bluetooth' | 'lan'} via */
|
|
451
|
+
const add = (via) => (/** @type {{ kind: string, data: string }} */ f) => {
|
|
356
452
|
if (found.some((x) => x.kind === f.kind && x.data === f.data)) return
|
|
357
453
|
const item = { kind: f.kind, data: f.data, via }
|
|
358
454
|
found.push(item)
|
|
359
455
|
try { onFound?.(item) } catch (_) {}
|
|
360
456
|
}
|
|
457
|
+
/** @type {Array<Promise<unknown>>} */
|
|
361
458
|
const runs = []
|
|
362
459
|
if (this._ble) {
|
|
363
460
|
await this._prepareBluetooth()
|
|
@@ -366,7 +463,7 @@ export class WebSocketProxyClient {
|
|
|
366
463
|
const lan = await this._lanModule()
|
|
367
464
|
if (lan) {
|
|
368
465
|
runs.push(lan.discoverLan({ kind, timeoutMs, onFound: add('lan') }).catch((e) => {
|
|
369
|
-
this._emit('error', { type: 'lan_unavailable', error: e, code: e
|
|
466
|
+
this._emit('error', { type: 'lan_unavailable', error: e, code: codeOf(e) })
|
|
370
467
|
return null
|
|
371
468
|
}))
|
|
372
469
|
}
|
|
@@ -378,12 +475,13 @@ export class WebSocketProxyClient {
|
|
|
378
475
|
return found
|
|
379
476
|
}
|
|
380
477
|
|
|
478
|
+
/** @returns {Promise<string>} */
|
|
381
479
|
connect () {
|
|
382
480
|
this._closed = false
|
|
383
481
|
this._rtc?.reopen()
|
|
384
482
|
this._prepareBluetooth()
|
|
385
|
-
return new Promise((resolve, reject) => {
|
|
386
|
-
if (this._connected) return resolve(this.token)
|
|
483
|
+
return new Promise(/** @param {(token: string) => void} resolve @param {(e: unknown) => void} reject */ (resolve, reject) => {
|
|
484
|
+
if (this._connected) return resolve(/** @type {string} */ (this.token))
|
|
387
485
|
// Un reintento que estaba esperando su turno sobra: este `connect()` ya abre uno.
|
|
388
486
|
if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null }
|
|
389
487
|
this._connectResolve = resolve
|
|
@@ -417,7 +515,10 @@ export class WebSocketProxyClient {
|
|
|
417
515
|
this._rejectAllPending(errorWithCode('Connection closed', 'CONNECTION_CLOSED'))
|
|
418
516
|
}
|
|
419
517
|
|
|
420
|
-
/**
|
|
518
|
+
/**
|
|
519
|
+
* Corta en seco todo lo que esperaba respuesta, con su motivo.
|
|
520
|
+
* @param {Error} error
|
|
521
|
+
*/
|
|
421
522
|
_rejectAllPending (error) {
|
|
422
523
|
const pending = [...this._pending.values()]
|
|
423
524
|
this._pending.clear()
|
|
@@ -430,7 +531,10 @@ export class WebSocketProxyClient {
|
|
|
430
531
|
/** Alias for close() to ease migration from older clients. */
|
|
431
532
|
disconnect () { return this.close() }
|
|
432
533
|
|
|
433
|
-
/**
|
|
534
|
+
/**
|
|
535
|
+
* Update connection options before (re)connecting.
|
|
536
|
+
* @param {WebSocketProxyClientOptions} [options]
|
|
537
|
+
*/
|
|
434
538
|
updateConfig (options = {}) {
|
|
435
539
|
if (options.url) this.url = options.url
|
|
436
540
|
if (typeof options.autoReconnect === 'boolean') this.autoReconnect = options.autoReconnect
|
|
@@ -465,12 +569,19 @@ export class WebSocketProxyClient {
|
|
|
465
569
|
}
|
|
466
570
|
}
|
|
467
571
|
|
|
572
|
+
/**
|
|
573
|
+
* @param {import('./index.js').ProxyEvent | string} event
|
|
574
|
+
* @param {Handler} handler
|
|
575
|
+
* @returns {() => void}
|
|
576
|
+
*/
|
|
468
577
|
on (event, handler) {
|
|
469
|
-
|
|
470
|
-
this._handlers.
|
|
578
|
+
let set = this._handlers.get(event)
|
|
579
|
+
if (!set) { set = new Set(); this._handlers.set(event, set) }
|
|
580
|
+
set.add(handler)
|
|
471
581
|
return () => this.off(event, handler)
|
|
472
582
|
}
|
|
473
583
|
|
|
584
|
+
/** @param {import('./index.js').ProxyEvent | string} event @param {Handler} handler */
|
|
474
585
|
off (event, handler) {
|
|
475
586
|
const set = this._handlers.get(event)
|
|
476
587
|
if (set) set.delete(handler)
|
|
@@ -479,6 +590,9 @@ export class WebSocketProxyClient {
|
|
|
479
590
|
/**
|
|
480
591
|
* Send a payload to one or many peer tokens.
|
|
481
592
|
* The payload is JSON-stringified into the envelope's `message` field.
|
|
593
|
+
*
|
|
594
|
+
* @param {string | string[]} to
|
|
595
|
+
* @param {any} payload
|
|
482
596
|
*/
|
|
483
597
|
send (to, payload) {
|
|
484
598
|
// `requireSealed` vale para los DOS caminos dirigidos, no solo para el de pubkey
|
|
@@ -523,21 +637,23 @@ export class WebSocketProxyClient {
|
|
|
523
637
|
* quemar CPU y señalización para nada. Si el canal se cae, `webrtc_close` lo desapunta y
|
|
524
638
|
* el siguiente mensaje vuelve a intentarlo.
|
|
525
639
|
*/
|
|
640
|
+
/** @param {string[]} tokens */
|
|
526
641
|
_upgradeDirect (tokens) {
|
|
527
642
|
// El Bluetooth negocia en paralelo con WebRTC y deduplica solo (ble/manager.js).
|
|
528
643
|
if (this._ble?.available) for (const t of tokens) if (!this._ble.isOpen(t)) this._ble.upgrade(t)
|
|
529
|
-
|
|
530
|
-
|
|
644
|
+
const rtc = this._rtc
|
|
645
|
+
if (!rtc) return
|
|
646
|
+
const tried = this._rtcTried = this._rtcTried || new Set()
|
|
531
647
|
for (const t of tokens) {
|
|
532
|
-
if (
|
|
533
|
-
|
|
648
|
+
if (tried.has(t) || rtc.isOpen(t)) continue
|
|
649
|
+
tried.add(t)
|
|
534
650
|
// La implementación se busca AQUÍ, justo antes de negociar, y no al conectar: esto ya
|
|
535
651
|
// corre desatendido, así que la espera no se la come nadie. Lanzarlo desde `connect`
|
|
536
652
|
// metía un microtask de más y descuadraba los tiempos de otras cosas — lo cazaron
|
|
537
653
|
// las pruebas del protocolo, que fallaban solo al correr todas juntas.
|
|
538
654
|
Promise.resolve()
|
|
539
655
|
.then(() => this._prepareWebRTC())
|
|
540
|
-
.then(() => this._rtc.connect(t))
|
|
656
|
+
.then(() => /** @type {WebRTCManager} */ (this._rtc).connect(t))
|
|
541
657
|
.catch(() => {}) // no poder ir directo no es un fallo: es el caso normal en internet
|
|
542
658
|
}
|
|
543
659
|
}
|
|
@@ -545,13 +661,19 @@ export class WebSocketProxyClient {
|
|
|
545
661
|
/**
|
|
546
662
|
* Force opening (or reusing) a WebRTC DataChannel to a peer.
|
|
547
663
|
* Resolves once the channel is open. Rejects on failure.
|
|
664
|
+
* @param {string} token
|
|
665
|
+
* @returns {Promise<void>}
|
|
548
666
|
*/
|
|
549
667
|
connectWebRTC (token) {
|
|
550
668
|
if (!this._rtc) return Promise.reject(new Error('WebRTC disabled'))
|
|
551
669
|
return this._rtc.connect(token)
|
|
552
670
|
}
|
|
553
671
|
|
|
554
|
-
/**
|
|
672
|
+
/**
|
|
673
|
+
* True if there is an open DataChannel to the given peer.
|
|
674
|
+
* @param {string} token
|
|
675
|
+
* @returns {boolean}
|
|
676
|
+
*/
|
|
555
677
|
isWebRTCOpen (token) {
|
|
556
678
|
return !!(this._rtc && this._rtc.isOpen(token))
|
|
557
679
|
}
|
|
@@ -559,22 +681,31 @@ export class WebSocketProxyClient {
|
|
|
559
681
|
/**
|
|
560
682
|
* EL MEJOR CANAL ABIERTO, en el orden de la escalera (docs/bluetooth.md §1): WebRTC si va
|
|
561
683
|
* directo, si no Bluetooth, si no WebRTC por TURN. False = por el proxio.
|
|
684
|
+
*
|
|
685
|
+
* @param {string} token
|
|
686
|
+
* @returns {DirectChannel | null}
|
|
562
687
|
*/
|
|
563
688
|
_directFor (token) {
|
|
564
689
|
const rtcOpen = !!this._rtc?.isOpen(token)
|
|
565
|
-
if (rtcOpen && this._rtc
|
|
690
|
+
if (rtcOpen && this._rtc?.peers?.get(token)?.route !== 'turn') return this._rtc
|
|
566
691
|
if (this._ble?.isOpen(token)) return this._ble
|
|
567
692
|
if (rtcOpen) return this._rtc
|
|
568
693
|
return null
|
|
569
694
|
}
|
|
570
695
|
|
|
571
|
-
/**
|
|
696
|
+
/**
|
|
697
|
+
* Manda por el mejor canal abierto; si no hay, deja que WebRTC empiece a negociar y da false.
|
|
698
|
+
* @param {string} token
|
|
699
|
+
* @param {string | Uint8Array} wire
|
|
700
|
+
* @returns {boolean}
|
|
701
|
+
*/
|
|
572
702
|
_tryDirect (token, wire) {
|
|
573
703
|
const d = this._directFor(token)
|
|
574
704
|
if (d) return d.trySend(token, wire)
|
|
575
705
|
return this._rtc ? this._rtc.trySend(token, wire) : false
|
|
576
706
|
}
|
|
577
707
|
|
|
708
|
+
/** @param {string} to @param {any} payload */
|
|
578
709
|
_proxySendOne (to, payload) {
|
|
579
710
|
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return
|
|
580
711
|
this._sendRaw({
|
|
@@ -586,23 +717,33 @@ export class WebSocketProxyClient {
|
|
|
586
717
|
/**
|
|
587
718
|
* Publish self into a public channel.
|
|
588
719
|
* @param {string} channelName
|
|
589
|
-
* @param {
|
|
720
|
+
* @param {Record<string, any>} [extraData] Extra fields baked into channel.data and signed.
|
|
721
|
+
* @returns {Promise<Frame>}
|
|
590
722
|
*/
|
|
591
723
|
async publish (channelName, extraData = {}) {
|
|
592
724
|
const channel = await buildSignedChannel(channelName, extraData)
|
|
593
725
|
return this._request({ type: 'publish', channel }, 'published', 'channel')
|
|
594
726
|
}
|
|
595
727
|
|
|
596
|
-
/**
|
|
728
|
+
/**
|
|
729
|
+
* Unpublish self from a public channel.
|
|
730
|
+
* @param {string} channelName
|
|
731
|
+
* @returns {Promise<Frame>}
|
|
732
|
+
*/
|
|
597
733
|
async unpublish (channelName) {
|
|
598
734
|
const channel = await buildSignedChannel(channelName)
|
|
599
735
|
return this._request({ type: 'unpublish', channel }, 'unpublished', 'channel')
|
|
600
736
|
}
|
|
601
737
|
|
|
602
|
-
/**
|
|
738
|
+
/**
|
|
739
|
+
* List the tokens currently in a channel.
|
|
740
|
+
* @param {string} channelName
|
|
741
|
+
* @returns {Promise<import('./index.js').ChannelTokens>}
|
|
742
|
+
*/
|
|
603
743
|
async list (channelName) {
|
|
604
744
|
const channel = await buildSignedChannel(channelName)
|
|
605
745
|
const res = await this._request({ type: 'list', channel }, 'channel_list', 'channel')
|
|
746
|
+
/** @type {import('./index.js').ChannelTokens} */
|
|
606
747
|
const tokens = res.tokens || []
|
|
607
748
|
// Vacío pero con una bóveda despertándose detrás (websocket-proxy ≥ 1.7.0): quien lista
|
|
608
749
|
// puede esperar unos segundos en vez de concluir que no hay nadie.
|
|
@@ -610,7 +751,10 @@ export class WebSocketProxyClient {
|
|
|
610
751
|
return tokens
|
|
611
752
|
}
|
|
612
753
|
|
|
613
|
-
/**
|
|
754
|
+
/**
|
|
755
|
+
* Alias for list() to ease migration from older clients.
|
|
756
|
+
* @param {string} channelName
|
|
757
|
+
*/
|
|
614
758
|
listChannel (channelName) { return this.list(channelName) }
|
|
615
759
|
|
|
616
760
|
/**
|
|
@@ -618,6 +762,9 @@ export class WebSocketProxyClient {
|
|
|
618
762
|
* `peer_disconnected` events live WITHOUT being listed as a member (you won't
|
|
619
763
|
* appear in others' list()). Ideal for a lobby that shows rooms in real time
|
|
620
764
|
* without publishing itself as a phantom room. Resolves with the current tokens.
|
|
765
|
+
*
|
|
766
|
+
* @param {string} channelName
|
|
767
|
+
* @returns {Promise<string[]>}
|
|
621
768
|
*/
|
|
622
769
|
async watch (channelName) {
|
|
623
770
|
const channel = await buildSignedChannel(channelName)
|
|
@@ -625,21 +772,34 @@ export class WebSocketProxyClient {
|
|
|
625
772
|
return res.tokens || []
|
|
626
773
|
}
|
|
627
774
|
|
|
628
|
-
/**
|
|
775
|
+
/**
|
|
776
|
+
* Stop watching a channel.
|
|
777
|
+
* @param {string} channelName
|
|
778
|
+
* @returns {Promise<Frame>}
|
|
779
|
+
*/
|
|
629
780
|
async unwatch (channelName) {
|
|
630
781
|
const channel = await buildSignedChannel(channelName)
|
|
631
782
|
return this._request({ type: 'unwatch', channel }, 'unwatched', 'channel')
|
|
632
783
|
}
|
|
633
784
|
|
|
634
|
-
/**
|
|
785
|
+
/**
|
|
786
|
+
* List public channel names (optionally filtered by prefix).
|
|
787
|
+
* @param {import('./index.js').ListChannelsOptions} [options]
|
|
788
|
+
* @returns {Promise<import('./index.js').ChannelEntry[]>}
|
|
789
|
+
*/
|
|
635
790
|
async listChannels (options = {}) {
|
|
791
|
+
/** @type {Frame} */
|
|
636
792
|
const msg = { type: 'list_channels' }
|
|
637
793
|
if (typeof options.prefix === 'string') msg.prefix = options.prefix
|
|
638
794
|
const res = await this._request(msg, 'channels_list')
|
|
639
795
|
return res.channels || []
|
|
640
796
|
}
|
|
641
797
|
|
|
642
|
-
/**
|
|
798
|
+
/**
|
|
799
|
+
* How many tokens are in a channel right now (no listing).
|
|
800
|
+
* @param {string} channelName
|
|
801
|
+
* @returns {Promise<number>}
|
|
802
|
+
*/
|
|
643
803
|
async channelCount (channelName) {
|
|
644
804
|
const res = await this._request(
|
|
645
805
|
{ type: 'channel_count', channel: channelName },
|
|
@@ -733,13 +893,13 @@ export class WebSocketProxyClient {
|
|
|
733
893
|
* @param {any} payload
|
|
734
894
|
* @param {{ peerPubkey?:string, peerEncPub?:string, pilar?:boolean }} [opts]
|
|
735
895
|
*/
|
|
736
|
-
async sendSealedTo (toTokens, payload, { peerPubkey, peerEncPub, pilar = false } =
|
|
896
|
+
async sendSealedTo (toTokens, payload, { peerPubkey, peerEncPub, pilar = false } = {}) {
|
|
737
897
|
const tokens = Array.isArray(toTokens) ? toTokens : [toTokens]
|
|
738
898
|
if (!peerEncPub) {
|
|
739
899
|
// Si la app no lo dice, lo dice el SALUDO: `helloTo` dejó apuntado de quién es
|
|
740
900
|
// cada token. Con más de uno no se adivina —cada identidad tiene su llave y un
|
|
741
901
|
// solo sobre solo lo abriría una—, así que ahí se exige decirlo.
|
|
742
|
-
if (!peerPubkey && tokens.length === 1) peerPubkey = this.pubkeyOfToken(tokens[0])
|
|
902
|
+
if (!peerPubkey && tokens.length === 1) peerPubkey = this.pubkeyOfToken(tokens[0]) || undefined
|
|
743
903
|
if (!peerPubkey) {
|
|
744
904
|
throw errorWithCode(
|
|
745
905
|
'sendSealedTo: nobody has said whose this token is — greet it (helloTo) or pass peerPubkey',
|
|
@@ -803,8 +963,9 @@ export class WebSocketProxyClient {
|
|
|
803
963
|
const d = this._directFor(token)
|
|
804
964
|
if (d && d === this._ble) return 'bluetooth'
|
|
805
965
|
if (d) {
|
|
806
|
-
const
|
|
807
|
-
|
|
966
|
+
const rtc = /** @type {WebRTCManager} */ (this._rtc)
|
|
967
|
+
const peer = /** @type {import('./webrtc.js').PeerState} */ (rtc.peers.get(token))
|
|
968
|
+
try { return (await rtc.probeRoute(peer)) || 'webrtc' } catch (_) { return 'webrtc' }
|
|
808
969
|
}
|
|
809
970
|
return 'proxy'
|
|
810
971
|
}
|
|
@@ -813,6 +974,12 @@ export class WebSocketProxyClient {
|
|
|
813
974
|
* Una parte por token: por el canal directo esperando a que vacíe su búfer (sin eso, un
|
|
814
975
|
* archivo grande lo desborda y el navegador cierra el canal), o por el proxio en vivo con
|
|
815
976
|
* una pausa corta entre partes, para no chocar con su límite de mensajes por segundo.
|
|
977
|
+
*
|
|
978
|
+
* @param {string} token
|
|
979
|
+
* @param {string | Uint8Array} envelope
|
|
980
|
+
* @param {string} peerPubkey
|
|
981
|
+
* @param {boolean} queueFallback
|
|
982
|
+
* @param {boolean} [relayFallback]
|
|
816
983
|
*/
|
|
817
984
|
async _sendPiece (token, envelope, peerPubkey, queueFallback, relayFallback = true) {
|
|
818
985
|
const d = this._directFor(token)
|
|
@@ -856,6 +1023,11 @@ export class WebSocketProxyClient {
|
|
|
856
1023
|
* su pubkey: la cola de 24 h del proxio, que además timbra su teléfono. Y se avisa con
|
|
857
1024
|
* `token_gone` para que la app deje de usar ese token. No bloquea a nadie: se manda ya y
|
|
858
1025
|
* el arreglo, si hace falta, llega detrás.
|
|
1026
|
+
*
|
|
1027
|
+
* @param {string} token
|
|
1028
|
+
* @param {any} envelope
|
|
1029
|
+
* @param {string} peerPubkey
|
|
1030
|
+
* @param {{ queueFallback?: boolean, skipDirect?: boolean }} [opts]
|
|
859
1031
|
*/
|
|
860
1032
|
_sendToTokenOrQueue (token, envelope, peerPubkey, { queueFallback = true, skipDirect = false } = {}) {
|
|
861
1033
|
if (this.requireSealed && !this._isSealed(envelope)) {
|
|
@@ -877,7 +1049,10 @@ export class WebSocketProxyClient {
|
|
|
877
1049
|
this._upgradeDirect([token])
|
|
878
1050
|
}
|
|
879
1051
|
|
|
880
|
-
/**
|
|
1052
|
+
/**
|
|
1053
|
+
* `message_sent` con fallos: lo que iba a un token que ya no existe sale por pubkey.
|
|
1054
|
+
* @param {Frame} data
|
|
1055
|
+
*/
|
|
881
1056
|
_tokenFailed (data) {
|
|
882
1057
|
const w = data.id && this._tokenWatch.get(data.id)
|
|
883
1058
|
if (!w) return
|
|
@@ -890,7 +1065,7 @@ export class WebSocketProxyClient {
|
|
|
890
1065
|
this._emit('error', { type: 'client', error: 'the peer left in the middle of a message too big to wait in the proxy', code: 'too-big-for-queue', peerPubkey: w.peerPubkey })
|
|
891
1066
|
return
|
|
892
1067
|
}
|
|
893
|
-
try { this._sendByPubkeyRaw([w.peerPubkey], w.envelope) } catch (e) { this._emit('error', { type: 'client', error: e.message, code: e
|
|
1068
|
+
try { this._sendByPubkeyRaw([w.peerPubkey], w.envelope) } catch (e) { this._emit('error', { type: 'client', error: /** @type {{ message?: string }} */ (e).message, code: codeOf(e) }) }
|
|
894
1069
|
}
|
|
895
1070
|
|
|
896
1071
|
// ---------- el saludo: de quién es este token ----------
|
|
@@ -912,6 +1087,8 @@ export class WebSocketProxyClient {
|
|
|
912
1087
|
* consigue que te sellen a una llave que no puedes abrir: el embustero se queda sin
|
|
913
1088
|
* leer, y nadie se queda suplantado. Quién firma de verdad lo dice el reto de la app,
|
|
914
1089
|
* o el `from_publickey` que pone el proxio cuando se enruta por pubkey.
|
|
1090
|
+
*
|
|
1091
|
+
* @param {string | string[]} to
|
|
915
1092
|
*/
|
|
916
1093
|
helloTo (to) {
|
|
917
1094
|
if (!this.myPublickey) {
|
|
@@ -925,7 +1102,11 @@ export class WebSocketProxyClient {
|
|
|
925
1102
|
}
|
|
926
1103
|
}
|
|
927
1104
|
|
|
928
|
-
/**
|
|
1105
|
+
/**
|
|
1106
|
+
* De quién es este token, si alguien lo ha dicho. `null` es «todavía no lo sé».
|
|
1107
|
+
* @param {string} token
|
|
1108
|
+
* @returns {string | null}
|
|
1109
|
+
*/
|
|
929
1110
|
pubkeyOfToken (token) {
|
|
930
1111
|
return this._tokenPubkeys.get(token) || null
|
|
931
1112
|
}
|
|
@@ -936,6 +1117,8 @@ export class WebSocketProxyClient {
|
|
|
936
1117
|
* `peer_identity` de vuelta. No autentica, y no hace falta: lo que se le mande va sellado a la
|
|
937
1118
|
* llave que ESA identidad anunció firmada. Espera a estar identificado, porque un saludo sin
|
|
938
1119
|
* identidad no dice nada.
|
|
1120
|
+
* @param {string} token
|
|
1121
|
+
* @param {number} [timeoutMs]
|
|
939
1122
|
* @returns {Promise<string|null>} la pubkey, o null si no contestó en `timeoutMs`
|
|
940
1123
|
*/
|
|
941
1124
|
async whoIs (token, timeoutMs = 10000) {
|
|
@@ -944,15 +1127,19 @@ export class WebSocketProxyClient {
|
|
|
944
1127
|
const t0 = Date.now()
|
|
945
1128
|
while (!this.myPublickey && Date.now() - t0 < timeoutMs) await new Promise((r) => setTimeout(r, 150))
|
|
946
1129
|
if (!this.myPublickey) return null
|
|
947
|
-
return new Promise((resolve) => {
|
|
1130
|
+
return new Promise(/** @param {(pk: string | null) => void} resolve */ (resolve) => {
|
|
1131
|
+
/** @param {string | null} pk */
|
|
948
1132
|
const done = (pk) => { off(); clearTimeout(timer); resolve(pk) }
|
|
949
|
-
const off = this.on('peer_identity', (t, pk) => { if (t === token) done(pk) })
|
|
1133
|
+
const off = this.on('peer_identity', (/** @type {string} */ t, /** @type {string} */ pk) => { if (t === token) done(pk) })
|
|
950
1134
|
const timer = setTimeout(() => done(null), Math.max(1000, timeoutMs - (Date.now() - t0)))
|
|
951
1135
|
try { this.helloTo(token) } catch (_) { done(null) }
|
|
952
1136
|
})
|
|
953
1137
|
}
|
|
954
1138
|
|
|
955
|
-
/**
|
|
1139
|
+
/**
|
|
1140
|
+
* Olvidar un token (se fue, o se quiere volver a preguntar). Sin argumento, todos.
|
|
1141
|
+
* @param {string | null} [token]
|
|
1142
|
+
*/
|
|
956
1143
|
forgetToken (token) {
|
|
957
1144
|
if (token == null) { this._tokenPubkeys.clear(); this._helloSent.clear(); this._tokenSpeaks.clear(); return }
|
|
958
1145
|
this._tokenPubkeys.delete(token)
|
|
@@ -975,7 +1162,10 @@ export class WebSocketProxyClient {
|
|
|
975
1162
|
return set ? set.has(feature) : null
|
|
976
1163
|
}
|
|
977
1164
|
|
|
978
|
-
/**
|
|
1165
|
+
/**
|
|
1166
|
+
* Antes de mandar bytes: si alguno dijo que no los entiende, no sale nada y se dice.
|
|
1167
|
+
* @param {string[]} targets
|
|
1168
|
+
*/
|
|
979
1169
|
_needPeerBinary (targets) {
|
|
980
1170
|
for (const t of targets) {
|
|
981
1171
|
if (t && this.speaks(t, 'binary') === false) {
|
|
@@ -984,6 +1174,7 @@ export class WebSocketProxyClient {
|
|
|
984
1174
|
}
|
|
985
1175
|
}
|
|
986
1176
|
|
|
1177
|
+
/** @param {string} from @param {Frame} msg */
|
|
987
1178
|
_onHello (from, msg) {
|
|
988
1179
|
if (typeof msg.publickey !== 'string' || !msg.publickey) return
|
|
989
1180
|
const antes = this._tokenPubkeys.get(from)
|
|
@@ -995,7 +1186,7 @@ export class WebSocketProxyClient {
|
|
|
995
1186
|
return
|
|
996
1187
|
}
|
|
997
1188
|
this._tokenPubkeys.set(from, msg.publickey)
|
|
998
|
-
const speaks = new Set(Array.isArray(msg.speaks) ? msg.speaks.filter((x) => typeof x === 'string').slice(0, 32) : [])
|
|
1189
|
+
const speaks = new Set(Array.isArray(msg.speaks) ? msg.speaks.filter((/** @type {unknown} */ x) => typeof x === 'string').slice(0, 32) : [])
|
|
999
1190
|
this._tokenSpeaks.set(from, speaks)
|
|
1000
1191
|
this._pubkeySpeaks.set(msg.publickey, speaks)
|
|
1001
1192
|
// Contestar UNA vez: el saludo queda simétrico sin rebotar para siempre.
|
|
@@ -1007,6 +1198,12 @@ export class WebSocketProxyClient {
|
|
|
1007
1198
|
* Sella con lo que haya: la bóveda de la app (`sealing`) o las primitivas del pilar.
|
|
1008
1199
|
* `pilar`: con el sobre del pilar aunque haya `sealing` (lo abre quien tenga la privada de
|
|
1009
1200
|
* `peerEncPub`, sin pasar por ninguna bóveda).
|
|
1201
|
+
*
|
|
1202
|
+
* @param {any} payload
|
|
1203
|
+
* @param {string | undefined} peerEncPub
|
|
1204
|
+
* @param {string | undefined} peerPubkey
|
|
1205
|
+
* @param {boolean} [pilar]
|
|
1206
|
+
* @returns {Promise<any>}
|
|
1010
1207
|
*/
|
|
1011
1208
|
async _seal (payload, peerEncPub, peerPubkey, pilar = false) {
|
|
1012
1209
|
if (!peerEncPub) throw errorWithCode('seal: missing peerEncPub', 'unsealed')
|
|
@@ -1015,12 +1212,21 @@ export class WebSocketProxyClient {
|
|
|
1015
1212
|
: seal(payload, peerEncPub)
|
|
1016
1213
|
}
|
|
1017
1214
|
|
|
1018
|
-
/**
|
|
1215
|
+
/**
|
|
1216
|
+
* ¿Este sobre es de la bóveda de la app (`sealing`)? Si no, es el del pilar.
|
|
1217
|
+
* @param {any} env
|
|
1218
|
+
* @returns {boolean}
|
|
1219
|
+
*/
|
|
1019
1220
|
_bySealing (env) { return !!this.sealing && this.sealing.isSealed(env) }
|
|
1020
1221
|
|
|
1021
|
-
/**
|
|
1222
|
+
/**
|
|
1223
|
+
* Abre un sobre con quien toca: la bóveda de la app o la llave del pilar.
|
|
1224
|
+
* @param {any} env
|
|
1225
|
+
* @param {MessageMeta} [meta]
|
|
1226
|
+
* @returns {Promise<any>}
|
|
1227
|
+
*/
|
|
1022
1228
|
_openEnvelope (env, meta) {
|
|
1023
|
-
if (this._bySealing(env)) return this.sealing.open(env, meta)
|
|
1229
|
+
if (this._bySealing(env)) return /** @type {import('./index.js').SealingBridge} */ (this.sealing).open(env, meta)
|
|
1024
1230
|
if (!this.myEncPrivateKey) throw errorWithCode('no encryption key to open a pilar envelope', 'unsealed')
|
|
1025
1231
|
return open(env, this.myEncPrivateKey)
|
|
1026
1232
|
}
|
|
@@ -1029,18 +1235,28 @@ export class WebSocketProxyClient {
|
|
|
1029
1235
|
* Quién sella las piezas de UN mensaje hacia UN destinatario. Con bytes (sealing.js): una
|
|
1030
1236
|
* CEK para el mensaje entero, sellada una vez con el sellado de siempre, y cada pieza
|
|
1031
1237
|
* cifrada como bytes con ella. Sin bytes, el sobre de texto de siempre por pieza.
|
|
1238
|
+
*
|
|
1239
|
+
* @param {boolean} bin
|
|
1240
|
+
* @param {string | undefined} peerEncPub
|
|
1241
|
+
* @param {string | undefined} peerPubkey
|
|
1242
|
+
* @param {boolean} [pilar]
|
|
1243
|
+
* @returns {Promise<(piece: any) => Promise<any>>}
|
|
1032
1244
|
*/
|
|
1033
1245
|
async _sealerFor (bin, peerEncPub, peerPubkey, pilar = false) {
|
|
1034
1246
|
if (!bin) return (piece) => this._seal(piece, peerEncPub, peerPubkey, pilar)
|
|
1035
1247
|
const cek = await makeMessageKey()
|
|
1036
1248
|
const k = await this._seal({ cek }, peerEncPub, peerPubkey, pilar)
|
|
1037
|
-
return async (bytes) => {
|
|
1249
|
+
return async (/** @type {Uint8Array} */ bytes) => {
|
|
1038
1250
|
const { iv, ct } = await encryptBytes(cek, bytes)
|
|
1039
1251
|
return pack({ bv: BIN_SEALED, k, iv, ct })
|
|
1040
1252
|
}
|
|
1041
1253
|
}
|
|
1042
1254
|
|
|
1043
|
-
/**
|
|
1255
|
+
/**
|
|
1256
|
+
* Lo que mide un mensaje para sus topes: su paquete si lleva bytes, su JSON si no.
|
|
1257
|
+
* @param {any} payload
|
|
1258
|
+
* @returns {Measured}
|
|
1259
|
+
*/
|
|
1044
1260
|
_measure (payload) {
|
|
1045
1261
|
if (hasBinary(payload)) {
|
|
1046
1262
|
const whole = pack(payload)
|
|
@@ -1050,7 +1266,11 @@ export class WebSocketProxyClient {
|
|
|
1050
1266
|
return { bin: false, whole, len: whole.length }
|
|
1051
1267
|
}
|
|
1052
1268
|
|
|
1053
|
-
/**
|
|
1269
|
+
/**
|
|
1270
|
+
* Cómo va por el cable: los bytes tal cual, el texto tal cual, y un objeto en JSON (o empaquetado, si lleva bytes).
|
|
1271
|
+
* @param {any} payload
|
|
1272
|
+
* @returns {string | Uint8Array}
|
|
1273
|
+
*/
|
|
1054
1274
|
_wire (payload) {
|
|
1055
1275
|
if (typeof payload === 'string' || payload instanceof Uint8Array) return payload
|
|
1056
1276
|
if (hasBinary(payload)) return pack(payload)
|
|
@@ -1064,7 +1284,12 @@ export class WebSocketProxyClient {
|
|
|
1064
1284
|
}
|
|
1065
1285
|
}
|
|
1066
1286
|
|
|
1067
|
-
/**
|
|
1287
|
+
/**
|
|
1288
|
+
* La CEK de un mensaje con bytes, abriendo su sobre una vez por mensaje.
|
|
1289
|
+
* @param {any} k
|
|
1290
|
+
* @param {MessageMeta} meta
|
|
1291
|
+
* @returns {Promise<string>}
|
|
1292
|
+
*/
|
|
1068
1293
|
_openMessageKey (k, meta) {
|
|
1069
1294
|
const id = JSON.stringify(k)
|
|
1070
1295
|
let p = this._msgKeys.get(id)
|
|
@@ -1075,7 +1300,7 @@ export class WebSocketProxyClient {
|
|
|
1075
1300
|
return o.cek
|
|
1076
1301
|
})()
|
|
1077
1302
|
this._msgKeys.set(id, p)
|
|
1078
|
-
if (this._msgKeys.size > 64) this._msgKeys.delete(this._msgKeys.keys().next().value)
|
|
1303
|
+
if (this._msgKeys.size > 64) this._msgKeys.delete(/** @type {string} */ (this._msgKeys.keys().next().value))
|
|
1079
1304
|
p.catch(() => this._msgKeys.delete(id))
|
|
1080
1305
|
}
|
|
1081
1306
|
return p
|
|
@@ -1090,6 +1315,9 @@ export class WebSocketProxyClient {
|
|
|
1090
1315
|
*
|
|
1091
1316
|
* Lo llama `identify` solo cuando el cliente tiene `myEncPub`. Se expone aparte para el
|
|
1092
1317
|
* caso de anunciar una llave nueva sin reconectar.
|
|
1318
|
+
*
|
|
1319
|
+
* @param {{ publickey: string, encPub: string, sign: SignFn }} args
|
|
1320
|
+
* @returns {Promise<string>}
|
|
1093
1321
|
*/
|
|
1094
1322
|
async announceEncPub ({ publickey, encPub, sign } = /** @type {any} */ ({})) {
|
|
1095
1323
|
const statement = await buildEncPubStatement({ publickey, encPub, sign })
|
|
@@ -1110,6 +1338,9 @@ export class WebSocketProxyClient {
|
|
|
1110
1338
|
* · `no-encpub-support` este proxio no sabe de esto (es viejo)
|
|
1111
1339
|
*
|
|
1112
1340
|
* Nunca devuelve `null` y nunca cae a «manda igual»: si no se puede sellar, no se manda.
|
|
1341
|
+
*
|
|
1342
|
+
* @param {string} publickey
|
|
1343
|
+
* @returns {Promise<string>}
|
|
1113
1344
|
*/
|
|
1114
1345
|
async encPubOf (publickey) {
|
|
1115
1346
|
if (typeof publickey !== 'string' || !publickey) {
|
|
@@ -1137,6 +1368,10 @@ export class WebSocketProxyClient {
|
|
|
1137
1368
|
* es «el proxio no tiene ninguna más nueva», no «no existe»: la bóveda sigue mandando.
|
|
1138
1369
|
*
|
|
1139
1370
|
* Lanza `no-acta-cache` si el proxio dice que no sabe de esto (es viejo).
|
|
1371
|
+
*
|
|
1372
|
+
* @param {string} profileId
|
|
1373
|
+
* @param {{ sinceSeq?: number }} [opts]
|
|
1374
|
+
* @returns {Promise<object[]>}
|
|
1140
1375
|
*/
|
|
1141
1376
|
async getActas (profileId, { sinceSeq } = {}) {
|
|
1142
1377
|
if (typeof profileId !== 'string' || !profileId) throw errorWithCode('getActas: missing profileId', 'bad-input')
|
|
@@ -1149,6 +1384,9 @@ export class WebSocketProxyClient {
|
|
|
1149
1384
|
* Le deja al proxio un acta de la cuenta, para que otros aparatos se enteren sin preguntar
|
|
1150
1385
|
* a la bóveda. Devuelve `{ stored }`: `false` es que ya la tenía o tiene más nuevas.
|
|
1151
1386
|
* Lanza `bad-acta` si no la selló su cuenta y `no-acta-cache` si el proxio es viejo.
|
|
1387
|
+
*
|
|
1388
|
+
* @param {object} acta
|
|
1389
|
+
* @returns {Promise<{ stored: boolean }>}
|
|
1152
1390
|
*/
|
|
1153
1391
|
async putActa (acta) {
|
|
1154
1392
|
if (!acta || typeof acta !== 'object') throw errorWithCode('putActa: missing acta', 'bad-input')
|
|
@@ -1164,6 +1402,7 @@ export class WebSocketProxyClient {
|
|
|
1164
1402
|
}
|
|
1165
1403
|
}
|
|
1166
1404
|
|
|
1405
|
+
/** @param {string} publickey @returns {Promise<string>} */
|
|
1167
1406
|
async _lookupEncPub (publickey) {
|
|
1168
1407
|
// EL CAMINO MÁS DIRECTO PRIMERO. Si la app comparte acta con el destinatario, la llave
|
|
1169
1408
|
// ya la tiene en la mano y firmada por el master: preguntársela a un servidor sería
|
|
@@ -1189,7 +1428,7 @@ export class WebSocketProxyClient {
|
|
|
1189
1428
|
const res = await this._request({ type: 'enc-lookup', publickeys: [publickey] }, 'enc-lookup')
|
|
1190
1429
|
// `samePubkey`, no `===`: el proxio guarda el string exacto con el que se anunció, y
|
|
1191
1430
|
// la app puede tener el mismo JWK escrito de otra forma.
|
|
1192
|
-
const statement = (res.keys || []).find((k) => samePubkey(k?.data?.publickey, publickey))
|
|
1431
|
+
const statement = (res.keys || []).find((/** @type {any} */ k) => samePubkey(k?.data?.publickey, publickey))
|
|
1193
1432
|
if (!statement) {
|
|
1194
1433
|
throw errorWithCode('no encryption key announced for that identity — it cannot be sealed to yet', 'no-encpub')
|
|
1195
1434
|
}
|
|
@@ -1200,19 +1439,28 @@ export class WebSocketProxyClient {
|
|
|
1200
1439
|
return encPub
|
|
1201
1440
|
}
|
|
1202
1441
|
|
|
1203
|
-
/**
|
|
1442
|
+
/**
|
|
1443
|
+
* Guardar una llave que ya viene firmada por su dueño (de un canal, de una invitación).
|
|
1444
|
+
* @param {import('./index.js').EncPubStatement} statement
|
|
1445
|
+
* @param {{ publickey: string }} args
|
|
1446
|
+
* @returns {Promise<string>}
|
|
1447
|
+
*/
|
|
1204
1448
|
async learnEncPub (statement, { publickey } = /** @type {any} */ ({})) {
|
|
1205
1449
|
const encPub = await readEncPubStatement(statement, { publickey })
|
|
1206
1450
|
this._encPubs.set(publickey, encPub)
|
|
1207
1451
|
return encPub
|
|
1208
1452
|
}
|
|
1209
1453
|
|
|
1210
|
-
/**
|
|
1454
|
+
/**
|
|
1455
|
+
* Olvidar lo aprendido de una identidad (rotó su llave, o se quiere volver a preguntar).
|
|
1456
|
+
* @param {string | null} [publickey]
|
|
1457
|
+
*/
|
|
1211
1458
|
forgetEncPub (publickey) {
|
|
1212
1459
|
if (publickey == null) this._encPubs.clear()
|
|
1213
1460
|
else this._encPubs.delete(publickey)
|
|
1214
1461
|
}
|
|
1215
1462
|
|
|
1463
|
+
/** @param {any} msg @returns {boolean} */
|
|
1216
1464
|
_isSealed (msg) {
|
|
1217
1465
|
if (msg instanceof Uint8Array) {
|
|
1218
1466
|
let env
|
|
@@ -1222,6 +1470,11 @@ export class WebSocketProxyClient {
|
|
|
1222
1470
|
return this.sealing ? (this.sealing.isSealed(msg) || (!!this.myEncPrivateKey && isSealed(msg))) : isSealed(msg)
|
|
1223
1471
|
}
|
|
1224
1472
|
|
|
1473
|
+
/**
|
|
1474
|
+
* @param {string | string[]} toPubkeys
|
|
1475
|
+
* @param {any} payload
|
|
1476
|
+
* @param {{ ephemeral?: boolean, quiet?: boolean, app?: string }} [opts]
|
|
1477
|
+
*/
|
|
1225
1478
|
sendByPubkey (toPubkeys, payload, opts = {}) {
|
|
1226
1479
|
if (this.requireSealed && !this._isSealed(payload)) {
|
|
1227
1480
|
throw Object.assign(
|
|
@@ -1239,6 +1492,10 @@ export class WebSocketProxyClient {
|
|
|
1239
1492
|
* receiving end still accepts plaintext, sending it that way bypasses the sealing
|
|
1240
1493
|
* entirely — and a peer that never read anything could still push a forged payload
|
|
1241
1494
|
* into the app.
|
|
1495
|
+
*
|
|
1496
|
+
* @param {string} from
|
|
1497
|
+
* @param {any} payload
|
|
1498
|
+
* @param {MessageMeta} meta
|
|
1242
1499
|
*/
|
|
1243
1500
|
async _deliver (from, payload, meta) {
|
|
1244
1501
|
// BYTES (binpack.js): un paquete. Si es un sobre binario se abre aquí; si no, es un
|
|
@@ -1246,7 +1503,7 @@ export class WebSocketProxyClient {
|
|
|
1246
1503
|
if (payload instanceof Uint8Array) {
|
|
1247
1504
|
let env
|
|
1248
1505
|
try { env = unpack(payload) } catch (e) {
|
|
1249
|
-
this._emit('error', { type: 'bad_pack', from, code: e
|
|
1506
|
+
this._emit('error', { type: 'bad_pack', from, code: codeOf(e) || 'bad-pack', error: e })
|
|
1250
1507
|
return
|
|
1251
1508
|
}
|
|
1252
1509
|
if (isBinSealed(env)) {
|
|
@@ -1293,21 +1550,32 @@ export class WebSocketProxyClient {
|
|
|
1293
1550
|
this._emit('message', from, payload, { ...meta, sealed: false })
|
|
1294
1551
|
}
|
|
1295
1552
|
|
|
1296
|
-
/**
|
|
1553
|
+
/**
|
|
1554
|
+
* Lo ya abierto a la app: entero, o a rearmar si es una parte (parts.js).
|
|
1555
|
+
* @param {string} from
|
|
1556
|
+
* @param {any} opened
|
|
1557
|
+
* @param {MessageMeta} fullMeta
|
|
1558
|
+
*/
|
|
1297
1559
|
_handOpened (from, opened, fullMeta) {
|
|
1298
1560
|
if (isPart(opened)) {
|
|
1299
1561
|
// Se agrupa por quien selló: solo esa llave pudo armar cada parte.
|
|
1300
1562
|
let whole
|
|
1301
1563
|
try { whole = this._parts.add(fullMeta.senderEncPub || fullMeta.fromPubkey || from || '', opened) }
|
|
1302
|
-
catch (e) { this._emit('error', { type: 'bad_part', from, code: e
|
|
1564
|
+
catch (e) { this._emit('error', { type: 'bad_part', from, code: codeOf(e) || 'bad-part', error: e }); return }
|
|
1303
1565
|
if (whole !== null) this._emit('message', from, whole, { ...fullMeta, parts: opened.__dotrino_part.n })
|
|
1304
1566
|
return
|
|
1305
1567
|
}
|
|
1306
1568
|
this._emit('message', from, opened, fullMeta)
|
|
1307
1569
|
}
|
|
1308
1570
|
|
|
1571
|
+
/**
|
|
1572
|
+
* @param {string | string[]} toPubkeys
|
|
1573
|
+
* @param {any} payload
|
|
1574
|
+
* @param {{ ephemeral?: boolean, quiet?: boolean, app?: string }} [opts]
|
|
1575
|
+
*/
|
|
1309
1576
|
_sendByPubkeyRaw (toPubkeys, payload, opts = {}) {
|
|
1310
1577
|
const list = Array.isArray(toPubkeys) ? toPubkeys : [toPubkeys]
|
|
1578
|
+
/** @type {Frame} */
|
|
1311
1579
|
const msg = {
|
|
1312
1580
|
to_publickey: list,
|
|
1313
1581
|
message: this._wire(payload)
|
|
@@ -1337,9 +1605,10 @@ export class WebSocketProxyClient {
|
|
|
1337
1605
|
* @returns {Promise<{code:string, expiresAt:number, node:string}>}
|
|
1338
1606
|
*/
|
|
1339
1607
|
requestPairingCode (opts = {}) {
|
|
1608
|
+
/** @type {Frame} */
|
|
1340
1609
|
const msg = { type: 'pair-code' }
|
|
1341
1610
|
if (opts.ttlMs) msg.ttlMs = opts.ttlMs
|
|
1342
|
-
return this._request(msg, 'pair-code')
|
|
1611
|
+
return /** @type {Promise<any>} */ (this._request(msg, 'pair-code'))
|
|
1343
1612
|
}
|
|
1344
1613
|
|
|
1345
1614
|
/**
|
|
@@ -1350,10 +1619,11 @@ export class WebSocketProxyClient {
|
|
|
1350
1619
|
* toda la malla: un pregón se lo queda el primero que conteste, y así es como
|
|
1351
1620
|
* un nodo hostil se mete en emparejamientos ajenos.
|
|
1352
1621
|
*
|
|
1353
|
-
* @
|
|
1622
|
+
* @param {string} code
|
|
1623
|
+
* @returns {Promise<{ ok: boolean, instance?: string, publickey?: string | null, code?: string, error?: string }>}
|
|
1354
1624
|
*/
|
|
1355
1625
|
redeemPairingCode (code) {
|
|
1356
|
-
return this._request({ type: 'pair-redeem', code }, 'pair-redeem')
|
|
1626
|
+
return /** @type {Promise<any>} */ (this._request({ type: 'pair-redeem', code }, 'pair-redeem'))
|
|
1357
1627
|
}
|
|
1358
1628
|
|
|
1359
1629
|
/**
|
|
@@ -1390,8 +1660,11 @@ export class WebSocketProxyClient {
|
|
|
1390
1660
|
*
|
|
1391
1661
|
* `sign` es lo que firma (normalmente `(d) => identity.signData(d)`); acepta tanto la
|
|
1392
1662
|
* firma en texto como el paquete del vault.
|
|
1663
|
+
*
|
|
1664
|
+
* @param {{ publickey: string, sign: (data: any) => Promise<any>, cert?: any, acta?: any }} args
|
|
1665
|
+
* @returns {Promise<{ publickey: string, queued_delivered: number }>}
|
|
1393
1666
|
*/
|
|
1394
|
-
async identifyAs ({ publickey, sign, cert, acta } = {}) {
|
|
1667
|
+
async identifyAs ({ publickey, sign, cert, acta } = /** @type {any} */ ({})) {
|
|
1395
1668
|
if (typeof sign !== 'function') throw new Error('identifyAs requires sign(data)')
|
|
1396
1669
|
if (!publickey) throw new Error('identifyAs requires publickey')
|
|
1397
1670
|
if (!this.token) throw new Error('identifyAs: not connected yet (no token)')
|
|
@@ -1410,21 +1683,26 @@ export class WebSocketProxyClient {
|
|
|
1410
1683
|
return this.identify({ data, signature, cert, acta, sign })
|
|
1411
1684
|
}
|
|
1412
1685
|
|
|
1686
|
+
/**
|
|
1687
|
+
* @param {{ data: any, signature: string, cert?: any, acta?: any, sign?: (data: any) => Promise<any> }} envelope
|
|
1688
|
+
* @returns {Promise<{ publickey: string, queued_delivered: number }>}
|
|
1689
|
+
*/
|
|
1413
1690
|
identify ({ data, signature, cert, acta, sign }) {
|
|
1414
1691
|
if (!data || !signature) throw new Error('identify requires {data, signature}')
|
|
1692
|
+
/** @type {Frame} */
|
|
1415
1693
|
const msg = { type: 'identify', data, signature }
|
|
1416
1694
|
if (this.app) msg.app = this.app
|
|
1417
1695
|
if (cert) msg.cert = cert // "una identidad": el proxy bindea este token también bajo tu maestra M
|
|
1418
1696
|
// Acta de perfil: el proxy la verifica (va firmada) y bindea también el `profileId`, así
|
|
1419
1697
|
// escribirle a la PERSONA llega a cualquiera de sus dispositivos. Ver acta-de-perfil.md.
|
|
1420
1698
|
if (acta) msg.acta = acta
|
|
1421
|
-
const done = this._request(msg, 'identified')
|
|
1699
|
+
const done = /** @type {Promise<{ publickey: string, queued_delivered: number }>} */ (this._request(msg, 'identified'))
|
|
1422
1700
|
// Mi identidad en el cable, para poder decirla en el saludo sin que la app la
|
|
1423
1701
|
// repita. Se apunta al pedirlo y no al confirmarlo: si la identificación falla,
|
|
1424
1702
|
// el saludo tampoco sale (el proxio no reparte a una conexión sin identidad).
|
|
1425
1703
|
this.myPublickey = data.publickey
|
|
1426
1704
|
if (this._rtc && typeof sign === 'function' && data.publickey) {
|
|
1427
|
-
done.then(() => this.enableTurn({ publicKey: data.publickey, sign })).catch(() => {})
|
|
1705
|
+
done.then(() => this.enableTurn({ publicKey: data.publickey, sign: /** @type {SignFn} */ (sign) })).catch(() => {})
|
|
1428
1706
|
}
|
|
1429
1707
|
// ANUNCIAR LA LLAVE DE CIFRADO, y por detrás. Identificarse es lo que da dirección a
|
|
1430
1708
|
// esta identidad; anunciar su llave es lo que hace que alguien pueda sellarle sin
|
|
@@ -1433,12 +1711,12 @@ export class WebSocketProxyClient {
|
|
|
1433
1711
|
// quiera escribirnos.
|
|
1434
1712
|
if (typeof sign === 'function' && data.publickey && this.myEncPub) {
|
|
1435
1713
|
done
|
|
1436
|
-
.then(() => this.announceEncPub({ publickey: data.publickey, encPub: this.myEncPub, sign }))
|
|
1714
|
+
.then(() => this.announceEncPub({ publickey: data.publickey, encPub: /** @type {string} */ (this.myEncPub), sign: /** @type {SignFn} */ (sign) }))
|
|
1437
1715
|
.catch((e) => {
|
|
1438
1716
|
// Se dice en voz alta: sin anuncio nadie podrá sellarnos, y el síntoma llega
|
|
1439
1717
|
// días después y del otro lado («no puedo escribirte»). Callarlo es justo el
|
|
1440
1718
|
// fallo mudo que el ecosistema paga caro.
|
|
1441
|
-
this._emit('error', { type: 'encpub_announce_failed', error: e, code: e
|
|
1719
|
+
this._emit('error', { type: 'encpub_announce_failed', error: e, code: codeOf(e) })
|
|
1442
1720
|
})
|
|
1443
1721
|
}
|
|
1444
1722
|
return done
|
|
@@ -1451,12 +1729,10 @@ export class WebSocketProxyClient {
|
|
|
1451
1729
|
* usa solo desde apps Dotrino y no como relay abierto). Las credenciales
|
|
1452
1730
|
* expiran solas (TTL corto) y hay cuota por pubkey/hora.
|
|
1453
1731
|
*
|
|
1454
|
-
* @param {
|
|
1455
|
-
* @
|
|
1456
|
-
* @param {(data:any)=>Promise<string|{signature:string}>} opts.sign Firma del vault (id.signData).
|
|
1457
|
-
* @returns {Promise<{enabled:boolean, iceServers:any[]|null, expiresAt:number|null}>}
|
|
1732
|
+
* @param {import('./index.js').TurnCredentialsOptions} opts
|
|
1733
|
+
* @returns {Promise<import('./index.js').TurnCredentials>}
|
|
1458
1734
|
*/
|
|
1459
|
-
async getTurnCredentials ({ publicKey, sign } = {}) {
|
|
1735
|
+
async getTurnCredentials ({ publicKey, sign } = /** @type {any} */ ({})) {
|
|
1460
1736
|
if (!publicKey || typeof sign !== 'function') {
|
|
1461
1737
|
throw new Error('getTurnCredentials requires { publicKey, sign }')
|
|
1462
1738
|
}
|
|
@@ -1479,10 +1755,10 @@ export class WebSocketProxyClient {
|
|
|
1479
1755
|
* Afecta a las conexiones P2P NUEVAS (los peers ya negociados conservan su
|
|
1480
1756
|
* configuración). Llamalo después de `identify`.
|
|
1481
1757
|
*
|
|
1482
|
-
* @param {
|
|
1758
|
+
* @param {import('./index.js').TurnCredentialsOptions} opts Igual que getTurnCredentials ({ publicKey, sign }).
|
|
1483
1759
|
* @returns {Promise<boolean>} true si TURN quedó activo.
|
|
1484
1760
|
*/
|
|
1485
|
-
async enableTurn ({ publicKey, sign } = {}) {
|
|
1761
|
+
async enableTurn ({ publicKey, sign } = /** @type {any} */ ({})) {
|
|
1486
1762
|
if (!this._rtc) throw new Error('WebRTC is disabled in this client')
|
|
1487
1763
|
if (this._turnTimer) {
|
|
1488
1764
|
clearTimeout(this._turnTimer)
|
|
@@ -1491,8 +1767,9 @@ export class WebSocketProxyClient {
|
|
|
1491
1767
|
let res
|
|
1492
1768
|
try {
|
|
1493
1769
|
res = await this.getTurnCredentials({ publicKey, sign })
|
|
1494
|
-
} catch (
|
|
1495
|
-
|
|
1770
|
+
} catch (err) {
|
|
1771
|
+
const e = /** @type {{ status?: number, retryAfterMs?: number, code?: string } | null | undefined} */ (err)
|
|
1772
|
+
if (e?.status !== 429) throw err
|
|
1496
1773
|
// 429: EL PROXIO DICE «AHORA NO» (tope diario de tráfico, cuota por hora, o no puede
|
|
1497
1774
|
// leer el consumo). No es un fallo: se sigue por el proxio, que es el escalón que
|
|
1498
1775
|
// siempre funciona. Se quita el relevo que hubiera (sus credenciales ya no se
|
|
@@ -1500,9 +1777,9 @@ export class WebSocketProxyClient {
|
|
|
1500
1777
|
// proxio dice que se puede — si no, un aparato que pasó por un día con el tope
|
|
1501
1778
|
// alcanzado se quedaría sin relevo hasta su siguiente reconexión.
|
|
1502
1779
|
this._rtc.setIceServers(DEFAULT_ICE_SERVERS)
|
|
1503
|
-
const retryAfterMs = Math.max(60000, Number(e
|
|
1504
|
-
this._turn = { active: false, code: e
|
|
1505
|
-
this._emit('turn_unavailable', { code: e
|
|
1780
|
+
const retryAfterMs = Math.max(60000, Number(e?.retryAfterMs) || 0)
|
|
1781
|
+
this._turn = { active: false, code: e?.code || null, retryAt: Date.now() + retryAfterMs }
|
|
1782
|
+
this._emit('turn_unavailable', { code: e?.code || null, retryAfterMs })
|
|
1506
1783
|
this._turnTimer = setTimeout(() => {
|
|
1507
1784
|
this._turnTimer = null
|
|
1508
1785
|
this.enableTurn({ publicKey, sign }).catch(() => {})
|
|
@@ -1535,7 +1812,7 @@ export class WebSocketProxyClient {
|
|
|
1535
1812
|
|
|
1536
1813
|
/**
|
|
1537
1814
|
* Consultar la config de Web Push del proxy.
|
|
1538
|
-
* @returns {Promise<
|
|
1815
|
+
* @returns {Promise<import('./index.js').PushConfig>}
|
|
1539
1816
|
*/
|
|
1540
1817
|
async getPushConfig () {
|
|
1541
1818
|
const res = await this._request({ type: 'push-config' }, 'push-config')
|
|
@@ -1559,16 +1836,10 @@ export class WebSocketProxyClient {
|
|
|
1559
1836
|
* vite-plugin-pwa/Workbox): inyectá los handlers de push en ese SW con
|
|
1560
1837
|
* `importScripts` y llamá enablePush() sin swPath para no clobbear el scope.
|
|
1561
1838
|
*
|
|
1562
|
-
* @param {
|
|
1563
|
-
* @param {string} opts.publicKey Pubkey JWK string del vault (la de identify).
|
|
1564
|
-
* @param {(data:any)=>Promise<string|{signature:string}>} opts.sign Firma del vault (id.signData).
|
|
1565
|
-
* @param {string} [opts.vapidPublicKey] VAPID pública; si falta se pide al proxy.
|
|
1566
|
-
* @param {ServiceWorkerRegistration} [opts.registration] SW ya registrado a reutilizar.
|
|
1567
|
-
* @param {string} [opts.swPath] Ruta de un SW a registrar (apps sin SW propio).
|
|
1568
|
-
* @param {string} [opts.swScope] Scope del SW (solo con swPath).
|
|
1839
|
+
* @param {import('./index.js').EnablePushOptions} opts
|
|
1569
1840
|
* @returns {Promise<PushSubscription>}
|
|
1570
1841
|
*/
|
|
1571
|
-
async enablePush ({ publicKey, sign, vapidPublicKey, registration, swPath, swScope } = {}) {
|
|
1842
|
+
async enablePush ({ publicKey, sign, vapidPublicKey, registration, swPath, swScope } = /** @type {any} */ ({})) {
|
|
1572
1843
|
if (typeof navigator === 'undefined' || !('serviceWorker' in navigator)) {
|
|
1573
1844
|
throw new Error('Service Worker is not supported in this environment')
|
|
1574
1845
|
}
|
|
@@ -1611,9 +1882,10 @@ export class WebSocketProxyClient {
|
|
|
1611
1882
|
* Registrar el TOKEN DE PUSH de una app nativa (FCM en Android; APNs más adelante) bajo
|
|
1612
1883
|
* esta pubkey, en vez de una PushSubscription del navegador. El proxy lo usa para el
|
|
1613
1884
|
* mismo timbre sin contenido. Firma del vault, igual que enablePush.
|
|
1614
|
-
* @param {{ publicKey:string, sign:
|
|
1885
|
+
* @param {{ publicKey:string, sign:SignFn, token:string, kind?:'fcm' }} opts
|
|
1886
|
+
* @returns {Promise<{ kind: 'fcm', token: string }>}
|
|
1615
1887
|
*/
|
|
1616
|
-
async registerPushToken ({ publicKey, sign, token, kind = 'fcm' } = {}) {
|
|
1888
|
+
async registerPushToken ({ publicKey, sign, token, kind = 'fcm' } = /** @type {any} */ ({})) {
|
|
1617
1889
|
if (!publicKey || typeof sign !== 'function' || !token) throw new Error('registerPushToken requires { publicKey, sign, token }')
|
|
1618
1890
|
const data = { op: 'push-subscribe', publickey: publicKey, subscription: JSON.stringify({ kind, token }), ts: Date.now(), ...this._appField() }
|
|
1619
1891
|
const signature = await normalizeSignature(sign, data)
|
|
@@ -1639,9 +1911,10 @@ export class WebSocketProxyClient {
|
|
|
1639
1911
|
* escribe un servicio cuando la bóveda no contesta. Un proxio que no anuncia `wake-self` lo
|
|
1640
1912
|
* guardaría para la cuenta y le quitaría el timbre a la bóveda, así que ahí no se manda.
|
|
1641
1913
|
*
|
|
1642
|
-
* @param {{ publicKey:string, sign:
|
|
1914
|
+
* @param {{ publicKey:string, sign:SignFn, url:string, acta:object, channel?:string, self?:boolean }} opts
|
|
1915
|
+
* @returns {Promise<{ kind: 'wake', url: string, profile: string | null }>}
|
|
1643
1916
|
*/
|
|
1644
|
-
async registerWake ({ publicKey, sign, url, acta, channel, self = false } = {}) {
|
|
1917
|
+
async registerWake ({ publicKey, sign, url, acta, channel, self = false } = /** @type {any} */ ({})) {
|
|
1645
1918
|
if (!publicKey || typeof sign !== 'function' || !url || !acta) throw errorWithCode('registerWake requires { publicKey, sign, url, acta }', 'bad-args')
|
|
1646
1919
|
if (self && channel) throw errorWithCode('registerWake: a self wake has no channel', 'bad-args')
|
|
1647
1920
|
if (self && !(Array.isArray(this.caps) && this.caps.includes('wake-self'))) throw errorWithCode('registerWake: this proxy does not support a wake for the device key (needs websocket-proxy >= 1.8.0)', 'no-wake-self-support')
|
|
@@ -1653,13 +1926,9 @@ export class WebSocketProxyClient {
|
|
|
1653
1926
|
|
|
1654
1927
|
/**
|
|
1655
1928
|
* Desactivar Web Push: cancela la PushSubscription local y la borra del proxy.
|
|
1656
|
-
* @param {
|
|
1657
|
-
* @param {string} opts.publicKey Pubkey JWK string del vault.
|
|
1658
|
-
* @param {(data:any)=>Promise<string|{signature:string}>} opts.sign Firma del vault.
|
|
1659
|
-
* @param {ServiceWorkerRegistration} [opts.registration] SW a usar (default: el activo).
|
|
1660
|
-
* @param {string} [opts.swPath] Ruta del SW si se registró uno propio.
|
|
1929
|
+
* @param {import('./index.js').DisablePushOptions} opts
|
|
1661
1930
|
*/
|
|
1662
|
-
async disablePush ({ publicKey, sign, registration, swPath } = {}) {
|
|
1931
|
+
async disablePush ({ publicKey, sign, registration, swPath } = /** @type {any} */ ({})) {
|
|
1663
1932
|
if (typeof navigator !== 'undefined' && 'serviceWorker' in navigator) {
|
|
1664
1933
|
try {
|
|
1665
1934
|
const reg = registration ||
|
|
@@ -1682,17 +1951,12 @@ export class WebSocketProxyClient {
|
|
|
1682
1951
|
* self-only: el target es siempre la pubkey que firma (no se puede programar
|
|
1683
1952
|
* a terceros). One-shot (`when`) o recurrente (`cron` + `tz`).
|
|
1684
1953
|
*
|
|
1685
|
-
* @param {
|
|
1686
|
-
* @param {string} opts.publicKey Pubkey JWK string del vault.
|
|
1687
|
-
* @param {(data:any)=>Promise<string|{signature:string}>} opts.sign Firma del vault.
|
|
1688
|
-
* @param {Date|number} [opts.when] One-shot: instante futuro (Date o epoch ms).
|
|
1689
|
-
* @param {string} [opts.cron] Recurrente: expresión cron (5 campos).
|
|
1690
|
-
* @param {string} [opts.tz] Timezone IANA para el cron (ej. 'America/Argentina/Buenos_Aires').
|
|
1691
|
-
* @param {object} [opts.payload] Datos extra opcionales para la notificación (ej. { title }).
|
|
1954
|
+
* @param {import('./index.js').SchedulePushOptions} opts
|
|
1692
1955
|
* @returns {Promise<{ jobId:number, nextFire:number }>}
|
|
1693
1956
|
*/
|
|
1694
|
-
async schedulePush ({ publicKey, sign, when, cron, tz, payload } = {}) {
|
|
1957
|
+
async schedulePush ({ publicKey, sign, when, cron, tz, payload } = /** @type {any} */ ({})) {
|
|
1695
1958
|
if (!publicKey || typeof sign !== 'function') throw new Error('schedulePush requires { publicKey, sign }')
|
|
1959
|
+
/** @type {{ cron?: string, tz?: string, fireAt?: number, payload?: object }} */
|
|
1696
1960
|
const spec = {}
|
|
1697
1961
|
if (cron) {
|
|
1698
1962
|
spec.cron = cron
|
|
@@ -1713,12 +1977,9 @@ export class WebSocketProxyClient {
|
|
|
1713
1977
|
|
|
1714
1978
|
/**
|
|
1715
1979
|
* Cancelar un push programado propio.
|
|
1716
|
-
* @param {
|
|
1717
|
-
* @param {string} opts.publicKey
|
|
1718
|
-
* @param {(data:any)=>Promise<string|{signature:string}>} opts.sign
|
|
1719
|
-
* @param {number} opts.jobId
|
|
1980
|
+
* @param {{ publicKey: string, sign: SignFn, jobId: number }} opts
|
|
1720
1981
|
*/
|
|
1721
|
-
async cancelScheduledPush ({ publicKey, sign, jobId } = {}) {
|
|
1982
|
+
async cancelScheduledPush ({ publicKey, sign, jobId } = /** @type {any} */ ({})) {
|
|
1722
1983
|
if (!publicKey || typeof sign !== 'function') throw new Error('cancelScheduledPush requires { publicKey, sign }')
|
|
1723
1984
|
const data = { op: 'cancel-push', publickey: publicKey, jobId, ts: Date.now() }
|
|
1724
1985
|
const signature = await normalizeSignature(sign, data)
|
|
@@ -1728,9 +1989,10 @@ export class WebSocketProxyClient {
|
|
|
1728
1989
|
|
|
1729
1990
|
/**
|
|
1730
1991
|
* Listar los push programados propios.
|
|
1731
|
-
* @
|
|
1992
|
+
* @param {{ publicKey: string, sign: SignFn }} opts
|
|
1993
|
+
* @returns {Promise<import('./index.js').ScheduledPush[]>}
|
|
1732
1994
|
*/
|
|
1733
|
-
async listScheduledPushes ({ publicKey, sign } = {}) {
|
|
1995
|
+
async listScheduledPushes ({ publicKey, sign } = /** @type {any} */ ({})) {
|
|
1734
1996
|
if (!publicKey || typeof sign !== 'function') throw new Error('listScheduledPushes requires { publicKey, sign }')
|
|
1735
1997
|
const data = { op: 'list-pushes', publickey: publicKey, ts: Date.now() }
|
|
1736
1998
|
const signature = await normalizeSignature(sign, data)
|
|
@@ -1738,7 +2000,11 @@ export class WebSocketProxyClient {
|
|
|
1738
2000
|
return res.jobs || []
|
|
1739
2001
|
}
|
|
1740
2002
|
|
|
1741
|
-
/**
|
|
2003
|
+
/**
|
|
2004
|
+
* Tear down the logical pair with a peer (both sides get notified).
|
|
2005
|
+
* @param {string} targetToken
|
|
2006
|
+
* @returns {Promise<Frame>}
|
|
2007
|
+
*/
|
|
1742
2008
|
async disconnectFrom (targetToken) {
|
|
1743
2009
|
return this._request(
|
|
1744
2010
|
{ type: 'disconnect', target: targetToken },
|
|
@@ -1746,12 +2012,19 @@ export class WebSocketProxyClient {
|
|
|
1746
2012
|
)
|
|
1747
2013
|
}
|
|
1748
2014
|
|
|
1749
|
-
/**
|
|
2015
|
+
/**
|
|
2016
|
+
* Public key in JWK string form, useful as a stable identity.
|
|
2017
|
+
* @returns {Promise<string>}
|
|
2018
|
+
*/
|
|
1750
2019
|
getPublicKey () {
|
|
1751
2020
|
return getPublicKeyJwk()
|
|
1752
2021
|
}
|
|
1753
2022
|
|
|
1754
|
-
/**
|
|
2023
|
+
/**
|
|
2024
|
+
* Sign arbitrary data with the local private key (base64 signature).
|
|
2025
|
+
* @param {any} data
|
|
2026
|
+
* @returns {Promise<string>}
|
|
2027
|
+
*/
|
|
1755
2028
|
sign (data) {
|
|
1756
2029
|
return signData(data)
|
|
1757
2030
|
}
|
|
@@ -1834,6 +2107,7 @@ export class WebSocketProxyClient {
|
|
|
1834
2107
|
}
|
|
1835
2108
|
|
|
1836
2109
|
// El intento no abrió ni falló a tiempo: se suelta y se trata como un cierre fallido.
|
|
2110
|
+
/** @param {WebSocket} ws */
|
|
1837
2111
|
_onConnectTimeout (ws) {
|
|
1838
2112
|
if (ws !== this.ws || this._connected) return
|
|
1839
2113
|
this.ws = null // a partir de acá, los eventos tardíos de `ws` se ignoran
|
|
@@ -1911,13 +2185,16 @@ export class WebSocketProxyClient {
|
|
|
1911
2185
|
// Con los valores por defecto: 3–6 s, 3–9 s, 3–15 s, 3–27 s y de ahí 3–33 s. El mínimo
|
|
1912
2186
|
// fijo es para el caso normal (una caída corta de la red), que vuelve enseguida; el azar
|
|
1913
2187
|
// reparte a los que se cayeron juntos.
|
|
2188
|
+
/** @param {number} attempt @returns {number} */
|
|
1914
2189
|
_reconnectWait (attempt) {
|
|
1915
2190
|
const base = Math.max(0, this.reconnectDelay)
|
|
1916
2191
|
const window = Math.min(Math.max(0, this.reconnectMaxDelay), base * 2 ** Math.max(0, attempt - 1))
|
|
1917
2192
|
return base + Math.random() * window
|
|
1918
2193
|
}
|
|
1919
2194
|
|
|
2195
|
+
/** @param {string | ArrayBuffer | Uint8Array} raw */
|
|
1920
2196
|
_handleFrame (raw) {
|
|
2197
|
+
/** @type {Frame} */
|
|
1921
2198
|
let data
|
|
1922
2199
|
if (typeof raw === 'string') {
|
|
1923
2200
|
try { data = JSON.parse(raw) } catch (e) {
|
|
@@ -1930,7 +2207,7 @@ export class WebSocketProxyClient {
|
|
|
1930
2207
|
const { header, body } = decodeFrame(raw)
|
|
1931
2208
|
data = { ...header, message: body }
|
|
1932
2209
|
} catch (e) {
|
|
1933
|
-
this._emit('error', { type: 'parse_error', code: e
|
|
2210
|
+
this._emit('error', { type: 'parse_error', code: codeOf(e) || 'bad-frame', error: e })
|
|
1934
2211
|
return
|
|
1935
2212
|
}
|
|
1936
2213
|
}
|
|
@@ -1947,7 +2224,8 @@ export class WebSocketProxyClient {
|
|
|
1947
2224
|
// son de TODO el ecosistema y no tienen dueño natural (la lista pública
|
|
1948
2225
|
// de salas): se pregunta en cada nodo y se mezcla, en vez de designar a
|
|
1949
2226
|
// uno como árbitro. Son públicos: van en cada instancia y en /peers.
|
|
1950
|
-
|
|
2227
|
+
const peers = Array.isArray(data.peers) ? data.peers : []
|
|
2228
|
+
this.peers = peers
|
|
1951
2229
|
// QUÉ SABE HACER ESTE PROXIO, dicho por él al conectar (§14: una incompatibilidad
|
|
1952
2230
|
// que no se anuncia se vive como silencio). `caps` ausente = proxio anterior a que
|
|
1953
2231
|
// esto existiera: no se da por hecho nada, se pregunta igual y contesta la
|
|
@@ -1955,11 +2233,11 @@ export class WebSocketProxyClient {
|
|
|
1955
2233
|
this.protocol = Number.isInteger(data.protocol) ? data.protocol : null
|
|
1956
2234
|
this.caps = Array.isArray(data.caps) ? data.caps : null
|
|
1957
2235
|
/** Este nodo + los que conoce, sin repetidos. */
|
|
1958
|
-
this.knownNodes = [this.node, ...
|
|
1959
|
-
this.token = this.instance
|
|
2236
|
+
this.knownNodes = /** @type {string[]} */ ([this.node, ...peers].filter((n, i, a) => n && a.indexOf(n) === i))
|
|
2237
|
+
this.token = /** @type {string} */ (this.instance)
|
|
1960
2238
|
this._emit('token', this.token)
|
|
1961
2239
|
if (this._connectResolve) {
|
|
1962
|
-
this._connectResolve(this.token)
|
|
2240
|
+
this._connectResolve(/** @type {string} */ (this.token))
|
|
1963
2241
|
this._connectResolve = null
|
|
1964
2242
|
this._connectReject = null
|
|
1965
2243
|
}
|
|
@@ -2069,6 +2347,7 @@ export class WebSocketProxyClient {
|
|
|
2069
2347
|
}
|
|
2070
2348
|
}
|
|
2071
2349
|
|
|
2350
|
+
/** @param {Frame} frame */
|
|
2072
2351
|
_sendRaw (frame) {
|
|
2073
2352
|
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
2074
2353
|
throw errorWithCode('WebSocket not connected', 'NOT_CONNECTED')
|
|
@@ -2086,7 +2365,11 @@ export class WebSocketProxyClient {
|
|
|
2086
2365
|
this._countOut(frame, text)
|
|
2087
2366
|
}
|
|
2088
2367
|
|
|
2089
|
-
/**
|
|
2368
|
+
/**
|
|
2369
|
+
* Cuenta un frame que sale por el proxio, y a quién iba.
|
|
2370
|
+
* @param {Frame} frame
|
|
2371
|
+
* @param {string | Uint8Array} text
|
|
2372
|
+
*/
|
|
2090
2373
|
_countOut (frame, text) {
|
|
2091
2374
|
this._traffic.frame('out', utf8Length(text))
|
|
2092
2375
|
if (typeof frame.message !== 'string' && !(frame.message instanceof Uint8Array)) return
|
|
@@ -2109,6 +2392,8 @@ export class WebSocketProxyClient {
|
|
|
2109
2392
|
*
|
|
2110
2393
|
* Los bytes son de payload (UTF-8), no del cable: las cabeceras de TLS/DTLS no se ven
|
|
2111
2394
|
* desde aquí.
|
|
2395
|
+
*
|
|
2396
|
+
* @returns {Promise<TransportStats>}
|
|
2112
2397
|
*/
|
|
2113
2398
|
async stats () {
|
|
2114
2399
|
const t = this._traffic
|
|
@@ -2152,8 +2437,14 @@ export class WebSocketProxyClient {
|
|
|
2152
2437
|
}
|
|
2153
2438
|
}
|
|
2154
2439
|
|
|
2440
|
+
/**
|
|
2441
|
+
* @param {Frame} frame
|
|
2442
|
+
* @param {string} expectedType
|
|
2443
|
+
* @param {string} [channelKey]
|
|
2444
|
+
* @returns {Promise<Frame>}
|
|
2445
|
+
*/
|
|
2155
2446
|
_request (frame, expectedType, channelKey) {
|
|
2156
|
-
return new Promise((resolve, reject) => {
|
|
2447
|
+
return new Promise(/** @param {(data: Frame) => void} resolve @param {(e: unknown) => void} reject */ (resolve, reject) => {
|
|
2157
2448
|
const id = `req_${this._nextId++}`
|
|
2158
2449
|
const out = { ...frame, id }
|
|
2159
2450
|
const timer = setTimeout(() => {
|
|
@@ -2171,31 +2462,34 @@ export class WebSocketProxyClient {
|
|
|
2171
2462
|
})
|
|
2172
2463
|
}
|
|
2173
2464
|
|
|
2465
|
+
/** @param {Frame} data @param {string} actualType */
|
|
2174
2466
|
_resolvePending (data, actualType) {
|
|
2175
2467
|
const id = data.id
|
|
2176
|
-
|
|
2177
|
-
|
|
2468
|
+
const entry = id ? this._pending.get(id) : undefined
|
|
2469
|
+
if (!id || !entry) return
|
|
2178
2470
|
if (entry.expectedType && entry.expectedType !== actualType) return
|
|
2179
2471
|
clearTimeout(entry.timer)
|
|
2180
2472
|
this._pending.delete(id)
|
|
2181
2473
|
entry.resolve(data)
|
|
2182
2474
|
}
|
|
2183
2475
|
|
|
2476
|
+
/** @param {Frame} data */
|
|
2184
2477
|
_rejectPending (data) {
|
|
2185
2478
|
const id = data.id
|
|
2186
|
-
|
|
2187
|
-
|
|
2479
|
+
const entry = id ? this._pending.get(id) : undefined
|
|
2480
|
+
if (!id || !entry) return
|
|
2188
2481
|
clearTimeout(entry.timer)
|
|
2189
2482
|
this._pending.delete(id)
|
|
2190
2483
|
// Con su `code`: quien llama distingue los casos por él, no por la frase (que el proxio
|
|
2191
2484
|
// puede cambiar o traducir). Antes se perdía aquí y solo quedaba comparar el texto.
|
|
2192
|
-
const e = errorWithCode(data.error || 'Server error', data.code || null)
|
|
2485
|
+
const e = /** @type {Error & { code: string, status?: number, retryAfterMs?: number }} */ (errorWithCode(data.error || 'Server error', data.code || null))
|
|
2193
2486
|
// «Ahora no» (429) y cuánto esperar, cuando el proxio lo dice.
|
|
2194
2487
|
if (data.status) e.status = data.status
|
|
2195
2488
|
if (data.retry_after_ms) e.retryAfterMs = data.retry_after_ms
|
|
2196
2489
|
entry.reject(e)
|
|
2197
2490
|
}
|
|
2198
2491
|
|
|
2492
|
+
/** @param {string} event @param {...any} args */
|
|
2199
2493
|
_emit (event, ...args) {
|
|
2200
2494
|
const set = this._handlers.get(event)
|
|
2201
2495
|
if (!set) return
|
|
@@ -2207,6 +2501,11 @@ export class WebSocketProxyClient {
|
|
|
2207
2501
|
|
|
2208
2502
|
// El callback de firma del vault devuelve `string` o `{ signature }` (id.signData
|
|
2209
2503
|
// devuelve un objeto). Normalizamos a string base64.
|
|
2504
|
+
/**
|
|
2505
|
+
* @param {SignFn} sign
|
|
2506
|
+
* @param {any} data
|
|
2507
|
+
* @returns {Promise<string>}
|
|
2508
|
+
*/
|
|
2210
2509
|
async function normalizeSignature (sign, data) {
|
|
2211
2510
|
const out = await sign(data)
|
|
2212
2511
|
const sig = typeof out === 'string' ? out : (out && out.signature)
|
|
@@ -2216,6 +2515,7 @@ async function normalizeSignature (sign, data) {
|
|
|
2216
2515
|
|
|
2217
2516
|
// Convierte la VAPID pública (base64url) al Uint8Array que espera
|
|
2218
2517
|
// pushManager.subscribe({ applicationServerKey }).
|
|
2518
|
+
/** @param {string} base64String @returns {Uint8Array<ArrayBuffer>} */
|
|
2219
2519
|
function urlBase64ToUint8Array (base64String) {
|
|
2220
2520
|
const padding = '='.repeat((4 - (base64String.length % 4)) % 4)
|
|
2221
2521
|
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/')
|
|
@@ -2224,3 +2524,12 @@ function urlBase64ToUint8Array (base64String) {
|
|
|
2224
2524
|
for (let i = 0; i < raw.length; i++) output[i] = raw.charCodeAt(i)
|
|
2225
2525
|
return output
|
|
2226
2526
|
}
|
|
2527
|
+
|
|
2528
|
+
/**
|
|
2529
|
+
* El `code` de un error, si lo trae (es el contrato, no la frase). `null` si no.
|
|
2530
|
+
* @param {unknown} e
|
|
2531
|
+
* @returns {string | null}
|
|
2532
|
+
*/
|
|
2533
|
+
function codeOf (e) {
|
|
2534
|
+
return /** @type {{ code?: string } | null | undefined} */ (e)?.code || null
|
|
2535
|
+
}
|