@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
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* LO QUE LA BÓVEDA TIENE QUE CONTARLE A QUIEN APRUEBA, y que no es un pedido.
|
|
3
3
|
*
|
|
4
|
-
* Son
|
|
4
|
+
* Son tres. Dos de la bóveda o de uno de sus aparatos: «me actualicé» y «hay versión nueva y
|
|
5
5
|
* necesita permisos de administrador: instálala a mano» (`update-needs-root`). (`ev: 'updated'`, dueño 2026-10-08: «las actualizaciones, que se
|
|
6
6
|
* envíe una notificación de que ocurrieron a los aprobadores»). Sale como aviso por el
|
|
7
7
|
* proxio, pero el timbre de una app nativa llega VACÍO —lo leen Google y Apple—, así que la
|
|
@@ -16,8 +16,15 @@
|
|
|
16
16
|
export const NOTICES_FILE = 'notices.json'
|
|
17
17
|
/** Cuánto se sigue contando un aviso. */
|
|
18
18
|
export const NOTICE_TTL_MS = 24 * 60 * 60 * 1000
|
|
19
|
-
/**
|
|
20
|
-
|
|
19
|
+
/**
|
|
20
|
+
* Los avisos que existen. El tercero, `pairing-contested`, es un INCIDENTE: dos aparatos
|
|
21
|
+
* respondieron a la misma invitación de emparejar y la sesión se canceló
|
|
22
|
+
* (`docs/pairing-protocol.md` §1.7). No pide nada: no hay a quién bloquear, porque ninguno
|
|
23
|
+
* entró. Lo cuenta, con el ID y la máquina de los dos.
|
|
24
|
+
*/
|
|
25
|
+
export const NOTICE_EVS = ['updated', 'update-needs-root', 'pairing-contested']
|
|
26
|
+
|
|
27
|
+
const newId = () => [...crypto.getRandomValues(new Uint8Array(8))].map((b) => b.toString(16).padStart(2, '0')).join('')
|
|
21
28
|
|
|
22
29
|
const fail = (code, message) => Object.assign(new Error(message), { code })
|
|
23
30
|
|
|
@@ -51,12 +58,23 @@ export function openNotices ({ disk, now = Date.now }) {
|
|
|
51
58
|
* administrador). `product`: qué (`@dotrino/vaultd` es la propia bóveda);
|
|
52
59
|
* `deviceId`/`label`: el aparato, si fue uno.
|
|
53
60
|
*/
|
|
54
|
-
add (ev, { version, from = null, product = '@dotrino/vaultd', deviceId = null, label = null }) {
|
|
61
|
+
add (ev, { version, from = null, product = '@dotrino/vaultd', deviceId = null, label = null, devices = null }) {
|
|
55
62
|
if (!NOTICE_EVS.includes(ev)) throw fail('bad-notice', `unknown notice: ${ev}`)
|
|
63
|
+
if (ev === 'pairing-contested') {
|
|
64
|
+
if (!Array.isArray(devices) || devices.length < 2) throw fail('bad-notice', `${ev}: the devices that answered are required`)
|
|
65
|
+
const n = {
|
|
66
|
+
id: newId(), ev,
|
|
67
|
+
devices: devices.slice(0, 8).map((d) => ({ deviceId: String(d?.deviceId || ''), machine: d?.machine || null })),
|
|
68
|
+
ts: now()
|
|
69
|
+
}
|
|
70
|
+
items = [...items.filter(alive), n]
|
|
71
|
+
save()
|
|
72
|
+
return n
|
|
73
|
+
}
|
|
56
74
|
if (typeof version !== 'string' || !version) throw fail('bad-notice', `${ev}: a version is required`)
|
|
57
75
|
if (typeof product !== 'string' || !product) throw fail('bad-notice', `${ev}: a product is required`)
|
|
58
76
|
const n = {
|
|
59
|
-
id:
|
|
77
|
+
id: newId(), ev, product, version, from: typeof from === 'string' ? from : null,
|
|
60
78
|
...(typeof deviceId === 'string' && deviceId ? { deviceId, label: typeof label === 'string' ? label : '' } : {}),
|
|
61
79
|
ts: now()
|
|
62
80
|
}
|
|
@@ -36,7 +36,7 @@ export async function masterPubkeyOf (identity) {
|
|
|
36
36
|
* @param {string} [opts.url] URL del proxy (default wss://proxy.dotrino.com).
|
|
37
37
|
* @returns {Promise<{ client, token:string, identify():Promise<void> }>}
|
|
38
38
|
*/
|
|
39
|
-
export async function createTransport ({ identity, url = DEFAULT_PROXY, commKey = null, log = () => {}, makeClient = null, announce = null, wakeUrl = null, recheckMs = 60_000, patienceMs = 5 * 60_000, reannounceMs = 10 * 60_000 }) {
|
|
39
|
+
export async function createTransport ({ identity, url = DEFAULT_PROXY, commKey = null, log = () => {}, makeClient = null, announce = null, wakeUrl = null, bluetooth = null, recheckMs = 60_000, patienceMs = 5 * 60_000, reannounceMs = 10 * 60_000 }) {
|
|
40
40
|
// Import dinámico DESPUÉS de instalar los globals que el paquete usa.
|
|
41
41
|
// `WebSocketProxyClient` (la clase) y NO el helper `getWebSocketProxyClient`:
|
|
42
42
|
// ese es un SINGLETON de proceso, y con multi-perfil el vault necesita una
|
|
@@ -80,7 +80,10 @@ export async function createTransport ({ identity, url = DEFAULT_PROXY, commKey
|
|
|
80
80
|
}
|
|
81
81
|
const client = makeClient ? makeClient({ url, acceptDirectFrom: inActa }) : new WebSocketProxyClient({
|
|
82
82
|
url, enableWebRTC: true, acceptDirectFrom: inActa, autoReconnect: true,
|
|
83
|
-
maxReconnectAttempts: 100000, reconnectDelay: 4000
|
|
83
|
+
maxReconnectAttempts: 100000, reconnectDelay: 4000,
|
|
84
|
+
// EL BLUETOOTH (proxy-client docs/bluetooth.md) lo decide la plataforma: el binario en
|
|
85
|
+
// Linux sí; la pestaña y la extensión no pueden. Misma puerta que WebRTC (`inActa`).
|
|
86
|
+
...(bluetooth ? { bluetooth } : {})
|
|
84
87
|
})
|
|
85
88
|
|
|
86
89
|
await client.connect()
|
|
@@ -520,7 +520,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
520
520
|
// ninguna llave y solo sabe la dirección `nombre@AB12-CD34-EF56`— pueda encontrar a quien
|
|
521
521
|
// la atiende. Lo construye la pieza compartida, porque quien lo busca es la extensión.
|
|
522
522
|
const { client, identify: reidentify, isIdentified, listen } = await createTransport({
|
|
523
|
-
identity, url: proxyUrl, commKey, log, announce: vaultChannel(fp), makeClient: platform.makeClient || null, wakeUrl: platform.wakeUrl || null
|
|
523
|
+
identity, url: proxyUrl, commKey, log, announce: vaultChannel(fp), makeClient: platform.makeClient || null, wakeUrl: platform.wakeUrl || null,
|
|
524
|
+
bluetooth: platform.bluetooth || null
|
|
524
525
|
})
|
|
525
526
|
|
|
526
527
|
// El registro público de cadenas de selladores: deposita, si hay a dónde, los eslabones
|
|
@@ -878,6 +879,13 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
878
879
|
markRotationDue(sub).catch((e) => log('[vault] could not rotate after the removal:', e.message))
|
|
879
880
|
},
|
|
880
881
|
defaultScope: [SCOPE.READ],
|
|
882
|
+
// EMPAREJAR CERCA (pairing-protocol.md §1.6): la invitación se anuncia por Bluetooth
|
|
883
|
+
// mientras la sesión vive, si este cliente lo tiene. Sin Bluetooth, el QR de siempre.
|
|
884
|
+
announce: (kind, data) => client.bluetoothAvailable ? client.announceBluetooth(kind, data) : null,
|
|
885
|
+
// DOS APARATOS RESPONDIERON (§1.7): la sesión ya se canceló; aquí se cuenta como incidente.
|
|
886
|
+
onContested: ({ devices }) => {
|
|
887
|
+
announcePairingContested(devices).catch((e) => log('[vault] could not tell the approvers about the contested pairing:', e.message))
|
|
888
|
+
},
|
|
881
889
|
onChallenge ({ deviceId, scope, machine }) {
|
|
882
890
|
log(`\n[vault] Un dispositivo quiere conectarse:`)
|
|
883
891
|
log(` deviceId: ${deviceId}`)
|
|
@@ -2178,6 +2186,39 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
2178
2186
|
* marcador hasta que el aviso salió, y tragarlo sería borrarlo sin haber avisado.
|
|
2179
2187
|
* @returns {Promise<{ approvers: number, sent: number, notice: object|null }>}
|
|
2180
2188
|
*/
|
|
2189
|
+
/** Manda un aviso ya apuntado (`notices`) a cada aprobador, sellado. Devuelve a cuántos salió. */
|
|
2190
|
+
async function sendNotice (notice, who, what) {
|
|
2191
|
+
const { id, ev, ts, ...rest } = notice
|
|
2192
|
+
const body = { ev, id, ...rest, ts }
|
|
2193
|
+
const seal = await sealOrFail(body)
|
|
2194
|
+
let sent = 0
|
|
2195
|
+
for (const pub of who) {
|
|
2196
|
+
try { client.sendByPubkey(pub, { type: MSG.ADMIN_EVENT, body, seal }, { app: 'vault' }); sent++ }
|
|
2197
|
+
catch (e) { log(`[vault] could not tell ${pub.slice(0, 24)}… about ${what}: ${e.message}`) }
|
|
2198
|
+
}
|
|
2199
|
+
return sent
|
|
2200
|
+
}
|
|
2201
|
+
|
|
2202
|
+
/**
|
|
2203
|
+
* UN INCIDENTE DE EMPAREJAMIENTO (pairing-protocol.md §1.7): dos aparatos respondieron a la
|
|
2204
|
+
* misma invitación y la sesión ya se canceló. Se cuenta a quien aprueba como aviso
|
|
2205
|
+
* (`pairing-contested`): no hay nada que aprobar ni a quién bloquear, porque nadie entró.
|
|
2206
|
+
* Sin aprobadores queda en la bitácora (ya lo apuntó el mostrador) y se dice en el log.
|
|
2207
|
+
*/
|
|
2208
|
+
async function announcePairingContested (devices) {
|
|
2209
|
+
const record = await refreshActa()
|
|
2210
|
+
const who = (record?.members || []).filter((m) => Acta.memberCan(record, m.pub, 'approve')).map((m) => m.pub)
|
|
2211
|
+
if (!who.length) {
|
|
2212
|
+
log('[vault] contested pairing: nobody can approve, so nobody is told (grant it with: dotrino-vault caps <ID> +aprueba)')
|
|
2213
|
+
return { approvers: 0, sent: 0 }
|
|
2214
|
+
}
|
|
2215
|
+
const notice = notices.add('pairing-contested', { devices })
|
|
2216
|
+
const sent = await sendNotice(notice, who, 'the contested pairing')
|
|
2217
|
+
log(`[vault] contested pairing: told ${sent} of ${who.length} approver(s)`)
|
|
2218
|
+
if (!sent) throw Object.assign(new Error('no approver could be told'), { code: 'announce-failed' })
|
|
2219
|
+
return { approvers: who.length, sent }
|
|
2220
|
+
}
|
|
2221
|
+
|
|
2181
2222
|
async function announceUpdate ({ version, from = null, product = '@dotrino/vaultd', deviceId = null, label = null, ev = 'updated' }) {
|
|
2182
2223
|
const record = await refreshActa()
|
|
2183
2224
|
const who = (record?.members || []).filter((m) => Acta.memberCan(record, m.pub, 'approve')).map((m) => m.pub)
|
|
@@ -2185,14 +2226,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
2185
2226
|
// `deviceId`/`label`: solo cuando quien se actualizó es un APARATO (`update-done`). El
|
|
2186
2227
|
// aviso de la propia bóveda no los lleva.
|
|
2187
2228
|
const notice = notices.add(ev, { version, from, product, ...(deviceId ? { deviceId, label: label || '' } : {}) })
|
|
2188
|
-
const
|
|
2189
|
-
const body = { ev, id, ...rest, ts }
|
|
2190
|
-
const seal = await sealOrFail(body)
|
|
2191
|
-
let sent = 0
|
|
2192
|
-
for (const pub of who) {
|
|
2193
|
-
try { client.sendByPubkey(pub, { type: MSG.ADMIN_EVENT, body, seal }, { app: 'vault' }); sent++ }
|
|
2194
|
-
catch (e) { log(`[vault] could not tell ${pub.slice(0, 24)}… about the update of ${product} to ${version}: ${e.message}`) }
|
|
2195
|
-
}
|
|
2229
|
+
const sent = await sendNotice(notice, who, `the update of ${product} to ${version}`)
|
|
2196
2230
|
audit(ev === 'updated' ? 'update.announced' : 'update.needs-root', { product, version, from: notice.from, device: deviceId, approvers: who.length, sent })
|
|
2197
2231
|
log(`[vault] update: told ${sent} of ${who.length} approver(s) that ${deviceId ? `${deviceId} (${product})` : 'this vault'} ${ev === 'updated' ? 'now runs' : 'needs administrator rights to install'} ${version}`)
|
|
2198
2232
|
if (!sent) throw Object.assign(new Error('no approver could be told'), { code: 'announce-failed' })
|
|
@@ -32,6 +32,7 @@
|
|
|
32
32
|
import { verifyDeviceSig, pubkeyId, commitCode } from '@dotrino/identity/capabilities'
|
|
33
33
|
import { verifyContinuity, canSeal, DEVICE_CAPS, VAULT_CN } from '@dotrino/identity/acta'
|
|
34
34
|
import { cleanMachine } from '@dotrino/identity/machine'
|
|
35
|
+
import { encodeInvite } from './invite.js'
|
|
35
36
|
|
|
36
37
|
/** Un token de emparejamiento vale 5 min. */
|
|
37
38
|
export const PAIRING_TTL_MS = 5 * 60 * 1000
|
|
@@ -132,7 +133,13 @@ export function createEnrollDesk ({
|
|
|
132
133
|
encPub = null, vaultLabel = '',
|
|
133
134
|
// Token de CONEXIÓN de esta bóveda en el proxy (4 chars): su dirección. Es lo
|
|
134
135
|
// único que necesita el QR corto para que el aparato le hable punto a punto.
|
|
135
|
-
connToken = null
|
|
136
|
+
connToken = null,
|
|
137
|
+
// ANUNCIAR LA INVITACIÓN cerca (pairing-protocol.md §1.6): `(kind, data) => stop | null`.
|
|
138
|
+
// Lo da quien tiene Bluetooth; la invitación se anuncia mientras la sesión vive.
|
|
139
|
+
announce = null,
|
|
140
|
+
// DOS APARATOS RESPONDIERON a la misma invitación (§1.7): la sesión ya se canceló aquí;
|
|
141
|
+
// quien monta la bóveda lo cuenta como incidente. `{ devices: [{ deviceId, machine }], mode }`.
|
|
142
|
+
onContested = () => {}
|
|
136
143
|
} = {}) {
|
|
137
144
|
if (!identity) throw new Error('createEnrollDesk: missing identity')
|
|
138
145
|
if (!iss) throw new Error('createEnrollDesk: missing iss (master pubkey)')
|
|
@@ -159,7 +166,16 @@ export function createEnrollDesk ({
|
|
|
159
166
|
try { ({ signature } = await identity.signData(signed)) } catch (e) { log('[vault] could not sign the reply:', e.message); return }
|
|
160
167
|
reply(to, { ...obj, signed, vsig: signature })
|
|
161
168
|
}
|
|
162
|
-
const fail = (to, error, sn) => tell(to, { type: MSG_ERROR, error }, sn)
|
|
169
|
+
const fail = (to, error, sn, code) => tell(to, { type: MSG_ERROR, error, ...(code ? { code } : {}) }, sn)
|
|
170
|
+
|
|
171
|
+
/** Anuncia la invitación de la sesión, si hay con qué. Devuelve con qué pararlo, o null. */
|
|
172
|
+
const announceInvite = (qr) => {
|
|
173
|
+
if (typeof announce !== 'function') return null
|
|
174
|
+
try { return announce('pair', encodeInvite(qr)) || null } catch (e) {
|
|
175
|
+
log('[vault] could not announce the invitation nearby:', e.message)
|
|
176
|
+
return null
|
|
177
|
+
}
|
|
178
|
+
}
|
|
163
179
|
const isFresh = (d) => typeof d?.ts === 'number' && Math.abs(Date.now() - d.ts) <= FRESH_WINDOW_MS
|
|
164
180
|
|
|
165
181
|
/**
|
|
@@ -216,13 +232,18 @@ export function createEnrollDesk ({
|
|
|
216
232
|
const conn = typeof connToken === 'function' ? await connToken() : connToken
|
|
217
233
|
if (conn) {
|
|
218
234
|
const sn = randToken(8)
|
|
219
|
-
|
|
220
|
-
|
|
235
|
+
const qr = { v: 2, conn, sn, m: mode, proxy }
|
|
236
|
+
const stopAnnounce = announceInvite(qr)
|
|
237
|
+
pending.set(sn, { token: sn, exp: Date.now() + PAIRING_TTL_MS, scope, caps, ttlMs, label, sn, mode, account: acct, state: 'AWAITING_ENROLL', stopAnnounce })
|
|
238
|
+
return { token: sn, qr, expiresInMs: PAIRING_TTL_MS, nearby: !!stopAnnounce }
|
|
221
239
|
}
|
|
222
240
|
const token = randToken(PAIR_TOKEN_BYTES)
|
|
223
241
|
const sn = randToken(PAIR_TOKEN_BYTES)
|
|
224
|
-
|
|
225
|
-
|
|
242
|
+
const qr = { v: 2, iss, proxy, token, sn, m: mode, ...(acct ? { acct } : {}) }
|
|
243
|
+
const stopAnnounce = announceInvite(qr)
|
|
244
|
+
pending.set(token, { token, exp: Date.now() + PAIRING_TTL_MS, scope, caps, ttlMs, label, sn, mode, account: acct, state: 'AWAITING_ENROLL', stopAnnounce })
|
|
245
|
+
// `nearby`: la invitación también se anuncia por Bluetooth (§1.6), para decirlo en pantalla.
|
|
246
|
+
return { token, qr, expiresInMs: PAIRING_TTL_MS, nearby: !!stopAnnounce }
|
|
226
247
|
}
|
|
227
248
|
|
|
228
249
|
function stopPairing (token) { forget(token) }
|
|
@@ -238,6 +259,8 @@ export function createEnrollDesk ({
|
|
|
238
259
|
pending.delete(key)
|
|
239
260
|
if (!pend) return
|
|
240
261
|
gone.add(pend.token); if (pend.sn) gone.add(pend.sn)
|
|
262
|
+
// Cerrada la sesión, la invitación deja de anunciarse.
|
|
263
|
+
if (pend.stopAnnounce) { try { pend.stopAnnounce() } catch (_) {} pend.stopAnnounce = null }
|
|
241
264
|
while (gone.size > 200) gone.delete(gone.values().next().value)
|
|
242
265
|
}
|
|
243
266
|
|
|
@@ -331,10 +354,25 @@ export function createEnrollDesk ({
|
|
|
331
354
|
audit('rejected', { what: 'enroll', reason: 'no-commit' })
|
|
332
355
|
return fail(from, 'this device speaks an old pairing version (no code commitment). Update it and try again.', d.sn)
|
|
333
356
|
}
|
|
334
|
-
//
|
|
335
|
-
|
|
336
|
-
|
|
357
|
+
// DOS APARATOS RESPONDIERON A LA MISMA INVITACIÓN (pairing-protocol.md §1.7): se cancela
|
|
358
|
+
// la sesión, no se aprueba a ninguno y es un incidente. Antes se rechazaba al segundo y el
|
|
359
|
+
// primero seguía: si el primero era el intruso, el legítimo se quedaba fuera y el dueño solo
|
|
360
|
+
// veía un código que no cuadraba. El reclamo se apunta SIN esperar (`claimed`), así dos
|
|
361
|
+
// ENROLL que llegan juntos no pasan los dos por aquí antes de que el primero lo marque.
|
|
362
|
+
if (pend.claimed && pend.claimed.dpub !== d.dpub) {
|
|
363
|
+
const first = pend.claimed
|
|
364
|
+
const [firstId, secondId] = await Promise.all([deviceIdOf(first.dpub), deviceIdOf(d.dpub)])
|
|
365
|
+
const devices = [{ deviceId: firstId, machine: first.machine }, { deviceId: secondId, machine: cleanMachine(d.machine) }]
|
|
366
|
+
forget(d.token)
|
|
367
|
+
audit('incident', { what: 'enroll', reason: 'pairing-contested', devices: [firstId, secondId] })
|
|
368
|
+
log(`[vault] pairing cancelled: ${firstId} and ${secondId} both answered the same invitation — reported as an incident`)
|
|
369
|
+
const why = 'pairing cancelled: another device answered this invitation. Start again.'
|
|
370
|
+
await Promise.all([fail(first.from, why, d.sn, 'pairing-contested'), fail(from, why, d.sn, 'pairing-contested')])
|
|
371
|
+
fire(onContested, { devices, mode: pend.mode || 'join' })
|
|
372
|
+
fire(onPendingChange)
|
|
373
|
+
return { contested: true }
|
|
337
374
|
}
|
|
375
|
+
if (!pend.claimed) pend.claimed = { dpub: d.dpub, from, machine: cleanMachine(d.machine) }
|
|
338
376
|
|
|
339
377
|
const deviceId = await deviceIdOf(d.dpub)
|
|
340
378
|
pend.state = 'PENDING_CONFIRM'
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* invite.js — la invitación de emparejamiento: cómo se escribe y cómo se lee.
|
|
3
|
+
*
|
|
4
|
+
* Una invitación viaja de dos maneras —un QR que se escanea y un código que se
|
|
5
|
+
* copia y se pega— y **las dos quieren lo mismo: que sea CORTA**. En un QR cada
|
|
6
|
+
* carácter son módulos, y los módulos son filas y columnas de terminal; en un
|
|
7
|
+
* código pegable, cada carácter es una oportunidad de que alguien lo corte mal.
|
|
8
|
+
*
|
|
9
|
+
* Por eso el formato vigente es **`c` (compacto)**: los datos van en BINARIO y el
|
|
10
|
+
* binario en base64url. Nada de JSON. Un JSON con la llave maestra dentro pesa
|
|
11
|
+
* ~340 caracteres (la llave es una JWK *serializada como string*, con sus comillas
|
|
12
|
+
* escapadas: 182 de esos 340 son ella sola); el mismo contenido en binario son ~75
|
|
13
|
+
* bytes → **~100 caracteres**. Medido en la práctica: el QR pasó de 69 módulos
|
|
14
|
+
* (77×39 en la terminal) a 41 (49×25), y el código pegable de 458 caracteres a 101.
|
|
15
|
+
*
|
|
16
|
+
* De dónde sale el ahorro, en orden de importancia:
|
|
17
|
+
* · **La llave `iss`** (182 → 44 chars). Una pubkey P-256 son dos coordenadas de
|
|
18
|
+
* 32 bytes; en el QR va el **punto comprimido** de 33 bytes (SEC1: `02`/`03`
|
|
19
|
+
* según la paridad de `y`, seguido de `x`) y el lector recupera `y` resolviendo
|
|
20
|
+
* la curva. La JWK se rearma con una PLANTILLA (el índice va en la cabecera)
|
|
21
|
+
* para que la string vuelva **byte a byte** igual: el proxy direcciona por esa
|
|
22
|
+
* string exacta, así que una coma de más rompe el enrutamiento.
|
|
23
|
+
* · **`token` y `sn`** (34+34 → 16+16 bytes): eran hexadecimal, que gasta dos
|
|
24
|
+
* caracteres por byte.
|
|
25
|
+
* · **`proxy`** (33 → 0): si es el del ecosistema no viaja; se sobreentiende.
|
|
26
|
+
* · **`m` y `v`**: dos campos de JSON → dos grupos de bits de la cabecera.
|
|
27
|
+
*
|
|
28
|
+
* SEGURIDAD DEL AHORRO: `encodeInvite` **comprueba el viaje de vuelta** antes de
|
|
29
|
+
* entregar la forma compacta — decodifica lo que acaba de codificar y exige que sea
|
|
30
|
+
* idéntico al original. Si algo no encaja (una JWK con otra forma, un campo nuevo,
|
|
31
|
+
* un `token` que no es hex), devuelve la forma larga en base64. Así una llave rara
|
|
32
|
+
* no rompe un emparejamiento: como mucho lo hace más grande.
|
|
33
|
+
*
|
|
34
|
+
* Formatos que se leen (el primer carácter dice cuál es):
|
|
35
|
+
* · `c` — compacto binario+base64url. **El que se emite hoy**, para el QR y para
|
|
36
|
+
* el código pegable: es a la vez el más corto y una sola palabra sin
|
|
37
|
+
* comillas ni llaves, que sobrevive a un doble clic y a un chat.
|
|
38
|
+
* · `b` — base64url del JSON. Forma larga, de reserva.
|
|
39
|
+
* · `j` — JSON crudo. Solo para leer enlaces ya emitidos.
|
|
40
|
+
* · sin marca — anterior a la marca de formato (base64url, o JSON).
|
|
41
|
+
*
|
|
42
|
+
* GOTCHA que justifica el `decodeURIComponent`: el JSON crudo lleva `{`, `}` y `"`,
|
|
43
|
+
* que **no son legales en una URI**. Al abrir el enlace, el navegador los
|
|
44
|
+
* percent-codifica (`%22`…), así que lo que llega a `location.hash` NO es lo que se
|
|
45
|
+
* emitió. Medido en un navegador real (2026-07-28). El formato compacto no tiene
|
|
46
|
+
* ese problema —base64url ya es seguro en una URL—, pero `j` sigue por ahí.
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
export const FMT_JSON = 'j'
|
|
50
|
+
export const FMT_B64 = 'b'
|
|
51
|
+
export const FMT_COMPACT = 'c'
|
|
52
|
+
/**
|
|
53
|
+
* `t` — la invitación CORTA: solo la dirección y el nonce de la sesión. La llave
|
|
54
|
+
* maestra ya no viaja; el aparato se la pide a la bóveda por la red presentando el
|
|
55
|
+
* `sn`, y la comprueba con la firma del certificado y con el código de 6 dígitos,
|
|
56
|
+
* que es lo único que de verdad decide. Esconderla no aportaba nada —una pública es
|
|
57
|
+
* pública— y ocupaba 44 de los ~100 caracteres.
|
|
58
|
+
*
|
|
59
|
+
* Lo que lleva NO es la dirección de la bóveda: es una **cita del proxy** —un código
|
|
60
|
+
* de 6 caracteres, de un solo uso y con minutos de vida, cuyos 2 primeros dicen qué
|
|
61
|
+
* proxio la emitió—. El aparato la CANJEA (`redeemPairingCode`) y obtiene la dirección
|
|
62
|
+
* real de la conexión, que hoy son 24 caracteres para poder rutearse entre proxios y no
|
|
63
|
+
* cabría cómoda en un QR. Además, una cita caduca y se quema: no deja una dirección
|
|
64
|
+
* permanente impresa en algo que circula.
|
|
65
|
+
*/
|
|
66
|
+
export const FMT_SHORT = 't'
|
|
67
|
+
|
|
68
|
+
/** El proxy del ecosistema: si es este, no viaja en la invitación compacta. */
|
|
69
|
+
export const DEFAULT_PROXY = 'wss://proxy.dotrino.com'
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* La base del enlace del QR. Corta a propósito (`/d#v=` en vez de `/vault#vault=`):
|
|
73
|
+
* son caracteres menos dentro del QR, y ahí los caracteres se pagan en módulos.
|
|
74
|
+
*
|
|
75
|
+
* `parseInvite` no mira la ruta, solo el #fragment: por eso un enlace emitido con
|
|
76
|
+
* cualquiera de las formas anteriores sigue emparejando aunque su dirección ya no
|
|
77
|
+
* exista.
|
|
78
|
+
*/
|
|
79
|
+
export const PAIR_URL = 'https://vault.dotrino.com/d#v='
|
|
80
|
+
|
|
81
|
+
// ---------------------------------------------------------------------------
|
|
82
|
+
// Conversiones (sin dependencias: esto corre en el navegador, en Node y dentro
|
|
83
|
+
// del binario SEA). El base64url vive en `b64.js`, porque el paquete de llaves de
|
|
84
|
+
// los inicios de sesión usa el mismo.
|
|
85
|
+
// ---------------------------------------------------------------------------
|
|
86
|
+
|
|
87
|
+
import { bytesToB64url, b64urlToBytes } from './b64.js'
|
|
88
|
+
|
|
89
|
+
const utf8 = (s) => new TextEncoder().encode(s)
|
|
90
|
+
const fromUtf8 = (b) => new TextDecoder().decode(b)
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* `token` y `sn` son hexadecimal. Caben en la invitación en dos tamaños —12 o 16
|
|
94
|
+
* bytes— porque el hexadecimal gasta dos caracteres por byte y en un QR eso se
|
|
95
|
+
* paga: 12 bytes (96 bits, lo que emite hoy `startPairing`) son 11 caracteres
|
|
96
|
+
* menos que 16, y esos 11 caracteres son la diferencia entre que quepa un nombre
|
|
97
|
+
* de cuenta normal o que el QR suba una versión entera.
|
|
98
|
+
*/
|
|
99
|
+
const hexLen = (s) => (typeof s === 'string' && /^[0-9a-f]+$/.test(s) && (s.length === 24 || s.length === 32)) ? s.length / 2 : 0
|
|
100
|
+
const hexToBytes = (s) => Uint8Array.from(s.match(/../g).map((h) => parseInt(h, 16)))
|
|
101
|
+
const bytesToHex = (b) => [...b].map((x) => x.toString(16).padStart(2, '0')).join('')
|
|
102
|
+
|
|
103
|
+
const b64urlEncodeStr = (s) => bytesToB64url(utf8(s))
|
|
104
|
+
const b64urlDecodeStr = (s) => { const b = b64urlToBytes(s); return b ? fromUtf8(b) : null }
|
|
105
|
+
|
|
106
|
+
// ---------------------------------------------------------------------------
|
|
107
|
+
// La llave maestra: JWK ⇄ punto comprimido de la curva P-256
|
|
108
|
+
// ---------------------------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Las formas de JWK que existen en el ecosistema. `JSON.stringify` de una JWK
|
|
112
|
+
* conserva el orden en que la exportó cada WebCrypto, y **ese orden es parte de la
|
|
113
|
+
* identidad**: el proxy direcciona por la string exacta. Por eso no se «normaliza»
|
|
114
|
+
* la JWK —eso cambiaría la dirección de la bóveda—, se rearma tal cual con la
|
|
115
|
+
* plantilla que le toca. El índice viaja en la cabecera (2 bits, hasta 4 formas).
|
|
116
|
+
*/
|
|
117
|
+
const JWK_TEMPLATES = [
|
|
118
|
+
// 0 — WebCrypto de Node (el daemon del PC): key_ops, ext, kty, x, y, crv
|
|
119
|
+
(x, y) => `{"key_ops":["verify"],"ext":true,"kty":"EC","x":"${x}","y":"${y}","crv":"P-256"}`,
|
|
120
|
+
// 1 — WebCrypto de navegador (Chrome/Firefox/Safari, alfabético): crv, ext, key_ops, kty, x, y
|
|
121
|
+
(x, y) => `{"crv":"P-256","ext":true,"key_ops":["verify"],"kty":"EC","x":"${x}","y":"${y}"}`,
|
|
122
|
+
]
|
|
123
|
+
|
|
124
|
+
// Parámetros de la curva P-256 (FIPS 186-4). `a` es −3.
|
|
125
|
+
const P256_P = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn
|
|
126
|
+
const P256_B = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn
|
|
127
|
+
|
|
128
|
+
const modPow = (base, exp, m) => {
|
|
129
|
+
let r = 1n; let b = base % m
|
|
130
|
+
while (exp > 0n) { if (exp & 1n) r = (r * b) % m; b = (b * b) % m; exp >>= 1n }
|
|
131
|
+
return r
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const bytesToBig = (b) => { let n = 0n; for (const x of b) n = (n << 8n) | BigInt(x); return n }
|
|
135
|
+
const bigToBytes32 = (n) => { const out = new Uint8Array(32); for (let i = 31; i >= 0; i--) { out[i] = Number(n & 0xffn); n >>= 8n } return out }
|
|
136
|
+
|
|
137
|
+
/** Coordenada de una JWK: base64url de 32 bytes exactos, o `null`. */
|
|
138
|
+
function coordBytes (s) {
|
|
139
|
+
if (typeof s !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(s)) return null
|
|
140
|
+
const b = b64urlToBytes(s)
|
|
141
|
+
return b && b.length === 32 ? b : null
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* `iss` (JWK serializada) → `{ tpl, point }` con el punto comprimido de 33 bytes, o
|
|
146
|
+
* `null` si la llave no tiene una forma conocida (entonces la invitación va larga).
|
|
147
|
+
*/
|
|
148
|
+
function packPubkey (iss) {
|
|
149
|
+
if (typeof iss !== 'string') return null
|
|
150
|
+
let jwk
|
|
151
|
+
try { jwk = JSON.parse(iss) } catch { return null }
|
|
152
|
+
if (!jwk || jwk.kty !== 'EC' || jwk.crv !== 'P-256') return null
|
|
153
|
+
const xb = coordBytes(jwk.x); const yb = coordBytes(jwk.y)
|
|
154
|
+
if (!xb || !yb) return null
|
|
155
|
+
|
|
156
|
+
const tpl = JWK_TEMPLATES.findIndex((f) => f(jwk.x, jwk.y) === iss)
|
|
157
|
+
if (tpl < 0) return null // forma desconocida: no se puede rearmar igual → larga
|
|
158
|
+
|
|
159
|
+
const point = new Uint8Array(33)
|
|
160
|
+
point[0] = 2 + (yb[31] & 1) // 02 = y par, 03 = y impar
|
|
161
|
+
point.set(xb, 1)
|
|
162
|
+
return { tpl, point }
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Punto comprimido + plantilla → la `iss` original (o `null` si el punto no es de la curva). */
|
|
166
|
+
function unpackPubkey (point, tpl) {
|
|
167
|
+
const template = JWK_TEMPLATES[tpl]
|
|
168
|
+
if (!template || point.length !== 33 || (point[0] !== 2 && point[0] !== 3)) return null
|
|
169
|
+
|
|
170
|
+
const x = bytesToBig(point.subarray(1))
|
|
171
|
+
if (x >= P256_P) return null
|
|
172
|
+
// y² = x³ − 3x + b (mod p). Con p ≡ 3 (mod 4) la raíz es y = (y²)^((p+1)/4).
|
|
173
|
+
const y2 = (((x * x) % P256_P) * x - 3n * x + P256_B) % P256_P
|
|
174
|
+
const rhs = (y2 + P256_P) % P256_P
|
|
175
|
+
let y = modPow(rhs, (P256_P + 1n) / 4n, P256_P)
|
|
176
|
+
if ((y * y) % P256_P !== rhs) return null // x no está en la curva
|
|
177
|
+
if ((y & 1n) !== BigInt(point[0] & 1)) y = P256_P - y
|
|
178
|
+
|
|
179
|
+
return template(bytesToB64url(point.subarray(1)), bytesToB64url(bigToBytes32(y)))
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ---------------------------------------------------------------------------
|
|
183
|
+
// El formato compacto
|
|
184
|
+
// ---------------------------------------------------------------------------
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Cabecera (1 byte):
|
|
188
|
+
* bits 0-2 versión del protocolo (`qr.v`, hoy 2)
|
|
189
|
+
* bit 3 modo: 0 = `join` · 1 = `adopt`
|
|
190
|
+
* bits 4-5 plantilla de la JWK (índice en `JWK_TEMPLATES`)
|
|
191
|
+
* bit 6 lleva proxy propio (si no, el del ecosistema)
|
|
192
|
+
* bit 7 `token`/`sn` de 12 bytes (si 0, de 16)
|
|
193
|
+
*
|
|
194
|
+
* Cuerpo: punto comprimido (33) ‖ token (n) ‖ sn (n) ‖ len+`acct` ‖ [len+`proxy`]
|
|
195
|
+
*/
|
|
196
|
+
const MODES = ['join', 'adopt']
|
|
197
|
+
|
|
198
|
+
function compactEncode (qr) {
|
|
199
|
+
if (!qr || typeof qr !== 'object') return null
|
|
200
|
+
const v = qr.v
|
|
201
|
+
if (!Number.isInteger(v) || v < 0 || v > 7) return null
|
|
202
|
+
const mode = MODES.indexOf(qr.m)
|
|
203
|
+
if (mode < 0) return null
|
|
204
|
+
const n = hexLen(qr.token)
|
|
205
|
+
if (!n || hexLen(qr.sn) !== n) return null
|
|
206
|
+
|
|
207
|
+
const pub = packPubkey(qr.iss)
|
|
208
|
+
if (!pub || pub.tpl > 3) return null
|
|
209
|
+
|
|
210
|
+
const acct = utf8(String(qr.acct || ''))
|
|
211
|
+
if (acct.length > 255) return null
|
|
212
|
+
const ownProxy = qr.proxy && qr.proxy !== DEFAULT_PROXY
|
|
213
|
+
const proxy = ownProxy ? utf8(String(qr.proxy)) : null
|
|
214
|
+
if (proxy && proxy.length > 255) return null
|
|
215
|
+
|
|
216
|
+
// Un campo que no se sepa escribir se perdería en silencio: eso NO se hace.
|
|
217
|
+
const known = new Set(['v', 'iss', 'proxy', 'token', 'sn', 'm', 'acct'])
|
|
218
|
+
if (Object.keys(qr).some((k) => !known.has(k))) return null
|
|
219
|
+
|
|
220
|
+
const head = v | (mode << 3) | (pub.tpl << 4) | (ownProxy ? 0x40 : 0) | (n === 12 ? 0x80 : 0)
|
|
221
|
+
const out = [head, ...pub.point, ...hexToBytes(qr.token), ...hexToBytes(qr.sn), acct.length, ...acct]
|
|
222
|
+
if (proxy) out.push(proxy.length, ...proxy)
|
|
223
|
+
return bytesToB64url(Uint8Array.from(out))
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function compactDecode (text) {
|
|
227
|
+
const b = b64urlToBytes(text)
|
|
228
|
+
const n = (b && (b[0] & 0x80)) ? 12 : 16
|
|
229
|
+
if (!b || b.length < 35 + n * 2) return null
|
|
230
|
+
const head = b[0]
|
|
231
|
+
|
|
232
|
+
const iss = unpackPubkey(b.subarray(1, 34), (head >> 4) & 3)
|
|
233
|
+
if (!iss) return null
|
|
234
|
+
|
|
235
|
+
let i = 34
|
|
236
|
+
const token = bytesToHex(b.subarray(i, i + n)); i += n
|
|
237
|
+
const sn = bytesToHex(b.subarray(i, i + n)); i += n
|
|
238
|
+
const acctLen = b[i]; i += 1
|
|
239
|
+
if (i + acctLen > b.length) return null
|
|
240
|
+
const acct = acctLen ? fromUtf8(b.subarray(i, i + acctLen)) : ''
|
|
241
|
+
i += acctLen
|
|
242
|
+
|
|
243
|
+
let proxy = DEFAULT_PROXY
|
|
244
|
+
if (head & 0x40) {
|
|
245
|
+
if (i >= b.length) return null
|
|
246
|
+
const n = b[i]; i += 1
|
|
247
|
+
if (i + n > b.length) return null
|
|
248
|
+
proxy = fromUtf8(b.subarray(i, i + n)); i += n
|
|
249
|
+
}
|
|
250
|
+
if (i !== b.length) return null // sobran bytes: no es lo que creemos que es
|
|
251
|
+
|
|
252
|
+
// Mismo orden de campos que `startPairing`, para que las dos formas serialicen igual.
|
|
253
|
+
return { v: head & 7, iss, proxy, token, sn, m: MODES[(head >> 3) & 1], ...(acct ? { acct } : {}) }
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// ---------------------------------------------------------------------------
|
|
257
|
+
// API
|
|
258
|
+
// ---------------------------------------------------------------------------
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Blob de la forma CORTA (`t`): cabecera(1) ‖ token de conexión(4 ASCII) ‖ sn(8)
|
|
262
|
+
* ‖ [len+proxy].
|
|
263
|
+
* bits 0-2 versión · bit 3 modo (join/adopt) · bit 4 lleva proxy propio
|
|
264
|
+
*
|
|
265
|
+
* Sin llave y sin nombre de cuenta: eso llega en la respuesta de la bóveda, así que
|
|
266
|
+
* un nombre largo ya no agranda el QR. 13 bytes → 18 caracteres.
|
|
267
|
+
*
|
|
268
|
+
* El PROXY sí viaja cuando no es el del ecosistema, y no es opcional: el token de
|
|
269
|
+
* conexión solo tiene sentido **en el proxy donde se emitió**. Quitarlo hacía que un
|
|
270
|
+
* aparato se conectara al proxy público y le hablara a un token de otro servidor —
|
|
271
|
+
* el mensaje no llegaba a ninguna parte y el emparejamiento se quedaba esperando.
|
|
272
|
+
* Le pasa a cualquiera con proxy propio (y lo cazó el E2E de secretos, que levanta
|
|
273
|
+
* uno local).
|
|
274
|
+
*/
|
|
275
|
+
// La CITA del proxio: 2 caracteres de prefijo de nodo + 4 = 6. Antes eran 4 (la
|
|
276
|
+
// dirección de la conexión). Cambió porque la dirección pasó a ser una instancia
|
|
277
|
+
// de 24 caracteres, y lo que se imprime en un QR ahora es una cita de un solo uso.
|
|
278
|
+
const CONN_TOKEN_LEN = 6
|
|
279
|
+
|
|
280
|
+
function shortEncode (qr) {
|
|
281
|
+
if (!qr || qr.v !== 2) return null
|
|
282
|
+
const mode = MODES.indexOf(qr.m)
|
|
283
|
+
if (mode < 0) return null
|
|
284
|
+
const conn = String(qr.conn || '')
|
|
285
|
+
if (conn.length !== CONN_TOKEN_LEN || !/^[\x21-\x7e]+$/.test(conn)) return null
|
|
286
|
+
if (!/^[0-9a-f]{16}$/.test(qr.sn || '')) return null // 8 bytes
|
|
287
|
+
const known = new Set(['v', 'conn', 'sn', 'm', 'proxy'])
|
|
288
|
+
if (Object.keys(qr).some((k) => !known.has(k))) return null
|
|
289
|
+
const ownProxy = qr.proxy && qr.proxy !== DEFAULT_PROXY
|
|
290
|
+
const proxy = ownProxy ? utf8(String(qr.proxy)) : null
|
|
291
|
+
if (proxy && proxy.length > 255) return null
|
|
292
|
+
const out = [qr.v | (mode << 3) | (ownProxy ? 0x10 : 0), ...[...conn].map((c) => c.charCodeAt(0)), ...hexToBytes(qr.sn)]
|
|
293
|
+
if (proxy) out.push(proxy.length, ...proxy)
|
|
294
|
+
return bytesToB64url(Uint8Array.from(out))
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function shortDecode (text) {
|
|
298
|
+
const b = b64urlToBytes(text)
|
|
299
|
+
if (!b || b.length < 1 + CONN_TOKEN_LEN + 8) return null
|
|
300
|
+
const head = b[0]
|
|
301
|
+
if (head & 0xe0) return null
|
|
302
|
+
let i = 1 + CONN_TOKEN_LEN + 8
|
|
303
|
+
let proxy = DEFAULT_PROXY
|
|
304
|
+
if (head & 0x10) {
|
|
305
|
+
if (i >= b.length) return null
|
|
306
|
+
const n = b[i]; i += 1
|
|
307
|
+
if (i + n !== b.length) return null
|
|
308
|
+
proxy = fromUtf8(b.subarray(i, i + n)); i += n
|
|
309
|
+
} else if (i !== b.length) return null
|
|
310
|
+
const conn = String.fromCharCode(...b.subarray(1, 1 + CONN_TOKEN_LEN))
|
|
311
|
+
return { v: head & 7, conn, sn: bytesToHex(b.subarray(1 + CONN_TOKEN_LEN, 1 + CONN_TOKEN_LEN + 8)), m: MODES[(head >> 3) & 1], proxy }
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Comparación por contenido, sin depender del orden de las claves. */
|
|
315
|
+
const canon = (o) => JSON.stringify(Object.keys(o).sort().map((k) => [k, o[k]]))
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* El payload marcado, listo para meter en el `#fragment` o para copiar y pegar.
|
|
319
|
+
*
|
|
320
|
+
* Por defecto **compacto**, que es lo más corto y a la vez pegable. Se cae a la
|
|
321
|
+
* forma larga (`b`) sola, sin avisar, si el compacto no reproduce el original
|
|
322
|
+
* exactamente: más vale un QR grande que uno que no empareja.
|
|
323
|
+
*/
|
|
324
|
+
export function encodeInvite (qr, fmt = FMT_COMPACT) {
|
|
325
|
+
const json = JSON.stringify(qr)
|
|
326
|
+
// La forma corta se emite cuando el QR trae dirección en vez de llave.
|
|
327
|
+
if (qr && qr.conn) {
|
|
328
|
+
const t = shortEncode(qr)
|
|
329
|
+
if (t) { const back = shortDecode(t); if (back && canon(back) === canon(qr)) return FMT_SHORT + t }
|
|
330
|
+
}
|
|
331
|
+
if (fmt === FMT_JSON) return FMT_JSON + json
|
|
332
|
+
if (fmt === FMT_COMPACT) {
|
|
333
|
+
const c = compactEncode(qr)
|
|
334
|
+
// El viaje de vuelta se comprueba SIEMPRE: es barato (una vez por
|
|
335
|
+
// emparejamiento) y es lo que permite comprimir sin jugarse el enrolamiento.
|
|
336
|
+
if (c) { const back = compactDecode(c); if (back && canon(back) === canon(qr)) return FMT_COMPACT + c }
|
|
337
|
+
}
|
|
338
|
+
return FMT_B64 + b64urlEncodeStr(json)
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** El enlace del QR: `https://vault.dotrino.com/d#v=<invitación>`. */
|
|
342
|
+
export function inviteUrl (qr) { return PAIR_URL + encodeInvite(qr) }
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Corta el `#fragment` de una URL. `#vault=` es la forma larga histórica y `#v=` la
|
|
346
|
+
* corta de hoy; se prueba la larga primero porque `#vault=` empieza por `#v`.
|
|
347
|
+
*/
|
|
348
|
+
const cutFragment = (text) => {
|
|
349
|
+
const long = text.indexOf('#vault=')
|
|
350
|
+
if (long >= 0) return text.slice(long + 7)
|
|
351
|
+
const short = text.indexOf('#v=')
|
|
352
|
+
return short >= 0 ? text.slice(short + 3) : text
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* Lee una invitación venga como venga: URL con `#v=`/`#vault=`, el código suelto,
|
|
357
|
+
* con marca de formato o sin ella (formatos viejos). Devuelve el objeto del QR o
|
|
358
|
+
* `null` — nunca lanza, porque del otro lado hay alguien pegando texto a mano.
|
|
359
|
+
*/
|
|
360
|
+
export function parseInvite (text) {
|
|
361
|
+
if (!text) return null
|
|
362
|
+
const payload = cutFragment(String(text).trim())
|
|
363
|
+
if (!payload) return null
|
|
364
|
+
|
|
365
|
+
const parse = (s) => { try { const o = JSON.parse(s); return (o && typeof o === 'object') ? o : null } catch { return null } }
|
|
366
|
+
// El navegador percent-codifica el JSON del fragmento; deshacerlo es un no-op si
|
|
367
|
+
// no lo tocó. Si el texto trae un `%` suelto, `decodeURIComponent` lanza: se usa
|
|
368
|
+
// el original.
|
|
369
|
+
const undoUrl = (s) => { try { return decodeURIComponent(s) } catch { return s } }
|
|
370
|
+
|
|
371
|
+
const tag = payload[0]
|
|
372
|
+
const rest = payload.slice(1)
|
|
373
|
+
if (tag === FMT_SHORT) { const o = shortDecode(rest); if (o) return o }
|
|
374
|
+
if (tag === FMT_COMPACT) { const o = compactDecode(rest); if (o) return o }
|
|
375
|
+
if (tag === FMT_JSON) { const o = parse(undoUrl(rest)) || parse(rest); if (o) return o }
|
|
376
|
+
if (tag === FMT_B64) { const s = b64urlDecodeStr(rest); const o = s && parse(s); if (o) return o }
|
|
377
|
+
|
|
378
|
+
// --- sin marca: formatos anteriores a la marca de formato (compatibilidad) ---
|
|
379
|
+
const raw = undoUrl(payload)
|
|
380
|
+
if (raw.trimStart().startsWith('{')) return parse(raw)
|
|
381
|
+
const s = b64urlDecodeStr(payload)
|
|
382
|
+
return s ? parse(s) : null
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
export default { encodeInvite, inviteUrl, parseInvite, FMT_JSON, FMT_B64, FMT_COMPACT, FMT_SHORT, PAIR_URL, DEFAULT_PROXY }
|