@dotrino/identity 0.125.1 → 0.126.1
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/src/index.js +2 -0
- package/vault/core.js +23 -0
- package/vault/facade.js +2 -0
- package/vault/vendor/proxy-client/VERSION.txt +1 -1
- package/vault/vendor/proxy-client/ble/manager.js +475 -0
- package/vault/vendor/proxy-client/ble/wire.js +192 -0
- package/vault/vendor/proxy-client/client.js +116 -9
- 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 +20 -8
- package/vault/vendor/vault/VERSION.txt +3 -2
- package/vault/vendor/vault/core/exNotices.js +66 -0
- package/vault/vendor/vault/core/gate.js +11 -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 +70 -12
- package/vault/vendor/vault/enroll.js +47 -9
- package/vault/vendor/vault/invite.js +385 -0
|
@@ -8,6 +8,9 @@
|
|
|
8
8
|
* con freno por conexión y freno global, antes de cualquier trabajo.
|
|
9
9
|
* · **El alta de un aparato** (`HELLO`, `ENROLL`, `ACTA_SEALED`): solo mientras hay un
|
|
10
10
|
* emparejamiento abierto y el mensaje es de ESE emparejamiento. Fuera de eso, nada.
|
|
11
|
+
* · **Los que salieron** (`CHECK`): un aparato de las actas de la ventana que ya no está pasa
|
|
12
|
+
* solo a preguntar si sigue dentro, con su firma y con freno. Se le contesta con su aviso
|
|
13
|
+
* de expulsión ya firmado (`exNotices.js`), para que se borre.
|
|
11
14
|
*
|
|
12
15
|
* Lo demás se descarta EN SILENCIO: sin respuesta, sin firma, sin línea en la bitácora y sin
|
|
13
16
|
* tocar el disco. Antes un desconocido conseguía que la bóveda le contestara con el acta
|
|
@@ -77,9 +80,10 @@ export function claimOf (MSG, p) {
|
|
|
77
80
|
* @param {object} o.MSG los tipos del protocolo
|
|
78
81
|
* @param {() => Promise<object|null>} o.acta el acta vigente de esta bóveda
|
|
79
82
|
* @param {(type: string, p: object, from: string) => boolean} o.pairing ¿es de un emparejamiento abierto?
|
|
83
|
+
* @param {(pub: string) => boolean} [o.former] ¿estuvo en el acta (y tiene su aviso)?
|
|
80
84
|
* @param {ReturnType<typeof makeLimiter>} [o.limiter]
|
|
81
85
|
*/
|
|
82
|
-
export function createGate ({ MSG, acta, pairing, limiter = makeLimiter(), verify = verifyDeviceSig }) {
|
|
86
|
+
export function createGate ({ MSG, acta, pairing, former = () => false, limiter = makeLimiter(), verify = verifyDeviceSig }) {
|
|
83
87
|
const LOGIN = new Set([MSG.LOGIN_START, MSG.LOGIN_FINISH, MSG.LOGIN_CLOSE])
|
|
84
88
|
const PAIRING = new Set([MSG.HELLO, MSG.ENROLL, MSG.ACTA_SEALED])
|
|
85
89
|
const stats = { dropped: 0, throttled: 0, since: Date.now() }
|
|
@@ -100,7 +104,12 @@ export function createGate ({ MSG, acta, pairing, limiter = makeLimiter(), verif
|
|
|
100
104
|
if (!claim || typeof claim.pub !== 'string' || !claim.pub) { stats.dropped++; return { ok: false } }
|
|
101
105
|
// NADA QUE DECIDIR SIN ACTA: se para (no hay a quién atender), no se deja pasar.
|
|
102
106
|
const record = await acta()
|
|
103
|
-
if (!record
|
|
107
|
+
if (!record) { stats.dropped++; return { ok: false } }
|
|
108
|
+
const member = (record.members || []).some((m) => m?.pub === claim.pub)
|
|
109
|
+
// Un ex-miembro, solo a preguntar si sigue dentro, y con freno.
|
|
110
|
+
const leaving = !member && type === MSG.CHECK && former(claim.pub)
|
|
111
|
+
if (!member && !leaving) { stats.dropped++; return { ok: false } }
|
|
112
|
+
if (leaving && !limiter.take('check:' + from)) { stats.throttled++; return { ok: false } }
|
|
104
113
|
if (claim.signature !== null) {
|
|
105
114
|
const ok = typeof claim.signature === 'string' && claim.data &&
|
|
106
115
|
await verify({ publickey: claim.pub, data: claim.data, signature: claim.signature }).catch(() => false)
|
|
@@ -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()
|
|
@@ -25,6 +25,7 @@ import { openThreadStore, STORE_READ_METHODS, PROFILE_EDIT_METHODS } from './thr
|
|
|
25
25
|
import { openSecretsStore, assertVar, RECOVERY as RECOVERY_WRAP, PROFILE_OWNER } from './secretsStore.js'
|
|
26
26
|
import { openSubacta } from './subacta.js'
|
|
27
27
|
import { openBlocked } from './blocked.js'
|
|
28
|
+
import { openExNotices } from './exNotices.js'
|
|
28
29
|
import { openNotifiable } from './notifiable.js'
|
|
29
30
|
import { openMachines } from './machines.js'
|
|
30
31
|
import { machineLine } from '@dotrino/identity/machine'
|
|
@@ -265,6 +266,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
265
266
|
const passwordsAtRest = disk.atRest
|
|
266
267
|
// Los aparatos BLOQUEADOS por un aprobador (`src/blocked.js`). Cifrado en reposo como lo demás.
|
|
267
268
|
const blocked = openBlocked({ disk })
|
|
269
|
+
const exNotices = openExNotices({ disk })
|
|
268
270
|
// Qué aprobadores dijeron que pueden recibir avisos (`src/notifiable.js`). No decide nada: se enseña.
|
|
269
271
|
const notifiable = openNotifiable({ disk })
|
|
270
272
|
// Dónde corre cada aparato, según lo último que dijo firmado (`src/machines.js`). Se enseña.
|
|
@@ -473,6 +475,19 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
473
475
|
* maestra o quedándose mudos. Se vio el 2026-09-02: de dos perfiles, el que tenía
|
|
474
476
|
* contraseña era el que no tenía `commkey.json`.
|
|
475
477
|
*/
|
|
478
|
+
/**
|
|
479
|
+
* LOS AVISOS DE LOS QUE SALIERON (`exNotices.js`): uno firmado por cada aparato de las actas
|
|
480
|
+
* de la ventana que ya no está. Solo con la bóveda ABIERTA y si esta sella: cerrada no firma.
|
|
481
|
+
*/
|
|
482
|
+
async function syncExNotices () {
|
|
483
|
+
try {
|
|
484
|
+
if (isLocked() || identity.masterLocked || !(await identity.isMaster?.())) return
|
|
485
|
+
const past = ((await identity.pastMembers()).members || []).map((m) => m.pub)
|
|
486
|
+
const n = await exNotices.sync(past, async (body) => (await identity.signData(body)).signature)
|
|
487
|
+
if (n) log(`[vault] signed the leaving notice of ${n} former member(s): they get it when they ask`)
|
|
488
|
+
} catch (e) { log('[vault] could not prepare the notices for former members:', e.message) }
|
|
489
|
+
}
|
|
490
|
+
|
|
476
491
|
async function ensureCommKeyInActa () {
|
|
477
492
|
try {
|
|
478
493
|
const info = await identity.profileActa?.()
|
|
@@ -505,7 +520,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
505
520
|
// ninguna llave y solo sabe la dirección `nombre@AB12-CD34-EF56`— pueda encontrar a quien
|
|
506
521
|
// la atiende. Lo construye la pieza compartida, porque quien lo busca es la extensión.
|
|
507
522
|
const { client, identify: reidentify, isIdentified, listen } = await createTransport({
|
|
508
|
-
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
|
|
509
525
|
})
|
|
510
526
|
|
|
511
527
|
// El registro público de cadenas de selladores: deposita, si hay a dónde, los eslabones
|
|
@@ -513,6 +529,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
513
529
|
// `sealers.js` — es una comodidad para quien lee, nunca una dependencia de la bóveda.
|
|
514
530
|
startSealersPublisher({ identity, client, log })
|
|
515
531
|
if (commSealedAtStart) await notifyMembers('commkey')
|
|
532
|
+
await syncExNotices()
|
|
516
533
|
|
|
517
534
|
async function revocationSet () {
|
|
518
535
|
const { revoked } = await identity.listDelegations()
|
|
@@ -862,6 +879,13 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
862
879
|
markRotationDue(sub).catch((e) => log('[vault] could not rotate after the removal:', e.message))
|
|
863
880
|
},
|
|
864
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
|
+
},
|
|
865
889
|
onChallenge ({ deviceId, scope, machine }) {
|
|
866
890
|
log(`\n[vault] Un dispositivo quiere conectarse:`)
|
|
867
891
|
log(` deviceId: ${deviceId}`)
|
|
@@ -1321,9 +1345,13 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
1321
1345
|
}
|
|
1322
1346
|
const record = (await identity.profileActa?.().catch(() => null))?.acta || null
|
|
1323
1347
|
const inside = (record?.members || []).some((m) => m?.pub === pub)
|
|
1324
|
-
|
|
1348
|
+
// Solo de los de dentro: un ex-miembro pregunta con freno y no escribe en la bitácora.
|
|
1349
|
+
if (inside) audit('check', { device: await deviceIdOf(pub).catch(() => null), in: true })
|
|
1325
1350
|
if (inside) return reply(from, { type: MSG.CHECKED, in: true })
|
|
1326
|
-
|
|
1351
|
+
// UN EX-MIEMBRO: su aviso, el que se firmó una vez (`exNotices`). Primero el aviso y luego
|
|
1352
|
+
// el «no»: el aparato deja de escuchar al recibir el «no». Aquí no se firma nada.
|
|
1353
|
+
const notice = exNotices.get(pub)
|
|
1354
|
+
if (notice) reply(from, { type: MSG.REVOKED, body: notice.body, signature: notice.signature })
|
|
1327
1355
|
reply(from, { type: MSG.CHECKED, in: false })
|
|
1328
1356
|
}
|
|
1329
1357
|
|
|
@@ -2158,6 +2186,39 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
2158
2186
|
* marcador hasta que el aviso salió, y tragarlo sería borrarlo sin haber avisado.
|
|
2159
2187
|
* @returns {Promise<{ approvers: number, sent: number, notice: object|null }>}
|
|
2160
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
|
+
|
|
2161
2222
|
async function announceUpdate ({ version, from = null, product = '@dotrino/vaultd', deviceId = null, label = null, ev = 'updated' }) {
|
|
2162
2223
|
const record = await refreshActa()
|
|
2163
2224
|
const who = (record?.members || []).filter((m) => Acta.memberCan(record, m.pub, 'approve')).map((m) => m.pub)
|
|
@@ -2165,14 +2226,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
2165
2226
|
// `deviceId`/`label`: solo cuando quien se actualizó es un APARATO (`update-done`). El
|
|
2166
2227
|
// aviso de la propia bóveda no los lleva.
|
|
2167
2228
|
const notice = notices.add(ev, { version, from, product, ...(deviceId ? { deviceId, label: label || '' } : {}) })
|
|
2168
|
-
const
|
|
2169
|
-
const body = { ev, id, ...rest, ts }
|
|
2170
|
-
const seal = await sealOrFail(body)
|
|
2171
|
-
let sent = 0
|
|
2172
|
-
for (const pub of who) {
|
|
2173
|
-
try { client.sendByPubkey(pub, { type: MSG.ADMIN_EVENT, body, seal }, { app: 'vault' }); sent++ }
|
|
2174
|
-
catch (e) { log(`[vault] could not tell ${pub.slice(0, 24)}… about the update of ${product} to ${version}: ${e.message}`) }
|
|
2175
|
-
}
|
|
2229
|
+
const sent = await sendNotice(notice, who, `the update of ${product} to ${version}`)
|
|
2176
2230
|
audit(ev === 'updated' ? 'update.announced' : 'update.needs-root', { product, version, from: notice.from, device: deviceId, approvers: who.length, sent })
|
|
2177
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}`)
|
|
2178
2232
|
if (!sent) throw Object.assign(new Error('no approver could be told'), { code: 'announce-failed' })
|
|
@@ -2235,7 +2289,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
2235
2289
|
const gate = createGate({
|
|
2236
2290
|
MSG,
|
|
2237
2291
|
acta: async () => (await identity.profileActa?.().catch(() => null))?.acta || null,
|
|
2238
|
-
pairing: (type, p) => desk.ownsPairing(type, p)
|
|
2292
|
+
pairing: (type, p) => desk.ownsPairing(type, p),
|
|
2293
|
+
former: (pub) => exNotices.has(pub)
|
|
2239
2294
|
})
|
|
2240
2295
|
|
|
2241
2296
|
// `listen` y no `client.on`: entrega también lo que llegó encolado antes de este punto.
|
|
@@ -2564,6 +2619,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
2564
2619
|
* `sendByPubkey`, así que al que está apagado le llega cuando encienda (cola 24 h).
|
|
2565
2620
|
*/
|
|
2566
2621
|
async function notifyMembers (ev, info = {}) {
|
|
2622
|
+
// El acta pudo cambiar (alguien salió): su aviso tiene que estar listo para cuando pregunte.
|
|
2623
|
+
await syncExNotices()
|
|
2567
2624
|
try {
|
|
2568
2625
|
// SIN FIRMA, y no falta nada: quien lo usa es el ACTA que viaja al lado, que se
|
|
2569
2626
|
// autentica sola (otra bóveda la adopta por `canAdopt`; el teléfono solo refresca y
|
|
@@ -4328,6 +4385,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
4328
4385
|
try {
|
|
4329
4386
|
if (await ensureCommKeyInActa()) { await reidentify?.(); await notifyMembers('commkey') }
|
|
4330
4387
|
} catch (_) {}
|
|
4388
|
+
await syncExNotices()
|
|
4331
4389
|
}
|
|
4332
4390
|
// Y ABSORBER LO PENDIENTE. La subacta ya lo estaba honrando con el perfil cerrado —de
|
|
4333
4391
|
// eso vive—, pero mientras siga ahí solo lo sabe esta máquina: al sellarlo, entra en
|
|
@@ -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'
|