@dotrino/identity 0.136.0 → 0.136.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/package.json +3 -2
  2. package/src/index.d.ts +60 -2
  3. package/src/index.js +364 -81
  4. package/src/node.js +29 -5
  5. package/types/acta.d.ts +397 -175
  6. package/types/assertion.d.ts +25 -18
  7. package/types/avatar.d.ts +14 -3
  8. package/types/capabilities.d.ts +110 -61
  9. package/types/content.d.ts +88 -45
  10. package/types/core.d.ts +578 -383
  11. package/types/keyid.d.ts +10 -3
  12. package/types/machine.d.ts +5 -1
  13. package/types/peerStore.d.ts +80 -0
  14. package/types/peerSync.d.ts +20 -6
  15. package/types/remote.d.ts +170 -42
  16. package/types/session.d.ts +74 -81
  17. package/types/sessionFlow.d.ts +108 -33
  18. package/types/vaultSeal.d.ts +21 -9
  19. package/vault/acta.js +245 -29
  20. package/vault/assertion.js +13 -4
  21. package/vault/avatar.js +12 -1
  22. package/vault/capabilities.js +56 -6
  23. package/vault/channel.js +18 -2
  24. package/vault/content.js +60 -6
  25. package/vault/core.js +419 -88
  26. package/vault/externalKeys.js +34 -2
  27. package/vault/facade.js +182 -24
  28. package/vault/globals.d.ts +60 -0
  29. package/vault/keyid.js +10 -1
  30. package/vault/machine.js +7 -1
  31. package/vault/nativeStore.js +21 -4
  32. package/vault/originPolicy.js +13 -2
  33. package/vault/peerStore.js +57 -10
  34. package/vault/peerSync.js +23 -4
  35. package/vault/remote.js +132 -32
  36. package/vault/session.js +24 -7
  37. package/vault/sessionFlow.js +43 -9
  38. package/vault/sync.js +59 -15
  39. package/vault/vault.js +78 -49
  40. package/vault/vaultSeal.js +18 -7
  41. package/vault/vendor/compat/VERSION.txt +1 -1
  42. package/vault/vendor/compat/advisory.js +58 -8
  43. package/vault/vendor/compat/index.js +57 -6
  44. package/vault/vendor/compat/ranges.js +12 -2
  45. package/vault/vendor/proxy-client/VERSION.txt +1 -1
  46. package/vault/vendor/proxy-client/client.js +41 -19
  47. package/vault/vendor/roadmap/manifests.js +23 -23
  48. package/vault/vendor/store/VERSION.txt +1 -1
  49. package/vault/vendor/vault/VERSION.txt +1 -1
  50. package/vault/vendor/vault/core/libVersion.js +1 -1
  51. package/vault/vendor/vault/core/transport.js +15 -3
  52. package/vault/vendor/vault/core/vault.js +71 -1
  53. package/vault/vendor/vault/protocol.js +25 -0
package/vault/vault.js CHANGED
@@ -25,10 +25,11 @@ import { useBackend as usePeerBackend } from './peerStore.js'
25
25
  const bridge = idKeys ? appBridge(idKeys) : null
26
26
  // Y si la app GUARDA la identidad (`storage`, la de iOS): todo vive allí, uno para todas
27
27
  // las páginas, porque WebKit parte el almacén de este iframe por página (`./nativeStore.js`).
28
- const native = bridge && idKeys.storage === true ? await nativeBackends(bridge) : null
28
+ const native = bridge && /** @type {NonNullable<typeof idKeys>} */ (idKeys).storage === true ? await nativeBackends(bridge) : null
29
29
  if (native) usePeerBackend(native.peers)
30
30
 
31
31
  // kv estilo localStorage (síncrono) para me, nonces, delegaciones, certs.
32
+ /** @type {import('./core.js').Kv} */
32
33
  const kv = native ? native.kv : {
33
34
  getItem: (k) => localStorage.getItem(k),
34
35
  setItem: (k, v) => localStorage.setItem(k, v),
@@ -39,11 +40,13 @@ import { useBackend as usePeerBackend } from './peerStore.js'
39
40
  // IndexedDB (clonado estructurado). Nadie —ni este código, ni un XSS en este
40
41
  // origen— puede leer sus bytes; solo firmar/derivar con ellas. Las llaves
41
42
  // planas (JWK) viejas de localStorage se migran y se borran (core.js).
42
- const baseKeyStore = native ? native.keyStore : await (() => new Promise((resolve) => {
43
+ /** @type {import('./core.js').KeyStore | null} */
44
+ const baseKeyStore = native ? native.keyStore : await (() => new Promise(/** @param {(ks: import('./core.js').KeyStore | null) => void} resolve */ (resolve) => {
43
45
  const req = indexedDB.open('dotrino-identity-keys', 1)
44
46
  req.onupgradeneeded = () => req.result.createObjectStore('keys')
45
47
  req.onsuccess = () => {
46
48
  const db = req.result
49
+ /** @param {IDBTransactionMode} mode @param {(st: IDBObjectStore) => IDBRequest} fn @returns {Promise<any>} */
47
50
  const op = (mode, fn) => new Promise((res, rej) => {
48
51
  const tx = db.transaction('keys', mode)
49
52
  const r = fn(tx.objectStore('keys'))
@@ -51,9 +54,9 @@ import { useBackend as usePeerBackend } from './peerStore.js'
51
54
  r.onerror = () => rej(r.error)
52
55
  })
53
56
  resolve({
54
- get: (name) => op('readonly', (st) => st.get(name)),
55
- set: (name, pair) => op('readwrite', (st) => st.put(pair, name)),
56
- remove: (name) => op('readwrite', (st) => st.delete(name))
57
+ get: (/** @type {string} */ name) => op('readonly', (st) => st.get(name)),
58
+ set: (/** @type {string} */ name, /** @type {any} */ pair) => op('readwrite', (st) => st.put(pair, name)),
59
+ remove: (/** @type {string} */ name) => op('readwrite', (st) => st.delete(name))
57
60
  })
58
61
  }
59
62
  req.onerror = () => resolve(null) // sin IDB (raro): cae al modo kv legado
@@ -65,6 +68,7 @@ import { useBackend as usePeerBackend } from './peerStore.js'
65
68
 
66
69
  // sessionKv: la prueba de desbloqueo del candado por contraseña vive en
67
70
  // sessionStorage — POR PESTAÑA: sobrevive al refresco, muere al cerrarla.
71
+ /** @type {import('./core.js').Kv} */
68
72
  const sessionKv = {
69
73
  getItem: (k) => sessionStorage.getItem(k),
70
74
  setItem: (k, v) => sessionStorage.setItem(k, v),
@@ -86,6 +90,7 @@ import { useBackend as usePeerBackend } from './peerStore.js'
86
90
  ? { title: 'wants to see', allow: 'Allow', deny: 'No', who: 'Your Dotrino identity', once: 'Only what you allow leaves here.', via: 'through' }
87
91
  : { title: 'quiere ver', allow: 'Permitir', deny: 'No', who: 'Tu identidad de Dotrino', once: 'De aquí solo sale lo que permitas.', via: 'a través de' }
88
92
  })()
93
+ /** @type {Record<string, string>} */
89
94
  const SCOPE_TXT = (() => {
90
95
  const en = (navigator.language || 'es').startsWith('en')
91
96
  return en
@@ -102,8 +107,10 @@ import { useBackend as usePeerBackend } from './peerStore.js'
102
107
  * home y habría que subirlo cada vez que nace una app. El subdominio ya es el nombre.
103
108
  */
104
109
  /** Lo que dice el origen se pinta como texto, nunca como marcado: quien lo escribe es él. */
105
- const escaparTexto = (t) => String(t).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
110
+ /** @param {unknown} t @returns {string} */
111
+ const escaparTexto = (t) => String(t).replace(/[&<>"']/g, (c) => /** @type {Record<string, string>} */ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c])
106
112
 
113
+ /** @param {string} origin @returns {string} */
107
114
  function nombreDeOrigen (origin) {
108
115
  try {
109
116
  const h = new URL(origin).hostname
@@ -114,10 +121,15 @@ import { useBackend as usePeerBackend } from './peerStore.js'
114
121
  } catch (_) { return String(origin) }
115
122
  }
116
123
 
124
+ /** @type {HTMLElement | null} */
117
125
  let consentAbierto = null
126
+ /**
127
+ * @param {{ origin: string, scopes: string[], onBehalfOf?: string | null }} q
128
+ * @returns {Promise<boolean>}
129
+ */
118
130
  function askConsent ({ origin, scopes, onBehalfOf }) {
119
131
  if (consentAbierto) return Promise.resolve(false) // una pregunta a la vez
120
- return new Promise((resolve) => {
132
+ return new Promise(/** @param {(v: boolean) => void} resolve */ (resolve) => {
121
133
  const host = document.createElement('div')
122
134
  host.style.cssText = 'position:fixed;inset:0;z-index:2147483647;display:flex;align-items:center;justify-content:center;background:rgba(10,8,20,.86);font-family:system-ui,-apple-system,Segoe UI,sans-serif'
123
135
  const lista = scopes.map((x) => `<li>${SCOPE_TXT[x] || x}</li>`).join('')
@@ -131,9 +143,10 @@ import { useBackend as usePeerBackend } from './peerStore.js'
131
143
  <button data-yes style="flex:1;padding:10px;border-radius:10px;border:0;background:#7c3aed;color:#fff;font:inherit;font-weight:600;cursor:pointer">${T_CONSENT.allow}</button>
132
144
  <button data-no style="flex:1;padding:10px;border-radius:10px;border:1px solid #2a2350;background:transparent;color:inherit;font:inherit;cursor:pointer">${T_CONSENT.deny}</button>
133
145
  </div></div>`
146
+ /** @param {boolean} v */
134
147
  const cerrar = (v) => { try { host.remove() } catch (_) {} consentAbierto = null; broadcast('consent:close', {}); resolve(v) }
135
- host.querySelector('[data-yes]').addEventListener('click', () => cerrar(true))
136
- host.querySelector('[data-no]').addEventListener('click', () => cerrar(false))
148
+ /** @type {HTMLElement} */ (host.querySelector('[data-yes]')).addEventListener('click', () => cerrar(true))
149
+ ;/** @type {HTMLElement} */ (host.querySelector('[data-no]')).addEventListener('click', () => cerrar(false))
137
150
  consentAbierto = host
138
151
  document.body.appendChild(host)
139
152
  broadcast('consent:open', { origin })
@@ -151,7 +164,8 @@ import { useBackend as usePeerBackend } from './peerStore.js'
151
164
  askConsent
152
165
  })
153
166
 
154
- const { handlers } = core
167
+ // Para el iframe, los manejadores son una tabla que se despacha por nombre (`method`).
168
+ const handlers = /** @type {Record<string, (params?: any) => Promise<any>>} */ (/** @type {unknown} */ (core.handlers))
155
169
  const policy = originPolicy({ selfOrigin: window.location.origin })
156
170
 
157
171
  // ---- Control de ORIGEN (crítico): la identidad solo habla con el ecosistema. ----
@@ -170,22 +184,26 @@ import { useBackend as usePeerBackend } from './peerStore.js'
170
184
  'https?://172\\.(1[6-9]|2\\d|3[01])\\.\\d{1,3}\\.\\d{1,3}(:\\d+)?' +
171
185
  ')$'
172
186
  )
187
+ /** @param {unknown} origin @returns {boolean} */
173
188
  const isAllowed = (origin) => typeof origin === 'string' && ALLOWED_ORIGIN.test(origin)
174
189
 
175
190
  // Broadcast de eventos del vault (sync + emparejamiento) SOLO a embebedores que
176
191
  // ya hicieron una petición válida (ventana+origen verificados), nunca con '*'.
177
- const embedders = [] // [{ win, origin }]
192
+ /** @type {Array<{ win: MessageEventSource | Window, origin: string }>} */
193
+ const embedders = []
194
+ /** @param {MessageEventSource | Window | null} win @param {string} origin */
178
195
  const rememberEmbedder = (win, origin) => {
179
196
  if (!win || win === window) return
180
197
  if (!embedders.some((e) => e.win === win)) embedders.push({ win, origin })
181
198
  }
199
+ /** @param {string} eventName @param {any} payload */
182
200
  const broadcast = (eventName, payload) => {
183
201
  for (const { win, origin } of embedders) {
184
- try { win.postMessage({ _cci: true, type: 'event', event: eventName, payload }, origin) } catch {}
202
+ try { /** @type {Window} */ (win).postMessage({ _cci: true, type: 'event', event: eventName, payload }, origin) } catch {}
185
203
  }
186
204
  }
187
- core.onSyncStatus((p) => broadcast('sync', p))
188
- core.onVaultEvent((p) => broadcast('vault', p))
205
+ core.onSyncStatus((/** @type {any} */ p) => broadcast('sync', p))
206
+ core.onVaultEvent((/** @type {any} */ p) => broadcast('vault', p))
189
207
 
190
208
  // ---- Modo SELF: este navegador actúa como bóveda ----
191
209
  // Corre la MISMA bóveda que el binario (`startBrowserVault`): emparejar, firmar, cajones,
@@ -218,9 +236,12 @@ import { useBackend as usePeerBackend } from './peerStore.js'
218
236
  return /^wss?:\/\//.test(p || '') ? p : null
219
237
  } catch (_) { return null }
220
238
  })()
221
- let daemon = null // la bóveda (`startBrowserVault`) cuando ESTE iframe es el activo
222
- let daemonError = null // por qué no arrancó (`{ code, message }`), para enseñarlo
223
- let _lockResolver = null // resolver del callback del lock (libera al resolverlo)
239
+ /** @type {any} la bóveda (`startBrowserVault`) cuando ESTE iframe es el activo */
240
+ let daemon = null
241
+ /** @type {{ code: string | null, message: string } | null} por qué no arrancó, para enseñarlo */
242
+ let daemonError = null
243
+ /** @type {(() => void) | null} resolver del callback del lock (libera al resolverlo) */
244
+ let _lockResolver = null
224
245
 
225
246
  // La dirección `nombre@AB12-CD34-EF56` sale del acta de la cuenta.
226
247
  const selfIdentity = { profileActa: () => handlers.profileActa({}) }
@@ -253,11 +274,12 @@ import { useBackend as usePeerBackend } from './peerStore.js'
253
274
  ...(selfProxyUrl ? { proxyUrl: selfProxyUrl } : {}),
254
275
  legacyLogins,
255
276
  onPendingChange: () => broadcast('selfVault', { pending: daemon ? daemon.listPending() : [] }),
256
- onStopped: (e) => { daemon = null; daemonError = { code: e?.code || null, message: e?.message || String(e) }; broadcast('selfVault', { running: false, error: daemonError.message }) },
257
- log: (...a) => console.log(...a)
277
+ onStopped: (/** @type {any} */ e) => { daemon = null; daemonError = { code: e?.code || null, message: e?.message || String(e) }; broadcast('selfVault', { running: false, error: daemonError.message }) },
278
+ log: (/** @type {any[]} */ ...a) => console.log(...a)
258
279
  })
259
280
  broadcast('selfVault', { running: true })
260
- } catch (e) {
281
+ } catch (err) {
282
+ const e = /** @type {any} */ (err)
261
283
  daemon = null
262
284
  daemonError = { code: e?.code || null, message: e?.message || String(e) }
263
285
  broadcast('selfVault', { error: daemonError.message })
@@ -277,7 +299,7 @@ import { useBackend as usePeerBackend } from './peerStore.js'
277
299
  navigator.locks.request(SELF_LOCK, { mode: 'exclusive', ifAvailable: true }, async (lock) => {
278
300
  if (!lock) return // otra pestaña visible lo tiene
279
301
  await startSelfDaemon()
280
- await new Promise((resolve) => { _lockResolver = resolve }) // mantener el lock
302
+ await new Promise(/** @param {(v?: void) => void} resolve */ (resolve) => { _lockResolver = resolve }) // mantener el lock
281
303
  stopSelfDaemon()
282
304
  }).catch(() => {})
283
305
  }
@@ -292,14 +314,17 @@ import { useBackend as usePeerBackend } from './peerStore.js'
292
314
  // (ra.ping para agentes @dotrino/remote-agent —ia—; terminal.ping para terminal
293
315
  // pre-migración) y consideramos online si responde cualquiera. Reusa el cliente
294
316
  // del proxy del daemon activo en ESTE iframe; si no hay daemon, devuelve vacío.
317
+ /** @param {string[]} pubkeys @param {{ timeoutMs?: number }} [opts] @returns {Promise<Set<string>>} */
295
318
  function probeOnline (pubkeys, { timeoutMs = 4000 } = {}) {
296
319
  return new Promise((resolve) => {
320
+ /** @type {Set<string>} */
297
321
  const online = new Set()
298
322
  const client = daemon?.client
299
323
  if (!client?.sendByPubkey || !pubkeys.length) return resolve(online)
300
324
  let rest = pubkeys.length
325
+ /** @type {Map<string, string>} */
301
326
  const byNonce = new Map()
302
- const off = client.on('message', (_f, p) => {
327
+ const off = client.on('message', (/** @type {string} */ _f, /** @type {any} */ p) => {
303
328
  if (!p || typeof p !== 'object') return
304
329
  if (p.type === 'ra.pong' || p.type === 'terminal.pong') {
305
330
  const pk = byNonce.get(p.n)
@@ -330,6 +355,7 @@ import { useBackend as usePeerBackend } from './peerStore.js'
330
355
  if (daemon) return handlers.listVaultDevices({})
331
356
  const { issued, revoked } = await handlers.listDelegations({})
332
357
  const now = Date.now()
358
+ /** @type {Map<string, any>} */
333
359
  const bySub = new Map()
334
360
  for (const x of (issued || [])) {
335
361
  if (!x.sub || x.revokedAt || (x.exp && x.exp <= now)) continue
@@ -340,17 +366,17 @@ import { useBackend as usePeerBackend } from './peerStore.js'
340
366
  deviceId: await keyLabel(x.sub),
341
367
  sub: x.sub, label: x.label || '', scope: x.scope, exp: x.exp, nonce: x.nonce
342
368
  })))
343
- return { devices, revoked: (revoked || []).map((r) => r.nonce || r) }
369
+ return { devices, revoked: (revoked || []).map((/** @type {any} */ r) => r.nonce || r) }
344
370
  },
345
371
  selfVaultStatus: async () => ({ enabled: await selfEnabled(), running: !!daemon, error: daemon ? null : daemonError }),
346
- setSelfVault: async ({ enabled }) => {
372
+ setSelfVault: async (/** @type {{ enabled?: boolean }} */ { enabled }) => {
347
373
  const { id } = await handlers.currentProfile()
348
374
  if (enabled && !id) throw Object.assign(new Error('no profile: the vault belongs to an account'), { code: 'no-profile' })
349
- if (enabled) kv.setItem(SELF_FLAG, id); else kv.removeItem(SELF_FLAG)
375
+ if (enabled) kv.setItem(SELF_FLAG, /** @type {string} */ (id)); else kv.removeItem(SELF_FLAG)
350
376
  if (enabled) holdSelfLock(); else releaseSelfLock()
351
377
  return { ok: true, enabled: !!enabled }
352
378
  },
353
- selfVaultPairing: async (opts) => {
379
+ selfVaultPairing: async (/** @type {any} */ opts) => {
354
380
  if (!daemon) throw new Error('this tab is not the active vault; open it as a visible tab')
355
381
  return daemon.startPairing(opts)
356
382
  },
@@ -360,11 +386,11 @@ import { useBackend as usePeerBackend } from './peerStore.js'
360
386
  const { issued } = await handlers.listDelegations({})
361
387
  return issued || []
362
388
  },
363
- selfVaultApprove: async ({ deviceId, code }) => {
389
+ selfVaultApprove: async (/** @type {{ deviceId: string, code: string }} */ { deviceId, code }) => {
364
390
  if (!daemon) throw new Error('this tab is not the active vault')
365
391
  return daemon.approve(deviceId, code)
366
392
  },
367
- selfVaultReject: async ({ deviceId }) => {
393
+ selfVaultReject: async (/** @type {{ deviceId: string }} */ { deviceId }) => {
368
394
  if (!daemon) throw new Error('this tab is not the active vault')
369
395
  daemon.reject(deviceId)
370
396
  return { ok: true }
@@ -378,7 +404,7 @@ import { useBackend as usePeerBackend } from './peerStore.js'
378
404
  * mientras siga en el acta un papel retirado significa «renueva», no «estás fuera».
379
405
  * Se conserva para quien de verdad quiera retirar un certificado suelto.
380
406
  */
381
- selfVaultRevoke: async ({ sub, nonce }) => {
407
+ selfVaultRevoke: async (/** @type {{ sub?: string, nonce?: string }} */ { sub, nonce }) => {
382
408
  if (sub) {
383
409
  if (daemon?.revokeDevice) return daemon.revokeDevice(sub)
384
410
  return handlers.revokeDevice({ sub })
@@ -388,7 +414,7 @@ import { useBackend as usePeerBackend } from './peerStore.js'
388
414
  },
389
415
  // Presencia online (ping/pong) de las máquinas enroladas. Requiere que ESTE
390
416
  // iframe sea el daemon activo (tiene el cliente del proxy); si no, devuelve [].
391
- selfVaultProbe: async ({ pubkeys }) => ({ online: [...(await probeOnline(pubkeys || []))] }),
417
+ selfVaultProbe: async (/** @type {{ pubkeys?: string[] }} */ { pubkeys }) => ({ online: [...(await probeOnline(pubkeys || []))] }),
392
418
 
393
419
  // ----- ENTRAR CON USUARIO Y CONTRASEÑA, desde la PESTAÑA -----
394
420
  //
@@ -410,7 +436,7 @@ import { useBackend as usePeerBackend } from './peerStore.js'
410
436
  * la bóveda guarda un paquete que no puede abrir. Es el mismo camino que `logins add`
411
437
  * del binario, con la misma pieza compartida.
412
438
  */
413
- selfVaultLoginAdd: async ({ user, password, label = '', caps } = {}) => {
439
+ selfVaultLoginAdd: async (/** @type {{ user?: string, password?: string, label?: string, caps?: string[] }} */ { user, password, label = '', caps } = {}) => {
414
440
  const d = pidaDaemon()
415
441
  const { client: opaque } = await import('@dotrino/opaque')
416
442
  const { makeDeviceKey, makeDeviceEncKey } = await import('@dotrino/identity/capabilities')
@@ -430,7 +456,7 @@ import { useBackend as usePeerBackend } from './peerStore.js'
430
456
  // Los PERMISOS del acta, cualquiera de ellos: los traduce a scopes el pilar del vault.
431
457
  label: nombre, blob, ...(caps ? { caps } : {})
432
458
  })
433
- return { ...r, address: loginAddress(user, await accountFingerprint(selfIdentity)) }
459
+ return { ...r, address: loginAddress(/** @type {string} */ (user), await accountFingerprint(selfIdentity)) }
434
460
  },
435
461
 
436
462
  /**
@@ -438,17 +464,17 @@ import { useBackend as usePeerBackend } from './peerStore.js'
438
464
  * siguen siendo los mismos. Por eso hace falta la vieja — sin ella no hay nada que
439
465
  * volver a cerrar — y por eso lo que estuviera abierto se cierra.
440
466
  */
441
- selfVaultLoginPasswd: async ({ user, oldPassword, newPassword } = {}) => {
467
+ selfVaultLoginPasswd: async (/** @type {{ user?: string, oldPassword?: string, newPassword?: string }} */ { user, oldPassword, newPassword } = {}) => {
442
468
  const d = pidaDaemon()
443
469
  const { client: opaque } = await import('@dotrino/opaque')
444
470
  const { sealDeviceKeys, openDeviceKeys } = await import('@dotrino/vault/password-logins')
445
471
  if (typeof newPassword !== 'string' || newPassword.length < 12) {
446
472
  throw Object.assign(new Error('the password must be at least 12 characters'), { code: 'weak-password' })
447
473
  }
448
- const start = opaque.loginStart({ password: oldPassword })
474
+ const start = opaque.loginStart({ password: /** @type {string} */ (oldPassword) })
449
475
  const begun = await d.loginBegin({ user, request: start.request })
450
476
  let fin
451
- try { fin = opaque.loginFinish({ state: start.state, response: begun.response, password: oldPassword }) }
477
+ try { fin = opaque.loginFinish({ state: start.state, response: begun.response, password: /** @type {string} */ (oldPassword) }) }
452
478
  catch (_) { throw Object.assign(new Error('wrong password'), { code: 'login-failed' }) }
453
479
  const entered = await d.loginEnd({ lid: begun.lid, finalization: fin.finalization, label: 'consola' })
454
480
  const keys = await openDeviceKeys(fin.exportKey, entered.blob)
@@ -463,28 +489,28 @@ import { useBackend as usePeerBackend } from './peerStore.js'
463
489
  },
464
490
 
465
491
  /** Cerrar un inicio de sesión abierto (sin `sid`, todos los de ese usuario). */
466
- selfVaultLoginClose: async ({ user, sid = null } = {}) => {
492
+ selfVaultLoginClose: async (/** @type {{ user?: string, sid?: string | null }} */ { user, sid = null } = {}) => {
467
493
  const d = pidaDaemon()
468
494
  if (sid) return d.closeLogin({ user, sid })
469
- const fila = d.listLogins().find((x) => x.user === user)
470
- for (const s of fila?.sessions || []) d.closeLogin({ user, sid: s.sid })
495
+ const fila = d.listLogins().find((/** @type {any} */ x) => x.user === user)
496
+ for (const s of /** @type {any[]} */ (fila?.sessions || [])) d.closeLogin({ user, sid: s.sid })
471
497
  return { ok: true, closed: (fila?.sessions || []).length }
472
498
  },
473
499
 
474
500
  /** Quitar la espera de los intentos fallidos, desde la máquina de la bóveda. */
475
- selfVaultLoginUnblock: async ({ user } = {}) => pidaDaemon().clearLoginBlock({ user }),
501
+ selfVaultLoginUnblock: async (/** @type {{ user?: string }} */ { user } = {}) => pidaDaemon().clearLoginBlock({ user }),
476
502
 
477
503
  /**
478
504
  * QUITARLO. Se va de aquí **y su llave sale del acta**: borrar solo el inicio de sesión
479
505
  * dejaba un miembro que ya no puede entrar y sigue siendo de la cuenta.
480
506
  */
481
- selfVaultLoginRemove: async ({ user } = {}) => {
507
+ selfVaultLoginRemove: async (/** @type {{ user?: string }} */ { user } = {}) => {
482
508
  const d = pidaDaemon()
483
- const fila = d.listLogins().find((x) => x.user === user)
509
+ const fila = d.listLogins().find((/** @type {any} */ x) => x.user === user)
484
510
  const r = await d.removeLogin({ user })
485
511
  if (r?.ok && fila?.pub) {
486
512
  try { await handlers.revokeDevice({ sub: fila.pub }) } catch (e) {
487
- throw Object.assign(new Error(`the login is gone but its key is still in the record: ${e.message}`), { code: 'revoke-failed' })
513
+ throw Object.assign(new Error(`the login is gone but its key is still in the record: ${/** @type {any} */ (e).message}`), { code: 'revoke-failed' })
488
514
  }
489
515
  }
490
516
  return { ...r, deviceId: fila?.deviceId || null }
@@ -497,22 +523,22 @@ import { useBackend as usePeerBackend } from './peerStore.js'
497
523
  // elige la contraseña del respaldo — o sea, puede leerlo todo. Un fallo en cualquiera de
498
524
  // las apps no puede convertirse en sacar los secretos de la cuenta.
499
525
  // El archivo se cierra AQUÍ: a la consola le llega ya cifrado.
500
- selfVaultBackupDrawers: async ({ __origin } = {}) => {
526
+ selfVaultBackupDrawers: async (/** @type {{ __origin?: string }} */ { __origin } = {}) => {
501
527
  soloConsola(__origin)
502
528
  return pidaDaemon().backupDrawers()
503
529
  },
504
- selfVaultBackupExport: async ({ drawers = null, password, __origin } = {}) => {
530
+ selfVaultBackupExport: async (/** @type {{ drawers?: string[] | null, password?: any, __origin?: string }} */ { drawers = null, password, __origin } = {}) => {
505
531
  soloConsola(__origin)
506
532
  const { sealBackup } = await import('@dotrino/vault/backup')
507
533
  const { payload, summary } = await pidaDaemon().exportBackup({ drawers })
508
534
  return { file: await sealBackup(payload, password), summary }
509
535
  },
510
- selfVaultBackupPlan: async ({ file, password, drawers = null, map = {}, __origin } = {}) => {
536
+ selfVaultBackupPlan: async (/** @type {{ file?: any, password?: any, drawers?: string[] | null, map?: Record<string, string>, __origin?: string }} */ { file, password, drawers = null, map = {}, __origin } = {}) => {
511
537
  soloConsola(__origin)
512
538
  const { openBackup } = await import('@dotrino/vault/backup')
513
539
  return pidaDaemon().planBackupImport(await openBackup(file, password), { drawers, map })
514
540
  },
515
- selfVaultBackupImport: async ({ file, password, drawers = null, map = {}, onConflict = null, decisions = {}, __origin } = {}) => {
541
+ selfVaultBackupImport: async (/** @type {{ file?: any, password?: any, drawers?: string[] | null, map?: Record<string, string>, onConflict?: string | null, decisions?: Record<string, any>, __origin?: string }} */ { file, password, drawers = null, map = {}, onConflict = null, decisions = {}, __origin } = {}) => {
516
542
  soloConsola(__origin)
517
543
  const { openBackup } = await import('@dotrino/vault/backup')
518
544
  return pidaDaemon().importBackup(await openBackup(file, password), { drawers, map, onConflict, decisions })
@@ -524,6 +550,7 @@ import { useBackend as usePeerBackend } from './peerStore.js'
524
550
  * que es donde se prueba. Lo demás del ecosistema no puede pedir un respaldo.
525
551
  */
526
552
  const CONSOLE_ORIGIN = /^(https:\/\/vault\.dotrino\.com|https?:\/\/(localhost|127\.0\.0\.1|192\.168\.\d{1,3}\.\d{1,3}|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3})(:\d+)?)$/
553
+ /** @param {unknown} origin */
527
554
  function soloConsola (origin) {
528
555
  if (!CONSOLE_ORIGIN.test(String(origin || ''))) {
529
556
  throw Object.assign(new Error('only the vault console (vault.dotrino.com) can back up or restore'), { code: 'not-the-console' })
@@ -549,11 +576,12 @@ import { useBackend as usePeerBackend } from './peerStore.js'
549
576
  if (!isAllowed(event.origin)) return // origen ajeno: silencio total
550
577
  rememberEmbedder(event.source, event.origin)
551
578
  const { id, method, params } = msg
552
- const reply = (payload) => event.source?.postMessage(
579
+ /** @param {Record<string, any>} payload */
580
+ const reply = (payload) => /** @type {Window | null} */ (event.source)?.postMessage(
553
581
  { _cci: true, type: 'response', id, ...payload },
554
582
  event.origin
555
583
  )
556
- const handler = selfHandlers[method] || handlers[method]
584
+ const handler = /** @type {Record<string, (params: any) => any>} */ (selfHandlers)[method] || /** @type {Record<string, (params: any) => any>} */ (handlers)[method]
557
585
  if (!handler) return reply({ error: `Unknown method: ${method}` })
558
586
  try {
559
587
  // LO QUE DECIDE QUIÉN ES DE LA CUENTA solo lo pide la consola (`originPolicy.js`): una app
@@ -569,7 +597,8 @@ import { useBackend as usePeerBackend } from './peerStore.js'
569
597
  // medias: la cuenta quedaba en Pedidos y no en la lista de perfiles (2026-10-12).
570
598
  if (native) await native.flush()
571
599
  reply({ result })
572
- } catch (e) {
600
+ } catch (err) {
601
+ const e = /** @type {any} */ (err)
573
602
  if (native) await native.flush()
574
603
  // `code` (y su `detail`) CRUZAN. Sin ellos, al otro lado solo llegaba la frase, y una
575
604
  // app que quiere reaccionar a un rechazo concreto —«esa bóveda ya está en otra cuenta
@@ -38,15 +38,21 @@ export const PLAIN_UNTIL = Date.UTC(2026, 11, 15)
38
38
  export const PLAIN_UNTIL_TEXT = '2026-12-15'
39
39
 
40
40
  /** ¿Todavía se tolera el claro de la migración? */
41
+ /** @param {number} [now] @returns {boolean} */
41
42
  export function plainAllowed (now = Date.now()) { return now < PLAIN_UNTIL }
42
43
 
44
+ /** @param {string} message @param {string} code */
43
45
  const withCode = (message, code) => Object.assign(new Error(message), { code })
44
46
 
45
- /** Las llaves de comunicación de las bóvedas de la cuenta, según el acta. */
47
+ /**
48
+ * Las llaves de comunicación de las bóvedas de la cuenta, según el acta.
49
+ * @param {import('./acta.js').MaybeActa} acta
50
+ * @returns {string[]}
51
+ */
46
52
  export function vaultKeysOf (acta) {
47
53
  return [...new Set((acta?.members || [])
48
54
  .filter((m) => m && m.cn === VAULT_CN && typeof m.pub === 'string' && m.pub)
49
- .map((m) => m.pub))]
55
+ .map((m) => /** @type {string} */ (m.pub)))]
50
56
  }
51
57
 
52
58
  /**
@@ -58,12 +64,15 @@ export function vaultKeysOf (acta) {
58
64
  * No se fía del proxio: cada acta tiene que verificarse y encadenar con la anterior aceptada
59
65
  * (`canAdopt`, la regla de siempre). Un proxio que no guarda actas (`no-acta-cache`) no es un
60
66
  * fallo: se sigue con la que ya se tenía, que es la verificada. Cualquier otro error se dice.
67
+ * @param {any} client un cliente de `@dotrino/proxy-client`
68
+ * @param {import('./acta.js').MaybeActa} acta
69
+ * @returns {Promise<import('./acta.js').MaybeActa>}
61
70
  */
62
71
  export async function latestActa (client, acta) {
63
72
  if (!acta?.profileId || typeof acta.seq !== 'number' || typeof client?.getActas !== 'function') return acta
64
73
  let newer
65
74
  try { newer = await client.getActas(acta.profileId, { sinceSeq: acta.seq }) } catch (e) {
66
- if (e?.code === 'no-acta-cache') return acta
75
+ if (/** @type {{ code?: string } | null | undefined} */ (e)?.code === 'no-acta-cache') return acta
67
76
  throw e
68
77
  }
69
78
  let current = acta
@@ -80,11 +89,11 @@ export async function latestActa (client, acta) {
80
89
  * @param {object} o
81
90
  * @param {string} o.dest a qué llave se enruta (la cuenta, o `to`)
82
91
  * @param {string|null} [o.to] una bóveda concreta (su llave de comunicación): solo a ella
83
- * @param {object|null} [o.acta] el acta de la cuenta que este aparato ya aceptó: de ella (o de una
92
+ * @param {import('./acta.js').MaybeActa} [o.acta] el acta de la cuenta que este aparato ya aceptó: de ella (o de una
84
93
  * más nueva que encadene con ella, `latestActa`) salen las bóvedas
85
94
  * @param {object} o.payload `{ type, data, signature, cert }`
86
95
  * @param {boolean} [o.quiet] no timbra a una bóveda dormida
87
- * @param {(line:string)=>void} [o.warn] dónde se dice que salió en claro (migración)
96
+ * @param {((line:string)=>void) | null} [o.warn] dónde se dice que salió en claro (migración)
88
97
  * @param {number} [o.now]
89
98
  * @returns {Promise<{ sealed:number, why?:string }>}
90
99
  */
@@ -103,12 +112,12 @@ export async function sendToVault (client, { dest, to = null, acta = null, paylo
103
112
  for (const peerEncPub of encPubs) await client.sendSealed([dest], payload, { peerEncPub, ...opts })
104
113
  return { sealed: encPubs.length }
105
114
  }
106
- const why = keys.length ? (lastError?.code || 'no-encpub') : 'no-vault-key'
115
+ const why = keys.length ? (/** @type {{ code?: string } | null} */ (lastError)?.code || 'no-encpub') : 'no-vault-key'
107
116
  if (!plainAllowed(now)) {
108
117
  throw withCode(`cannot seal the request to the vault (${why}): update the vault, or let this device see the current record`, 'vault-unsealable')
109
118
  }
110
119
  // MIGRACIÓN (caduca 2026-12-15): ver la cabecera.
111
- try { warn?.(`[vault] request ${payload?.type || ''} sent UNSEALED (${why}): tolerated only until ${PLAIN_UNTIL_TEXT} — update the vault`) } catch (_) {}
120
+ try { warn?.(`[vault] request ${/** @type {{ type?: string } | null | undefined} */ (payload)?.type || ''} sent UNSEALED (${why}): tolerated only until ${PLAIN_UNTIL_TEXT} — update the vault`) } catch (_) {}
112
121
  client.sendByPubkey(dest, payload, opts)
113
122
  return { sealed: 0, why }
114
123
  }
@@ -116,6 +125,8 @@ export async function sendToVault (client, { dest, to = null, acta = null, paylo
116
125
  /**
117
126
  * ¿Se acepta esta respuesta? Sellada, siempre. Por el socket local, siempre. En claro, solo
118
127
  * durante la migración, y se dice. Devuelve `false` para ignorarla.
128
+ * @param {{ meta?: { sealed?: boolean } | null, local?: boolean, type?: string, warn?: ((line: string) => void) | null, now?: number }} args
129
+ * @returns {boolean}
119
130
  */
120
131
  export function acceptReply ({ meta, local = false, type = '', warn = null, now = Date.now() }) {
121
132
  if (local || meta?.sealed) return true
@@ -1,3 +1,3 @@
1
- Copia vendorizada de @dotrino/compat@0.5.0 (dotrino-compat/src/{advisory,index,ranges}.js).
1
+ Copia vendorizada de @dotrino/compat@0.5.1 (dotrino-compat/src/{advisory,index,ranges}.js).
2
2
  NO se edita a mano: la escribe `node vendor.mjs` y la vigila test/vendor-up-to-date.test.mjs.
3
3
  Qué versión es cada pieza y si pueden hablar (CONVENCIONES §14).
@@ -31,26 +31,52 @@
31
31
  * es otro silencio, que es de lo que venimos huyendo.
32
32
  */
33
33
 
34
+ /**
35
+ * Una entrada de la lista de rotas que lleva el aviso.
36
+ * @typedef {object} AdvisoryEntry
37
+ * @property {string} product
38
+ * @property {string[]} versions
39
+ * @property {string} [why]
40
+ * @property {string} [fix]
41
+ */
42
+
43
+ /**
44
+ * El aviso firmado: «actualiza estos componentes».
45
+ * @typedef {object} Advisory
46
+ * @property {'compat.advisory'} op
47
+ * @property {number} seq solo hacia adelante
48
+ * @property {number} issued ms desde epoch
49
+ * @property {AdvisoryEntry[]} broken
50
+ * @property {string} sig ECDSA P-256 (P1363) en base64
51
+ */
52
+
34
53
  /**
35
54
  * JSON canónico (claves ordenadas, recursivo). Es una COPIA deliberada del de
36
55
  * `@dotrino/proxy-client`: este paquete no depende de nadie —lo importan las ~30 apps y el
37
56
  * proxio— y la firma tiene que dar los mismos bytes en las dos puntas. Si algún día
38
57
  * cambian, cambian los dos: hay un test que compara la salida contra la del pilar.
58
+ *
59
+ * @param {unknown} value
60
+ * @returns {string}
39
61
  */
40
62
  export function canonicalStringify (value) {
41
63
  if (value === null || typeof value !== 'object') return JSON.stringify(value)
42
64
  if (Array.isArray(value)) return '[' + value.map(canonicalStringify).join(',') + ']'
43
- const keys = Object.keys(value).sort()
44
- return '{' + keys.map((k) => JSON.stringify(k) + ':' + canonicalStringify(value[k])).join(',') + '}'
65
+ const o = /** @type {Record<string, unknown>} */ (value)
66
+ const keys = Object.keys(o).sort()
67
+ return '{' + keys.map((k) => JSON.stringify(k) + ':' + canonicalStringify(o[k])).join(',') + '}'
45
68
  }
46
69
 
70
+ /** @param {string} s */
47
71
  const enc = (s) => new TextEncoder().encode(s)
72
+ /** @param {ArrayBuffer} buf */
48
73
  const b64 = (buf) => {
49
74
  const b = new Uint8Array(buf)
50
75
  let s = ''
51
76
  for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i])
52
77
  return btoa(s)
53
78
  }
79
+ /** @param {string} str */
54
80
  const fromB64 = (str) => {
55
81
  const bin = atob(str)
56
82
  const out = new Uint8Array(bin.length)
@@ -58,26 +84,37 @@ const fromB64 = (str) => {
58
84
  return out
59
85
  }
60
86
 
61
- /** El cuerpo que se firma: todo menos la firma. */
87
+ /**
88
+ * El cuerpo que se firma: todo menos la firma.
89
+ * @param {Partial<Advisory> | null | undefined} a
90
+ * @returns {Omit<Partial<Advisory>, 'sig'>}
91
+ */
62
92
  export const advisoryBody = (a) => {
63
93
  const { sig, ...body } = a || {}
64
94
  return body
65
95
  }
66
96
 
67
- /** ¿Tiene forma de aviso? No dice si es de fiar, solo si se puede juzgar. */
97
+ /**
98
+ * ¿Tiene forma de aviso? No dice si es de fiar, solo si se puede juzgar.
99
+ * @param {any} a lo que llegó de la red, sin comprobar: esta función es la que lo comprueba
100
+ * @returns {a is Advisory}
101
+ */
68
102
  export function isAdvisory (a) {
69
103
  return !!a && a.op === 'compat.advisory' && Number.isInteger(a.seq) && a.seq >= 0 &&
70
104
  typeof a.issued === 'number' && Array.isArray(a.broken) && typeof a.sig === 'string' &&
71
- a.broken.every((b) => b && typeof b.product === 'string' && Array.isArray(b.versions) &&
72
- b.versions.every((v) => typeof v === 'string'))
105
+ a.broken.every((/** @type {any} */ b) => b && typeof b.product === 'string' && Array.isArray(b.versions) &&
106
+ b.versions.every((/** @type {unknown} */ v) => typeof v === 'string'))
73
107
  }
74
108
 
75
109
  /**
76
110
  * FIRMA un aviso. Lo corre quien publica, no quien lo recibe: aquí está para que el
77
111
  * formato lo defina un solo sitio y no dos implementaciones que se separan.
112
+ *
113
+ * @param {{ seq: number, broken: AdvisoryEntry[], privateJwk: JsonWebKey, issued?: number }} args
114
+ * @returns {Promise<Advisory>}
78
115
  */
79
116
  export async function signAdvisory ({ seq, broken, privateJwk, issued = Date.now() }) {
80
- const body = { op: 'compat.advisory', seq, issued, broken }
117
+ const body = { op: /** @type {const} */ ('compat.advisory'), seq, issued, broken }
81
118
  const key = await globalThis.crypto.subtle.importKey(
82
119
  'jwk', privateJwk, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign'])
83
120
  const sig = await globalThis.crypto.subtle.sign(
@@ -88,6 +125,9 @@ export async function signAdvisory ({ seq, broken, privateJwk, issued = Date.now
88
125
  /**
89
126
  * ¿Lo firmó la llave de release que trae MI build? `publickey` es un JWK en texto, igual
90
127
  * que en el resto del ecosistema.
128
+ *
129
+ * @param {{ advisory: unknown, publickey: unknown }} args
130
+ * @returns {Promise<boolean>}
91
131
  */
92
132
  export async function verifyAdvisory ({ advisory, publickey }) {
93
133
  if (!isAdvisory(advisory) || typeof publickey !== 'string') return false
@@ -103,6 +143,9 @@ export async function verifyAdvisory ({ advisory, publickey }) {
103
143
  /**
104
144
  * ¿ME QUEDO CON EL QUE LLEGA? Solo hacia adelante y solo si lo firma quien yo digo.
105
145
  * Devuelve el aviso vigente (el nuevo o el que ya tenía) y por qué.
146
+ *
147
+ * @param {{ current?: Advisory | null, incoming: unknown, publickey: string }} args
148
+ * @returns {Promise<{ advisory: Advisory | null, adopted: boolean, reason: 'not-an-advisory' | 'not-newer' | 'invalid-signature' | 'newer' | 'first' }>}
106
149
  */
107
150
  export async function adoptAdvisory ({ current, incoming, publickey }) {
108
151
  if (!isAdvisory(incoming)) return { advisory: current || null, adopted: false, reason: 'not-an-advisory' }
@@ -121,12 +164,19 @@ export async function adoptAdvisory ({ current, incoming, publickey }) {
121
164
  * Se suman, no se sustituyen: el aviso puede añadir lo que se descubrió después de esta
122
165
  * build, pero **no puede quitar** lo que esta build ya afirma. Que la red pudiera
123
166
  * desmarcar algo que el código da por roto sería el repliegue de manual.
167
+ *
168
+ * @param {{ baked?: Array<{ product: string, versions: string | string[], why?: string, fix?: string }>, advisory?: unknown }} [args]
169
+ * @returns {Array<{ product: string, versions: string | string[], why?: string, fix?: string }>}
124
170
  */
125
171
  export function brokenNow ({ baked = [], advisory = null } = {}) {
126
172
  return advisory && isAdvisory(advisory) ? [...baked, ...advisory.broken] : [...baked]
127
173
  }
128
174
 
129
- /** Lo que el administrador enseña del aviso vigente (§14: se ve, no se esconde). */
175
+ /**
176
+ * Lo que el administrador enseña del aviso vigente (§14: se ve, no se esconde).
177
+ * @param {unknown} advisory
178
+ * @returns {{ seq: number, issued: number, components: Array<{ product: string, versions: string[], why: string | null, fix: string | null }> } | null}
179
+ */
130
180
  export function advisorySummary (advisory) {
131
181
  if (!isAdvisory(advisory)) return null
132
182
  return {