@dotrino/identity 0.136.1 → 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.
package/vault/core.js CHANGED
@@ -26,6 +26,81 @@ import { assertionBody, cleanScopes, claimsAllowed, ASSERTION_DEFAULT_TTL_MS, AS
26
26
  import { pubkeyId as pubkeyIdOf, signWithDevice, keyLabel } from './capabilities.js'
27
27
  import { enrollDevice as remoteEnroll, requestSign as remoteSign, requestStore as remoteStore, requestDevices as remoteDevices, requestRenew as remoteRenew, requestAdmin as remoteAdmin, requestApproval as remoteApproval, requestRenounce as remoteRenounce, checkMembership as remoteCheck, registerLocalVault } from './remote.js'
28
28
 
29
+ /**
30
+ * Almacén clave → texto, síncrono (localStorage, o lo que lo imite en Node y en la app).
31
+ * @typedef {{ getItem (k: string): string | null, setItem (k: string, v: string): void, removeItem (k: string): void }} Kv
32
+ */
33
+ /**
34
+ * Una llave que firma o deriva: una CryptoKey, o un asa de una llave que vive fuera (el chip).
35
+ * @typedef {import('./capabilities.js').SigningKey | { external: true, kid?: string, sign: (bytes: Uint8Array) => Promise<string>, deriveBits?: (peerPubJwkStr: string) => Promise<ArrayBuffer>, paired?: (account: any) => Promise<any> }} PrivateKeyLike
36
+ */
37
+ /**
38
+ * Lo que se guarda de un par en el almacén de llaves.
39
+ * @typedef {{ privateKey: PrivateKeyLike, publicJwk: JsonWebKey }} StoredPair
40
+ */
41
+ /**
42
+ * Dónde viven las llaves privadas: IndexedDB en el navegador (CryptoKey no extraíble), o el
43
+ * chip del teléfono (`externalKeys.js`), que además sabe crearlas e importarlas.
44
+ * @typedef {object} KeyStore
45
+ * @property {(name: string) => Promise<any>} get
46
+ * @property {(name: string, rec: any) => Promise<void>} set
47
+ * @property {(name: string) => Promise<void>} remove
48
+ * @property {(kind: 'sign' | 'enc', name: string) => Promise<StoredPair>} [create]
49
+ * @property {(pair: { sign: { name: string, privateJwk: JsonWebKey, publickey: string }, enc: { name: string, privateJwk: JsonWebKey | null, publickey: string | null } }) => Promise<void>} [importPair]
50
+ */
51
+
52
+ /**
53
+ * El libro de contactos que usa el núcleo: la interfaz de `vault/peerStore.js`.
54
+ * @typedef {{ initPeerStorage (): Promise<import('./peerStore.js').PeerBook>,
55
+ * loadPeers (): import('./peerStore.js').PeerBook, savePeers (p: import('./peerStore.js').PeerBook): void,
56
+ * setPeersDirect (p: import('./peerStore.js').PeerBook): void,
57
+ * upsertPeer (publickey: string, patch: Record<string, any>): import('./peerStore.js').PeerRecord,
58
+ * onDirty (fn: (() => void) | null): void,
59
+ * setProfile? (pid: string | null, opts?: { volatile?: boolean }): void | Promise<void>,
60
+ * adoptLegacy? (pid: string): void | Promise<void> }} CorePeers
61
+ */
62
+ /**
63
+ * El candado de la maestra: sella y abre con la llave que sale de la contraseña del perfil.
64
+ * Cerrado, `open` devuelve `null`.
65
+ * @typedef {{ seal? (plaintext: string): Promise<any>, open? (sealed: any): Promise<string | null> }} KeyLock
66
+ */
67
+ /**
68
+ * Lo que el núcleo necesita de quien lo monta (el iframe, Node o la app).
69
+ * @typedef {object} CoreDeps
70
+ * @property {Kv} kv almacén síncrono estilo localStorage (keypairs, me, nonces)
71
+ * @property {CorePeers} peers el libro de contactos
72
+ * @property {((cfg: { fileName: string, kind: string, exportLocal: () => Promise<any>, applyMerged: (merged: any) => Promise<void>, mergeFn: (local: any, remote: any) => Promise<{ merged: any, changed: boolean }> }) => any) | null} [makeSync]
73
+ * fábrica del respaldo en Drive (`createSync`); sin ella, los `sync*` lanzan
74
+ * @property {KeyStore | null} [keyStore] dónde viven las llaves privadas; sin él, JWK en `kv`
75
+ * @property {Kv | null} [sessionKv] lo de esta pestaña (`sessionStorage`)
76
+ * @property {boolean} [removeAccountOnExpulsion]
77
+ * @property {KeyLock | null} [keyLock]
78
+ * @property {((q: { origin: string, scopes: string[], already: string[], onBehalfOf: string | null }) => Promise<boolean> | boolean) | null} [askConsent]
79
+ */
80
+
81
+ /**
82
+ * Un perfil de la lista de este aparato.
83
+ * @typedef {{ id: string, name?: string, pubkey?: string | null, pendingJoin?: boolean } & Record<string, any>} ProfileEntry
84
+ */
85
+ /**
86
+ * Un par cargado: la privada (CryptoKey o el asa del chip; `null` con el candado echado) y la pública.
87
+ * @typedef {{ privateKey: any, publicKey: CryptoKey, publicJwk: JsonWebKey, locked?: boolean }} LoadedPair
88
+ */
89
+
90
+ /**
91
+ * El emparejamiento guardado con la bóveda: su papel, a quién y por dónde.
92
+ * @typedef {{ cert: any, master: string, proxy: string, deviceId?: string, pairedAt?: number, account?: string } & Record<string, any>} VaultLink
93
+ */
94
+ /** @typedef {import('./remote.js').DeviceKey} DeviceKey */
95
+
96
+ /** @typedef {import('./acta.js').Acta} Acta */
97
+
98
+ /**
99
+ * Los parámetros de un manejador: llegan por `postMessage` (de cualquier aplicación) o por la
100
+ * API de Node, sin comprobar. Cada manejador valida lo que usa.
101
+ * @typedef {Record<string, any>} HandlerParams
102
+ */
103
+
29
104
  export const KEY_STORAGE = 'dotrino.identity.keypair'
30
105
  export const ENC_KEY_STORAGE = 'dotrino.identity.enc-keypair'
31
106
  export const ME_STORAGE = 'dotrino.identity.me'
@@ -62,10 +137,11 @@ const PILAR_VAULT = '@dotrino/vault'
62
137
 
63
138
  // ----- crypto helpers (puros) -----
64
139
 
140
+ /** @param {any} v @returns {string} */
65
141
  export function canonicalStringify (v) {
66
142
  if (v === null || typeof v !== 'object') return JSON.stringify(v)
67
143
  // Un array con `undefined` va como `null`, igual que en JSON.stringify.
68
- if (Array.isArray(v)) return '[' + v.map((x) => x === undefined ? 'null' : canonicalStringify(x)).join(',') + ']'
144
+ if (Array.isArray(v)) return '[' + v.map((/** @type {unknown} */ x) => x === undefined ? 'null' : canonicalStringify(x)).join(',') + ']'
69
145
  // Una clave con `undefined` NO existe, igual que en JSON.stringify: antes salía como
70
146
  // `"k":undefined` (ni siquiera es JSON) y lo firmado en memoria no cuadraba con lo mismo
71
147
  // leído del disco o de la red (el directorio de nombres, 2026-10-15).
@@ -73,6 +149,7 @@ export function canonicalStringify (v) {
73
149
  return '{' + ks.map(k => JSON.stringify(k) + ':' + canonicalStringify(v[k])).join(',') + '}'
74
150
  }
75
151
 
152
+ /** @param {ArrayBuffer | ArrayLike<number>} buf @returns {string} */
76
153
  export function bufToBase64 (buf) {
77
154
  const bytes = new Uint8Array(buf)
78
155
  let s = ''
@@ -80,6 +157,7 @@ export function bufToBase64 (buf) {
80
157
  return btoa(s)
81
158
  }
82
159
 
160
+ /** @param {string} b64 @returns {ArrayBuffer} */
83
161
  export function base64ToBuf (b64) {
84
162
  const s = atob(b64)
85
163
  const bytes = new Uint8Array(s.length)
@@ -87,11 +165,13 @@ export function base64ToBuf (b64) {
87
165
  return bytes.buffer
88
166
  }
89
167
 
168
+ /** @param {string | JsonWebKey} jwkStr @returns {Promise<CryptoKey>} */
90
169
  async function importPeerEncPubkey (jwkStr) {
91
170
  const jwk = typeof jwkStr === 'string' ? JSON.parse(jwkStr) : jwkStr
92
171
  return crypto.subtle.importKey('jwk', jwk, { name: 'ECDH', namedCurve: 'P-256' }, true, [])
93
172
  }
94
173
 
174
+ /** @param {any} myPriv CryptoKey ECDH, o el asa de una llave del chip @param {CryptoKey} peerPub @returns {Promise<CryptoKey>} */
95
175
  async function deriveSharedAesKey (myPriv, peerPub) {
96
176
  if (myPriv?.external) {
97
177
  // Llave EXTERNA: el chip da los 32 bytes del secreto ECDH, que es exactamente lo que
@@ -109,12 +189,14 @@ async function deriveSharedAesKey (myPriv, peerPub) {
109
189
  )
110
190
  }
111
191
 
192
+ /** @param {any} privateKey CryptoKey ECDSA, o el asa de una llave del chip @param {Uint8Array<ArrayBuffer>} bytes @returns {Promise<string>} */
112
193
  async function signBytes (privateKey, bytes) {
113
194
  if (privateKey?.external) return privateKey.sign(bytes) // el chip del teléfono (ver rawSign)
114
195
  const sig = await crypto.subtle.sign({ name: 'ECDSA', hash: { name: 'SHA-256' } }, privateKey, bytes)
115
196
  return bufToBase64(sig)
116
197
  }
117
198
 
199
+ /** @param {string} publicJwkStr @param {Uint8Array<ArrayBuffer>} bytes @param {string} signatureBase64 @returns {Promise<boolean>} */
118
200
  async function verifyBytes (publicJwkStr, bytes, signatureBase64) {
119
201
  let publicKey
120
202
  try {
@@ -131,21 +213,13 @@ async function verifyBytes (publicJwkStr, bytes, signatureBase64) {
131
213
  )
132
214
  }
133
215
 
134
- /**
135
- * Crea el núcleo de identidad sobre los backends inyectados.
136
- *
137
- * @param {Object} deps
138
- * @param {{getItem(k):string|null, setItem(k,v):void, removeItem(k):void}} deps.kv
139
- * Almacén clave-valor síncrono estilo localStorage (keypairs, me, nonces).
140
- * @param {Object} deps.peers Peer book con la interfaz de vault/peerStore.js:
141
- * { initPeerStorage, loadPeers, savePeers, setPeersDirect, upsertPeer, onDirty }
142
- * @param {Function|null} [deps.makeSync] Factory de sync (createSync). Si es null,
143
- * los métodos sync* lanzan "sync not ready" (modo headless / sin Drive).
144
- * @returns {Promise<{ handlers:Object, get me():Object, sync:Object|null,
145
- * onSyncStatus(fn):void }>}
216
+ /*
217
+ * Crea el núcleo de identidad sobre los backends inyectados: `createIdentityCore`, más abajo.
218
+ * Las dependencias (`deps`) están descritas en el tipo `CoreDeps`.
146
219
  */
147
220
  // Campos personales estándar del perfil (escalares fijos), con su cap de longitud.
148
221
  // Cada uno tiene un flag `<campo>Visible` (booleano) para mostrar/ocultar al compartir.
222
+ /** @type {Array<[string, number]>} */
149
223
  const STD_FIELD_CAPS = [
150
224
  ['nombres', 60], ['apellidos', 60], ['email', 120], ['telefono', 40], ['direccion', 200]
151
225
  ]
@@ -165,8 +239,14 @@ const STD_FIELDS_SENSITIVE = new Set(['telefono', 'direccion'])
165
239
  * Sensibles (teléfono, dirección) OCULTOS salvo que su marca diga que sí, explícitamente.
166
240
  * El resto se comparte salvo que digas que no.
167
241
  */
242
+ /**
243
+ * @param {Record<string, any>} [m]
244
+ * @returns {Record<string, 'public' | 'private'>}
245
+ */
168
246
  export function profileFieldClasses (m = {}) {
247
+ /** @type {Record<string, 'public' | 'private'>} */
169
248
  const out = {}
249
+ /** @param {boolean} esPublico @returns {'public' | 'private'} */
170
250
  const clase = (esPublico) => (esPublico ? 'public' : 'private')
171
251
  if (m.nickname) out.nickname = clase(true)
172
252
  if (m.avatar) out.avatar = clase(m.avatarVisible !== false)
@@ -179,7 +259,12 @@ export function profileFieldClasses (m = {}) {
179
259
 
180
260
  // Sanea un patch de perfil (avatar/links/fields/nickname + campos estándar). Cada link/field
181
261
  // lleva `visible` (oculto = no se comparte). Caps de tamaño para no inflar el `me`. Los ids los pone la UI.
262
+ /**
263
+ * @param {Record<string, any>} [patch]
264
+ * @returns {Record<string, any>}
265
+ */
182
266
  function sanitizeProfilePatch (patch = {}) {
267
+ /** @type {Record<string, any>} */
183
268
  const out = {}
184
269
  if (typeof patch.nickname === 'string') out.nickname = patch.nickname.slice(0, 40)
185
270
  // Campos personales estándar (Nombres/Apellidos/Correo/Teléfono/Dirección) + su visibilidad.
@@ -193,7 +278,7 @@ function sanitizeProfilePatch (patch = {}) {
193
278
  if (typeof patch.avatarVisible === 'boolean') out.avatarVisible = patch.avatarVisible
194
279
  if (Array.isArray(patch.links)) {
195
280
  // Filtra vacíos ANTES del tope: un draft vacío no debe consumir cupo ni desplazar un enlace real.
196
- out.links = patch.links.slice(0, 100).map((l) => ({
281
+ out.links = patch.links.slice(0, 100).map((/** @type {any} */ l) => ({
197
282
  id: String(l?.id || '').slice(0, 24),
198
283
  type: String(l?.type || 'web').slice(0, 16),
199
284
  value: String(l?.value || '').slice(0, 200),
@@ -201,7 +286,7 @@ function sanitizeProfilePatch (patch = {}) {
201
286
  })).filter((l) => l.value).slice(0, 30)
202
287
  }
203
288
  if (Array.isArray(patch.fields)) {
204
- out.fields = patch.fields.slice(0, 20).map((f) => ({
289
+ out.fields = patch.fields.slice(0, 20).map((/** @type {any} */ f) => ({
205
290
  id: String(f?.id || '').slice(0, 24),
206
291
  label: String(f?.label || '').slice(0, 40),
207
292
  value: String(f?.value || '').slice(0, 280),
@@ -218,6 +303,8 @@ function sanitizeProfilePatch (patch = {}) {
218
303
  * aplicación que pide sería la aplicación aprobándose a sí misma.
219
304
  *
220
305
  * Si no se inyecta, no se concede nada nuevo: sin forma de preguntar, la respuesta es no.
306
+ *
307
+ * @param {CoreDeps} deps
221
308
  */
222
309
  export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null, keyStore: hostKeyStore = null, sessionKv = null, removeAccountOnExpulsion = true, keyLock = null, askConsent = null }) {
223
310
  const {
@@ -250,21 +337,29 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
250
337
  const VOLATILE_CLAIM = 'dotrino.identity.volatile.claim' // en sessionKv: la de ESTA pestaña
251
338
  const VOLATILE_STALE_MS = 90_000
252
339
  const VOLATILE_BEAT_MS = 20_000
340
+ /** @type {Set<string | null>} */
253
341
  const volatilePids = new Set()
342
+ /** @type {ProfileEntry[]} */
254
343
  let volatileProfiles = []
344
+ /** @type {ReturnType<typeof setInterval> | null} */
255
345
  let volatileBeat = null
256
346
  const rawKv = hostKv
257
347
  const keyStore = hostKeyStore
258
348
 
349
+ /** @returns {Record<string, number>} */
259
350
  const loadVolatile = () => { try { return JSON.parse(hostKv.getItem(VOLATILE_STORAGE) || '{}') || {} } catch (_) { return {} } }
351
+ /** @param {Record<string, number>} m */
260
352
  const saveVolatile = (m) => hostKv.setItem(VOLATILE_STORAGE, JSON.stringify(m))
353
+ /** @param {string} pid */
261
354
  const beatVolatile = (pid) => { const m = loadVolatile(); m[pid] = Date.now(); saveVolatile(m) }
355
+ /** @param {string} pid */
262
356
  const keepBeating = (pid) => {
263
357
  if (volatileBeat) clearInterval(volatileBeat)
264
358
  beatVolatile(pid)
265
- volatileBeat = setInterval(() => beatVolatile(pid), VOLATILE_BEAT_MS)
359
+ const beat = setInterval(() => beatVolatile(pid), VOLATILE_BEAT_MS)
360
+ volatileBeat = beat
266
361
  // En el navegador, que el latido no impida cerrar nada.
267
- try { volatileBeat.unref?.() } catch (_) {}
362
+ try { beat.unref?.() } catch (_) {}
268
363
  }
269
364
 
270
365
  // ----- multi-perfil: kv SCOPEADO por el perfil activo -----
@@ -272,20 +367,26 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
272
367
  // namespacean transparentemente bajo `dotrino.identity.p.<currentPid>.*`. Las dos claves
273
368
  // globales (lista de perfiles + activo) usan el kv crudo. Cambiar de perfil = setear el
274
369
  // activo; la app recarga la página y re-inicializa con el nuevo (no reactivo, por diseño).
370
+ /** @type {string | null} */
275
371
  let currentPid = null
372
+ /** @param {string} k @returns {string} */
276
373
  const _scoped = (k) => (!currentPid || k === PROFILES_STORAGE || k === CURRENT_STORAGE)
277
374
  ? k : k.replace(/^dotrino\.identity\./, `dotrino.identity.p.${currentPid}.`)
375
+ /** @type {Kv} */
278
376
  const kv = {
279
377
  getItem: (k) => rawKv.getItem(_scoped(k)),
280
378
  setItem: (k, v) => rawKv.setItem(_scoped(k), v),
281
379
  removeItem: (k) => rawKv.removeItem(_scoped(k))
282
380
  }
381
+ /** @returns {ProfileEntry[]} */
283
382
  const loadProfiles = () => {
383
+ /** @type {ProfileEntry[]} */
284
384
  let list = []
285
385
  try { list = JSON.parse(hostKv.getItem(PROFILES_STORAGE) || '[]') || [] } catch { list = [] }
286
386
  return volatileProfiles.length ? [...list, ...volatileProfiles] : list
287
387
  }
288
388
  /** Lo volátil se queda en memoria; al disco va solo el resto. */
389
+ /** @param {ProfileEntry[]} list */
289
390
  const saveProfiles = (list) => {
290
391
  if (volatilePids.size) volatileProfiles = list.filter((p) => volatilePids.has(p.id))
291
392
  hostKv.setItem(PROFILES_STORAGE, JSON.stringify(list.filter((p) => !volatilePids.has(p.id))))
@@ -303,8 +404,10 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
303
404
  // entrada), y en la bóveda es UN directorio por perfil, donde esa lista está vacía y
304
405
  // no hay ninguna entrada que marcar. El kv es lo único que existe siempre y ya está
305
406
  // acotado al perfil abierto, así que ahí va la marca de la bóveda.
407
+ /** @param {string | null} [pid] @returns {boolean} */
306
408
  const isPendingJoin = (pid = currentPid) =>
307
409
  kv.getItem(PENDING_JOIN_STORAGE) === '1' || !!loadProfiles().find((p) => p.id === pid)?.pendingJoin
410
+ /** @param {string | null} [pid] */
308
411
  const clearPendingJoin = (pid = currentPid) => {
309
412
  try { kv.removeItem(PENDING_JOIN_STORAGE) } catch (_) {}
310
413
  const list = loadProfiles(); const e = list.find((p) => p.id === pid)
@@ -318,13 +421,20 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
318
421
  // kv, se importa como no extractable y se BORRA el plano. Sin keyStore
319
422
  // (Node/tests) se conserva el comportamiento kv anterior.
320
423
 
424
+ /** @type {Record<'sign' | 'enc', { algo: EcKeyImportParams, privUses: KeyUsage[], pubUses: KeyUsage[], pairUses: KeyUsage[] }>} */
321
425
  const ALGO_OF = {
322
426
  sign: { algo: { name: 'ECDSA', namedCurve: 'P-256' }, privUses: ['sign'], pubUses: ['verify'], pairUses: ['sign', 'verify'] },
323
427
  enc: { algo: { name: 'ECDH', namedCurve: 'P-256' }, privUses: ['deriveBits', 'deriveKey'], pubUses: [], pairUses: ['deriveBits', 'deriveKey'] }
324
428
  }
325
429
 
430
+ /**
431
+ * @param {'sign' | 'enc'} kind
432
+ * @param {string} storageKey
433
+ * @returns {Promise<LoadedPair>}
434
+ */
326
435
  async function loadOrCreatePair (kind, storageKey) {
327
436
  const { algo, privUses, pubUses, pairUses } = ALGO_OF[kind]
437
+ /** @param {JsonWebKey} jwk */
328
438
  const importPub = (jwk) => crypto.subtle.importKey('jwk', jwk, algo, true, pubUses)
329
439
  if (keyStore) {
330
440
  const name = _scoped(storageKey)
@@ -399,6 +509,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
399
509
  * bóveda cerrada no podía ni cifrar la lista de variables de la consola. Le pasó a la
400
510
  * alojada, cuya identidad nace con el candado ya abierto (2026-10-27).
401
511
  */
512
+ /** @param {string} storageKey @param {JsonWebKey} privateJwk @param {JsonWebKey} publicJwk @returns {Promise<void>} */
402
513
  async function guardarPar (storageKey, privateJwk, publicJwk) {
403
514
  if (storageKey === KEY_STORAGE && keyLock?.seal) {
404
515
  const sealed = await keyLock.seal(JSON.stringify(privateJwk))
@@ -471,12 +582,16 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
471
582
  return {}
472
583
  }
473
584
  }
585
+ /** @param {Record<string, number>} obj */
474
586
  function saveNonces (obj) { kv.setItem(NONCE_STORAGE, JSON.stringify(obj)) }
587
+ /** @param {string} nonce */
475
588
  function rememberNonce (nonce) { const o = loadNonces(); o[nonce] = Date.now(); saveNonces(o) }
589
+ /** @param {string} nonce */
476
590
  function isFreshNonce (nonce) { return Object.prototype.hasOwnProperty.call(loadNonces(), nonce) }
477
591
 
478
592
  // ----- delegaciones de capacidad emitidas + revocaciones (kv-backed) -----
479
593
 
594
+ /** @param {string} key @returns {Record<string, any>} */
480
595
  function loadJson (key) { try { return JSON.parse(kv.getItem(key) || '{}') || {} } catch (_) { return {} } }
481
596
 
482
597
  // YA NO SE PODA NADA, y el motivo es que la poda existía por el reloj.
@@ -493,6 +608,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
493
608
  // los 30 días porque para entonces el papel estaba vencido seguro, y sin vencimiento
494
609
  // olvidar una revocación lo resucita.
495
610
  const loadDelegations = () => loadJson(DELEGATIONS_STORAGE)
611
+ /** @param {Record<string, any>} o */
496
612
  const saveDelegations = (o) => kv.setItem(DELEGATIONS_STORAGE, JSON.stringify(o))
497
613
 
498
614
  /**
@@ -504,6 +620,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
504
620
  function loadRevocations () {
505
621
  return loadJson(REVOCATIONS_STORAGE)
506
622
  }
623
+ /** @param {Record<string, any>} o */
507
624
  const saveRevocations = (o) => kv.setItem(REVOCATIONS_STORAGE, JSON.stringify(o))
508
625
 
509
626
  /**
@@ -512,10 +629,12 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
512
629
  * Solo toca las listas locales: avisar al aparato es cosa del mostrador de enrolamiento,
513
630
  * que es quien puede firmar la orden de autoborrado.
514
631
  */
632
+ /** @param {string} sub @param {string | null} [keepNonce] @returns {string[]} */
515
633
  function revokePriorCertsFor (sub, keepNonce) {
516
634
  const store = loadDelegations()
517
635
  const rev = loadRevocations()
518
636
  const now = Date.now()
637
+ /** @type {string[]} */
519
638
  const hit = []
520
639
  for (const [nonce, d] of Object.entries(store)) {
521
640
  if (nonce === keepNonce || d?.sub !== sub || d?.revokedAt) continue
@@ -529,7 +648,9 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
529
648
 
530
649
  // ----- emparejamiento con el vault del usuario (este dispositivo enrolado) -----
531
650
  // Canal de eventos 'vault' (p.ej. el código a tipear durante el emparejamiento).
651
+ /** @type {Set<(payload: any) => void>} */
532
652
  const vaultListeners = new Set()
653
+ /** @param {Record<string, any>} p */
533
654
  const emitVault = (p) => { for (const fn of vaultListeners) { try { fn(p) } catch (_) {} } }
534
655
 
535
656
  /**
@@ -579,7 +700,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
579
700
  removingAccount = true
580
701
  const gone = currentPid
581
702
  try { await purgeProfile(gone) } catch (e) {
582
- emitVault({ phase: 'account-removed', removed: gone, error: e?.message || String(e) })
703
+ emitVault({ phase: 'account-removed', removed: gone, error: /** @type {any} */ (e)?.message || String(e) })
583
704
  return
584
705
  }
585
706
  // Y ya está: qué cuenta queda puesta lo resuelve el ARRANQUE al recargar, que es donde
@@ -596,6 +717,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
596
717
  * Ojo: no es «cambiar de cuenta» de cara a las apps (eso exige recargar, multi-perfil no
597
718
  * es reactivo). Es dejar esta identidad coherente consigo misma antes de contestar.
598
719
  */
720
+ /** @param {string} pid */
599
721
  async function openProfileInMemory (pid) {
600
722
  currentPid = pid
601
723
  // Una cuenta volátil no deja rastro: si escribiera aquí, al cerrar la pestaña el
@@ -607,10 +729,12 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
607
729
  keypair = await loadOrCreateKeypair(); publickeyJwkStr = JSON.stringify(keypair.publicJwk)
608
730
  encKeypair = await loadOrCreateEncKeypair(); encPublickeyJwkStr = JSON.stringify(encKeypair.publicJwk)
609
731
  const saved = loadMe()
610
- me = (saved && saved.publickey === publickeyJwkStr)
732
+ /** @type {Record<string, any>} */
733
+ const abierto = (saved && saved.publickey === publickeyJwkStr)
611
734
  ? { ...saved, encryptionPubkey: encPublickeyJwkStr }
612
735
  : { publickey: publickeyJwkStr, encryptionPubkey: encPublickeyJwkStr }
613
- return { id: pid, name: me.nickname || '', pubkey: publickeyJwkStr }
736
+ me = abierto
737
+ return { id: pid, name: abierto.nickname || '', pubkey: publickeyJwkStr }
614
738
  }
615
739
 
616
740
  /**
@@ -622,16 +746,18 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
622
746
  * que no eran de nadie y la tuya sin abrir. La cuenta que se descarta es siempre una
623
747
  * recién creada por `vaultPair`, así que no hay nada dentro que perder.
624
748
  */
749
+ /** @param {string} pid @param {string | null} backTo */
625
750
  async function discardBornProfile (pid, backTo) {
626
751
  try {
627
752
  await purgeProfile(pid)
628
753
  if (backTo && loadProfiles().some((p) => p.id === backTo)) await openProfileInMemory(backTo)
629
754
  } catch (e) {
630
- console.warn('[identity] could not discard the account born for the pairing:', e?.message || e)
755
+ console.warn('[identity] could not discard the account born for the pairing:', /** @type {any} */ (e)?.message || e)
631
756
  }
632
757
  }
633
758
 
634
759
  /** El certificado de bóveda guardado en OTRA cuenta de este dispositivo (sin abrirla). */
760
+ /** @param {string} pid @returns {VaultLink | null} */
635
761
  const vaultCertOf = (pid) => {
636
762
  try {
637
763
  const raw = rawKv.getItem(VAULT_CERT_STORAGE.replace(/^dotrino\.identity\./, `dotrino.identity.p.${pid}.`))
@@ -658,6 +784,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
658
784
  * su contraseña; sin la frase no hay con qué, y se contesta `profile-locked` en vez de
659
785
  * fingir que no existe.
660
786
  */
787
+ /** @param {string} pid @returns {Promise<DeviceKey>} */
661
788
  async function signerForProfile (pid) {
662
789
  const nombre = KEY_STORAGE.replace(/^dotrino\.identity\./, `dotrino.identity.p.${pid}.`)
663
790
  if (keyStore) {
@@ -687,6 +814,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
687
814
  * Mismas tres reglas que allí: no se mueve `currentPid`, no se genera ninguna llave (si no
688
815
  * está, se dice) y una cuenta sellada bajo su contraseña se contesta `profile-locked`.
689
816
  */
817
+ /** @param {string | null} pid @returns {Promise<any>} */
690
818
  async function encKeyForProfile (pid) {
691
819
  if (pid === currentPid) return encKeypair?.privateKey || null
692
820
  const { algo, privUses } = ALGO_OF.enc
@@ -715,11 +843,15 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
715
843
  * Lo que no se puede abrir se dice (`ctxError`) en vez de quedarse como un pedido sin
716
844
  * comando: son cosas distintas y en la pantalla hay que poder distinguirlas.
717
845
  */
846
+ /** @param {any} items @param {string | null} pid */
718
847
  async function abrirContextos (items, pid) {
719
848
  if (!Array.isArray(items) || !items.length) return items
849
+ /** @type {any} */
720
850
  let priv = null
851
+ /** @type {string | null} */
721
852
  let fallo = null
722
- try { priv = await encKeyForProfile(pid) } catch (e) { fallo = e?.code || 'no-key' }
853
+ try { priv = await encKeyForProfile(pid) } catch (e) { fallo = /** @type {any} */ (e)?.code || 'no-key' }
854
+ /** @type {any[]} */
723
855
  const salida = []
724
856
  for (const raw of items) {
725
857
  const { ctxWrap, ctxEnvelope, ...it } = raw || {}
@@ -729,13 +861,14 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
729
861
  const cek = await Content.openWrap({ wrap: ctxWrap, myEncPrivateKey: priv })
730
862
  salida.push({ ...it, ctx: JSON.parse(await Content.decryptWithCek({ cek, envelope: ctxEnvelope })) })
731
863
  } catch (e) {
732
- salida.push({ ...it, ctxError: e?.code || 'cannot-open' })
864
+ salida.push({ ...it, ctxError: /** @type {any} */ (e)?.code || 'cannot-open' })
733
865
  }
734
866
  }
735
867
  return salida
736
868
  }
737
869
 
738
870
  /** La cuenta de este dispositivo que YA está emparejada con la bóveda `master`, si la hay. */
871
+ /** @param {string | null | undefined} master */
739
872
  const profilePairedWith = (master) => {
740
873
  if (!master) return null
741
874
  return loadProfiles().find((p) => vaultCertOf(p.id)?.master === master) || null
@@ -745,6 +878,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
745
878
  * Borra un perfil y todo lo suyo. Sin preguntas: el freno de «no te quedes sin ninguna»
746
879
  * es de la interfaz y vive en `deleteProfile`.
747
880
  */
881
+ /** @param {string | null} id */
748
882
  async function purgeProfile (id) {
749
883
  const list = loadProfiles().filter((p) => p.id !== id)
750
884
  saveProfiles(list)
@@ -783,6 +917,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
783
917
  * DEGRADAR: avisar a la app de que la bóveda nos está rechazando, y que sea el usuario
784
918
  * quien decida. El borrado real llega por `vault.revoked` firmado (ver `wipeVaultLink`).
785
919
  */
920
+ /** @param {any} e @returns {never} */
786
921
  const handleVaultError = (e) => {
787
922
  if (e && /\brevoked\b/.test(e.message || '')) emitVault({ phase: 'rejected', reason: e.message })
788
923
  throw e
@@ -797,13 +932,14 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
797
932
  *
798
933
  * Solo lo suyo: sin cert o sin `vault:approve` en ese cert, no hay nada que hacer aquí.
799
934
  */
935
+ /** @param {string} pid @param {{ op?: string, id?: string }} [args] */
800
936
  async function approvalsDeOtroPerfil (pid, { op, id } = {}) {
801
937
  if (!loadProfiles().some((p) => p.id === pid)) throw Object.assign(new Error('that profile does not exist on this device'), { code: 'no-profile' })
802
938
  const v = vaultCertOf(pid)
803
939
  if (!v?.cert) throw Object.assign(new Error('that profile is not paired with a vault'), { code: 'not-paired' })
804
940
  if (!(v.cert.scope || []).includes('vault:approve')) throw Object.assign(new Error('that profile does not approve requests'), { code: 'no-approve' })
805
941
  const device = await signerForProfile(pid)
806
- const r = await remoteApproval({ acta: actaOfProfile(pid), master: v.master, proxy: v.proxy, device, cert: v.cert, op, id })
942
+ const r = await remoteApproval({ acta: actaOfProfile(pid), master: v.master, proxy: v.proxy, device, cert: v.cert, op: /** @type {string} */ (op), id })
807
943
  // Y EL COMANDO SE ABRE TAMBIÉN AQUÍ, con la llave de ESA cuenta. Sin esto los pedidos de
808
944
  // las demás cuentas se veían sin comando —el dato por el que se mira la pantalla— y el
809
945
  // fallo era mudo: llegaban con su sobre cerrado y nadie lo abría.
@@ -812,8 +948,10 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
812
948
  }
813
949
 
814
950
  /** Id estable y corto de una llave de cifrado: con esto se indexan las envolturas. */
951
+ /** @param {string} encPub */
815
952
  const encKeyId = async (encPub) => (await pubkeyIdOf(encPub)).slice(0, 16)
816
953
 
954
+ /** @returns {VaultLink | null} */
817
955
  const loadVaultCert = () => { try { return JSON.parse(kv.getItem(VAULT_CERT_STORAGE) || 'null') } catch (_) { return null } }
818
956
 
819
957
  /**
@@ -827,11 +965,14 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
827
965
  * aparte», y fingirlo haría creer, por ejemplo, que lo suyo está respaldado en otro sitio.
828
966
  * Lo pone quien levanta la bóveda (`setSelfVault`) y lo quita al pararla.
829
967
  */
968
+ /** @type {{ cert: any, proxy: string } | null} */
830
969
  let selfLink = null
831
970
  /** Lo que se espera a una bóveda elegida: una alojada dormida arranca antes de contestar. */
832
971
  const VAULT_WAKE_MS = 45000
972
+ /** @type {(() => void) | null} */
833
973
  let selfLinkOff = null
834
974
  /** El enlace con el que administrar: el emparejamiento si lo hay, y si no, la bóveda local. */
975
+ /** @returns {{ v: VaultLink, device: DeviceKey, self: boolean } | null} */
835
976
  const adminLink = () => {
836
977
  const v = loadVaultCert(); const device = loadVaultDevice()
837
978
  if (v?.cert && device) return { v, device, self: false }
@@ -848,11 +989,14 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
848
989
  // porque el iframe no ve si está dentro de una extensión o de la app nativa, y viaja con
849
990
  // cada pedido firmado a la bóveda para que su lista lo enseñe al día. Sin página que lo
850
991
  // diga (Node, un cliente viejo) no se manda nada: mejor ningún dato que uno equivocado.
992
+ /** @type {{ kind: string, os: string, name: string } | null} */
851
993
  let pageMachine = null
994
+ /** @returns {DeviceKey | null} */
852
995
  const loadVaultDevice = () => {
853
996
  const d = loadVaultDeviceKey()
854
997
  return d && pageMachine ? { ...d, machine: pageMachine } : d
855
998
  }
999
+ /** @returns {DeviceKey | null} */
856
1000
  const loadVaultDeviceKey = () => {
857
1001
  try {
858
1002
  const d = JSON.parse(kv.getItem(VAULT_DEVICE_STORAGE) || 'null')
@@ -892,9 +1036,13 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
892
1036
  // Separar por `onBehalfOf` no le da a nadie más de lo que tenía: el nombre lo pone el
893
1037
  // origen, así que un origen que mintiera solo conseguiría una concesión aparte —vacía—,
894
1038
  // nunca la de otro origen. `|` no aparece en un origen, así que la clave no es ambigua.
1039
+ /** @param {string} origin @param {string | null | undefined} onBehalfOf @returns {string} */
895
1040
  const grantKey = (origin, onBehalfOf) => onBehalfOf ? `${origin}|${onBehalfOf}` : origin
1041
+ /** @param {unknown} onBehalfOf @returns {string} */
896
1042
  const behalfName = (onBehalfOf) => onBehalfOf ? String(onBehalfOf).slice(0, 60) : ''
1043
+ /** @returns {Record<string, { scopes: string[], at?: number, lastUsed?: number, onBehalfOf?: string }>} */
897
1044
  const loadGrants = () => {
1045
+ /** @type {Record<string, any>} */
898
1046
  let g
899
1047
  try { g = JSON.parse(kv.getItem(GRANTS_STORAGE) || '{}') } catch (_) { return {} }
900
1048
  // MIGRACIÓN DECLARADA (identity 0.93.0) — quitar después del 2026-10-17.
@@ -904,22 +1052,28 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
904
1052
  for (const k of Object.keys(g)) if (!k.includes('|') && g[k]?.onBehalfOf) delete g[k]
905
1053
  return g
906
1054
  }
1055
+ /** @param {Record<string, any>} g */
907
1056
  const saveGrants = (g) => { try { kv.setItem(GRANTS_STORAGE, JSON.stringify(g)) } catch (_) {} }
908
1057
  /** Lo concedido a un origen (y a nombre de quién pide), hoy. */
1058
+ /** @param {string} key @returns {string[]} */
909
1059
  const grantedTo = (key) => (loadGrants()[key]?.scopes) || []
910
1060
 
1061
+ /** @returns {Acta | null} */
911
1062
  const loadActa = () => { try { return JSON.parse(kv.getItem(ACTA_STORAGE) || 'null') } catch (_) { return null } }
912
1063
  /** El acta guardada de OTRO perfil de este aparato (la del activo es `loadActa`). Dice a qué bóvedas sellarle. */
1064
+ /** @param {string} pid @returns {Acta | null} */
913
1065
  const actaOfProfile = (pid) => {
914
1066
  if (pid === currentPid) return loadActa()
915
1067
  try { return JSON.parse(rawKv.getItem(`dotrino.identity.p.${pid}.acta`) || 'null') } catch (_) { return null }
916
1068
  }
1069
+ /** @param {Acta} a */
917
1070
  const saveActa = (a) => kv.setItem(ACTA_STORAGE, JSON.stringify(a))
918
1071
  // VENTANA DE RETENCIÓN (§1.3): el master conserva las últimas actas para que un miembro
919
1072
  // que estuvo apagado pueda comprobar el encadenamiento al volver. Un tercero no las
920
1073
  // necesita —le basta el snapshot actual—, pero entre miembros hay que poder verificar
921
1074
  // que la nueva desciende de la que uno tenía. Más viejo que la ventana ⇒ re-admitirse.
922
1075
  const ACTA_WINDOW = 50
1076
+ /** @returns {Acta[]} */
923
1077
  const loadHistory = () => { try { return JSON.parse(kv.getItem(ACTA_HISTORY_STORAGE) || '[]') || [] } catch (_) { return [] } }
924
1078
  /**
925
1079
  * LOS ESLABONES DE LA CADENA DE SELLADORES NO CADUCAN (dueño, 2026-08-31).
@@ -937,6 +1091,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
937
1091
  * No crecen: solo suman al añadir o quitar una bóveda, que casi nunca pasa. Un usuario
938
1092
  * normal guarda uno —el génesis— para siempre.
939
1093
  */
1094
+ /** @param {Acta | null | undefined} acta */
940
1095
  const pushHistory = (acta) => {
941
1096
  if (!acta) return
942
1097
  const h = loadHistory().filter((a) => a.seq !== acta.seq)
@@ -955,6 +1110,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
955
1110
  * Es lo que un extraño necesita para anclar en el `profileId`, y es corta a propósito —
956
1111
  * no lleva las actas de emparejar aparatos, que son casi todas.
957
1112
  */
1113
+ /** @returns {Acta[]} */
958
1114
  const sealerChain = () => {
959
1115
  const cur = loadActa()
960
1116
  if (!cur) return []
@@ -981,7 +1137,9 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
981
1137
  return [...antes, ...out]
982
1138
  }
983
1139
 
1140
+ /** @returns {import('./acta.js').RenounceRecord[]} */
984
1141
  const loadRenounces = () => { try { return JSON.parse(kv.getItem(RENOUNCE_STORAGE) || '[]') || [] } catch (_) { return [] } }
1142
+ /** @param {import('./acta.js').RenounceRecord[]} l */
985
1143
  const saveRenounces = (l) => kv.setItem(RENOUNCE_STORAGE, JSON.stringify(l))
986
1144
 
987
1145
  /** ¿Es ESTE dispositivo el master (el único que puede sellar)? */
@@ -997,15 +1155,18 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
997
1155
  * y devuelve su pública. Se llama en cada acta, porque esa llave rota con el acta.
998
1156
  * Un navegador no sella secretos: se queda en `null` y el acta no lleva llave.
999
1157
  */
1158
+ /** @type {(() => Promise<string | null>) | null} */
1000
1159
  let sealKeyProvider = null
1001
1160
 
1002
1161
  /** Sella con la llave del perfil (CryptoKey, puede ser no extractable). */
1162
+ /** @param {Acta} acta */
1003
1163
  const seal = (acta) => Acta.sealActa({ acta, privateKey: masterKey() })
1004
1164
 
1005
1165
  /**
1006
1166
  * Aplica cambios, sella y guarda. Solo funciona si este dispositivo es el master: es la
1007
1167
  * regla 1 del modelo, y `applyChanges` la vuelve a comprobar por su cuenta.
1008
1168
  */
1169
+ /** @param {any} changes @returns {Promise<Acta>} */
1009
1170
  async function sealChanges (changes) {
1010
1171
  const acta = loadActa()
1011
1172
  if (!acta) throw new Error('this profile has no record yet')
@@ -1030,8 +1191,9 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1030
1191
  * con todas las capacidades. `profileId` = la pubkey de este perfil → el perfil se llama
1031
1192
  * como la identidad que el usuario ya tenía, así que no hay nada que migrar.
1032
1193
  */
1194
+ /** @param {string} [label] @returns {Promise<Acta>} */
1033
1195
  async function ensureActa (label = '') {
1034
- if (loadActa()) return loadActa()
1196
+ if (loadActa()) return /** @type {Acta} */ (loadActa())
1035
1197
  const base = Acta.genesisActa({
1036
1198
  pub: publickeyJwkStr, encPub: encPublickeyJwkStr, label: label || me?.nickname || ''
1037
1199
  })
@@ -1040,7 +1202,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1040
1202
  try {
1041
1203
  const { generation } = await Content.makeGeneration({ members: base.members, gen: 1 })
1042
1204
  base.keyring = [generation]
1043
- } catch (e) { console.warn('[identity] could not create the content key:', e.message) }
1205
+ } catch (e) { console.warn('[identity] could not create the content key:', /** @type {any} */ (e).message) }
1044
1206
  const genesis = await seal(base)
1045
1207
  saveActa(genesis)
1046
1208
  // EL GÉNESIS VA A LA HISTORIA DESDE EL PRIMER DÍA. Es el ancla de la cadena de
@@ -1049,7 +1211,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1049
1211
  // guardaba lo que DEJABA de ser vigente, así que una cuenta que nunca cambió su acta
1050
1212
  // no tenía génesis guardado y su cadena salía vacía.
1051
1213
  pushHistory(genesis)
1052
- return loadActa()
1214
+ return /** @type {Acta} */ (loadActa())
1053
1215
  }
1054
1216
 
1055
1217
  // ----- CLAVE DE CONTENIDO del perfil (para que todos tus dispositivos lean lo mismo) -----
@@ -1076,13 +1238,16 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1076
1238
  * 3. clave nueva → no podrá abrir el contenido NUEVO. Lo que ya leyó no
1077
1239
  * vuelve: eso no se puede deshacer y no se promete.
1078
1240
  */
1241
+ /** @param {string} pub */
1079
1242
  async function removeDevice (pub) {
1080
1243
  if (!pub || typeof pub !== 'string') throw new Error('pub (device pubkey) required')
1081
1244
  // Si no es miembro (papeles de antes de que existiera el acta), no es un error: se
1082
1245
  // le quitan igual los certificados, que es lo que de verdad le abría la puerta.
1083
- const isMember = (loadActa().members || []).some((m) => m.pub === pub)
1084
- const acta = isMember ? await sealChanges([{ op: 'remove', pub }]) : loadActa()
1246
+ // Sin acta esto lanza (`TypeError`), igual que siempre: no hay de dónde quitar a nadie.
1247
+ const isMember = (/** @type {Acta} */ (loadActa()).members || []).some((m) => m.pub === pub)
1248
+ const acta = isMember ? await sealChanges([{ op: 'remove', pub }]) : /** @type {Acta} */ (loadActa())
1085
1249
  const nonces = revokePriorCertsFor(pub, null)
1250
+ /** @type {{ gen: number, sinLlave: Array<string | undefined> } | null} */
1086
1251
  let rotated = null
1087
1252
  try { rotated = await rotateCek() } catch (_) {}
1088
1253
  return { ok: true, seq: acta.seq, nonces, rotated, revokedAt: Date.now() }
@@ -1090,7 +1255,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1090
1255
 
1091
1256
  /** Rota la clave: generación nueva envuelta SOLO a los miembros actuales. */
1092
1257
  async function rotateCek () {
1093
- const acta = loadActa()
1258
+ const acta = /** @type {Acta} */ (loadActa())
1094
1259
  const gen = ((acta.keyring || []).at(-1)?.gen || 0) + 1
1095
1260
  const { generation, sinLlave } = await Content.makeGeneration({ members: acta.members, gen })
1096
1261
  await sealChanges([{ op: 'keyring', generation }])
@@ -1116,17 +1281,21 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1116
1281
  * cerrada no firma nada (`CLAUDE.md`, «la maestra tiene dos trabajos»), y cambiar el acta
1117
1282
  * al abrir es justo uno de ellos.
1118
1283
  */
1284
+ /** @param {number} [now] */
1119
1285
  async function pruneExpiredDevices (now = Date.now()) {
1120
1286
  if (!keypair?.privateKey) return { removed: [], seq: null }
1121
1287
  const acta = loadActa()
1122
1288
  if (!acta) return { removed: [], seq: null }
1123
1289
  const store = loadDelegations(); const rev = loadRevocations()
1290
+ /** @type {Map<string, any[]>} */
1124
1291
  const porSub = new Map()
1125
1292
  for (const d of Object.values(store)) {
1126
1293
  if (!d?.sub || d.revokedAt || rev[d.nonce]) continue
1127
- if (!porSub.has(d.sub)) porSub.set(d.sub, [])
1128
- porSub.get(d.sub).push(d)
1294
+ let lista = porSub.get(d.sub)
1295
+ if (!lista) { lista = []; porSub.set(d.sub, lista) }
1296
+ lista.push(d)
1129
1297
  }
1298
+ /** @param {any} d */
1130
1299
  const muerto = (d) => typeof d.seq !== 'number'
1131
1300
  const muertos = [...porSub]
1132
1301
  .filter(([sub, ds]) => sub !== publickeyJwkStr && ds.every(muerto))
@@ -1202,6 +1371,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1202
1371
  // esa cuenta no reconoce y el aparato quedaría fuera de su propio perfil.
1203
1372
 
1204
1373
  /** Lo que quedó anotado de un inicio de sesión con contraseña, para cerrarlo o enseñarlo. */
1374
+ /** @param {string} pid @returns {Record<string, any> | null} */
1205
1375
  const loginMetaOf = (pid) => {
1206
1376
  try {
1207
1377
  const raw = pid === currentPid
@@ -1214,8 +1384,8 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1214
1384
  const deviceIdDe = keyLabel
1215
1385
 
1216
1386
  /**
1217
- * @param {object} entrada lo que devuelve `loginWithPassword` del pilar
1218
- * @param {boolean} remember `false` = cuenta VOLÁTIL (se va con la pestaña)
1387
+ * @param {any} entrada lo que devuelve `loginWithPassword` del pilar (lo comprueba esta función)
1388
+ * @param {{ remember?: boolean, proxy?: string | null }} [opts] `remember: false` = cuenta VOLÁTIL (se va con la pestaña)
1219
1389
  */
1220
1390
  async function adoptLogin (entrada, { remember = false, proxy = null } = {}) {
1221
1391
  // LO MÍNIMO QUE ESTA CASA TIENE QUE COMPROBAR ANTES DE ADOPTAR NADA. Quien entró ya
@@ -1224,7 +1394,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1224
1394
  // se quedaría con una identidad que ningún acta reconoce — y sin forma de notarlo.
1225
1395
  const v = await Acta.verifyActa({ acta: entrada?.acta })
1226
1396
  if (!v.ok) throw Object.assign(new Error('the account record does not verify: ' + v.reason), { code: 'bad-record' })
1227
- if (!(entrada.acta.members || []).some((m) => m?.pub === entrada.publickey)) {
1397
+ if (!(entrada.acta.members || []).some((/** @type {any} */ m) => m?.pub === entrada.publickey)) {
1228
1398
  throw Object.assign(new Error('that key is not a member of the account record'), { code: 'not-a-member' })
1229
1399
  }
1230
1400
 
@@ -1245,6 +1415,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1245
1415
  // con `deriveBits` a secas), y aquí hace falta además `deriveKey`. Es lo mismo que ya
1246
1416
  // se hace al generar una propia — quién puede hacer qué con esta llave lo decide esta
1247
1417
  // casa, no una etiqueta que viajó dentro del paquete.
1418
+ /** @param {JsonWebKey} jwk @returns {JsonWebKey} */
1248
1419
  const sinTopes = (jwk) => { const { key_ops: _o, ...resto } = jwk || {}; return resto }
1249
1420
  if (keyStore?.importPair) {
1250
1421
  // DENTRO DE UNA APP NATIVA: la llave que entrega la bóveda la guarda la app (cifrada
@@ -1293,7 +1464,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1293
1464
  name: entrada.acta?.name || entrada.address, profileId: entrada.acta?.profileId || null
1294
1465
  }).then(
1295
1466
  () => emitVault({ phase: 'native-account', ok: true }),
1296
- (e) => { console.warn('[identity] the phone did not save the account: ' + e.message); emitVault({ phase: 'native-account', ok: false, code: e.code || 'native-error', reason: e.message }) }
1467
+ (/** @type {any} */ e) => { console.warn('[identity] the phone did not save the account: ' + e.message); emitVault({ phase: 'native-account', ok: false, code: e.code || 'native-error', reason: e.message }) }
1297
1468
  )
1298
1469
  }
1299
1470
  return { id: pid, name: entrada.user, address: entrada.address, user: entrada.user, sid: entrada.sid, volatile: !remember }
@@ -1308,16 +1479,18 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1308
1479
  }
1309
1480
 
1310
1481
  /** Deja de tener por nuestra una cuenta de paso: ni en la lista, ni reclamada, ni latiendo. */
1482
+ /** @param {string} pid */
1311
1483
  function forgetVolatile (pid) {
1312
1484
  volatilePids.delete(pid)
1313
1485
  volatileProfiles = volatileProfiles.filter((x) => x.id !== pid)
1314
1486
  const m = loadVolatile()
1315
1487
  if (m[pid]) { delete m[pid]; saveVolatile(m) }
1316
- try { if (sessionKv?.getItem(VOLATILE_CLAIM) === pid) sessionKv.removeItem(VOLATILE_CLAIM) } catch (_) {}
1488
+ try { if (sessionKv?.getItem(VOLATILE_CLAIM) === pid) /** @type {Kv} */ (sessionKv).removeItem(VOLATILE_CLAIM) } catch (_) {}
1317
1489
  if (volatileBeat) { clearInterval(volatileBeat); volatileBeat = null }
1318
1490
  }
1319
1491
 
1320
1492
  /** Borra una cuenta de paso —con sus llaves— y vuelve a la que este navegador tenía. */
1493
+ /** @param {string} pid */
1321
1494
  async function dropVolatile (pid) {
1322
1495
  forgetVolatile(pid)
1323
1496
  await purgeProfile(pid)
@@ -1335,6 +1508,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1335
1508
  * colgado esperándola—, pero borrar la cuenta de este navegador no lo es: eso pasa siempre.
1336
1509
  * La plaza que quede abierta allí se cierra desde la consola, y así está dicho en el diseño.
1337
1510
  */
1511
+ /** @param {Record<string, any> | null} meta @returns {Promise<Record<string, any>>} */
1338
1512
  async function closeLoginOn (meta) {
1339
1513
  if (!meta?.user || !meta?.sid) return { ok: false, reason: 'no-login' }
1340
1514
  let client = null
@@ -1355,8 +1529,8 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1355
1529
  }
1356
1530
  return { ok: false, reason: 'no-vault' }
1357
1531
  } catch (e) {
1358
- return { ok: false, reason: e?.code || 'no-answer' }
1359
- } finally { try { client?.close() } catch (_) {} }
1532
+ return { ok: false, reason: /** @type {any} */ (e)?.code || 'no-answer' }
1533
+ } finally { try { /** @type {any} */ (client)?.close() } catch (_) {} }
1360
1534
  }
1361
1535
 
1362
1536
  /**
@@ -1373,10 +1547,11 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1373
1547
  * acta sin preguntar: una cuenta con su contenido pasaba a colgar de otra en silencio —
1374
1548
  * justo la fusión de cuentas que el modelo prohíbe (§4). Eso se acabó.
1375
1549
  */
1550
+ /** @param {any} candidate */
1376
1551
  async function joinProfile (candidate) {
1377
1552
  const v = await Acta.verifyActa({ acta: candidate })
1378
1553
  if (!v.ok) return { joined: false, reason: 'invalid-record:' + v.reason }
1379
- if (!candidate.members.some((m) => m.pub === publickeyJwkStr)) {
1554
+ if (!candidate.members.some((/** @type {any} */ m) => m.pub === publickeyJwkStr)) {
1380
1555
  return { joined: false, reason: 'not-a-member' }
1381
1556
  }
1382
1557
  const current = loadActa()
@@ -1412,6 +1587,9 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1412
1587
  * cert contra la bóveda y entra a su cuenta. Aparte para que la decisión de CUÁL cuenta y
1413
1588
  * el deshacerla si esto falla vivan juntos arriba, y aquí solo quede el trámite.
1414
1589
  */
1590
+ /**
1591
+ * @param {{ qr: any, label?: string, machine?: any, account?: string | null, requireCaps?: string[] | null }} args
1592
+ */
1415
1593
  async function pairWithVault ({ qr, label = '', machine = undefined, account = null, requireCaps = null }) {
1416
1594
  // Usa la PROPIA llave de identidad de este navegador como dispositivo: el cert delega
1417
1595
  // TU identidad (P) desde la maestra M → una sola identidad (signData/identify/cert = P).
@@ -1441,7 +1619,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1441
1619
  name: res.account || res.acta?.name || '', profileId: res.acta?.profileId || null
1442
1620
  }).then(
1443
1621
  () => emitVault({ phase: 'native-account', ok: true }),
1444
- (e) => { console.warn('[identity] the phone did not save the account: ' + e.message); emitVault({ phase: 'native-account', ok: false, code: e.code || 'native-error', reason: e.message }) }
1622
+ (/** @type {any} */ e) => { console.warn('[identity] the phone did not save the account: ' + e.message); emitVault({ phase: 'native-account', ok: false, code: e.code || 'native-error', reason: e.message }) }
1445
1623
  )
1446
1624
  }
1447
1625
  pullProfileFromVault() // adoptar el perfil que ya viva en el vault (si hay)
@@ -1463,11 +1641,13 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1463
1641
  * la manda: entra solo si su hash es el `prev` de la siguiente que ya tengo, y se baja eslabón
1464
1642
  * a eslabón desde las que conozco. Nunca cambia la vigente: solo completa lo que hay detrás.
1465
1643
  */
1644
+ /** @param {any} actas */
1466
1645
  async function fillHistoryNow (actas) {
1467
1646
  const cur = loadActa()
1468
1647
  if (!cur || !Array.isArray(actas) || !actas.length) return { added: 0 }
1469
1648
  const known = new Map([...loadHistory(), cur].map((a) => [a.seq, a]))
1470
- const offered = new Map(actas.filter((a) => a && a.profileId === cur.profileId && typeof a.seq === 'number').map((a) => [a.seq, a]))
1649
+ /** @type {Map<number, any>} */
1650
+ const offered = new Map(actas.filter((/** @type {any} */ a) => a && a.profileId === cur.profileId && typeof a.seq === 'number').map((/** @type {any} */ a) => [a.seq, a]))
1471
1651
  let added = 0
1472
1652
  for (const s of [...known.keys()].sort((a, b) => b - a)) {
1473
1653
  let node = known.get(s)
@@ -1483,13 +1663,16 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1483
1663
  }
1484
1664
  return { added }
1485
1665
  }
1666
+ /** @param {any} actas */
1486
1667
  function fillHistory (actas) {
1487
1668
  const run = adoptQueue.then(() => fillHistoryNow(actas))
1488
1669
  adoptQueue = run.catch(() => {})
1489
1670
  return run
1490
1671
  }
1491
1672
 
1673
+ /** @param {any} chain */
1492
1674
  async function adoptChain (chain) {
1675
+ /** @type {any} */
1493
1676
  let last = null
1494
1677
  for (const a of [...(chain || [])].sort((x, y) => x.seq - y.seq)) {
1495
1678
  const r = await adoptActa(a)
@@ -1513,13 +1696,16 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1513
1696
  // estando en la #58, las dos se compararon contra la #58, y la #59 se guardó DESPUÉS — el acta
1514
1697
  // retrocedió y los aparatos con papel de la #60 recibían «stale-record». Con la fila, la
1515
1698
  // segunda se compara contra lo que dejó la primera, y una más vieja se rechaza.
1699
+ /** @type {Promise<unknown>} */
1516
1700
  let adoptQueue = Promise.resolve()
1701
+ /** @param {any} candidate */
1517
1702
  function adoptActa (candidate) {
1518
1703
  const run = adoptQueue.then(() => adoptActaNow(candidate))
1519
1704
  adoptQueue = run.catch(() => {})
1520
1705
  return run
1521
1706
  }
1522
1707
 
1708
+ /** @param {any} candidate */
1523
1709
  async function adoptActaNow (candidate) {
1524
1710
  const current = loadActa()
1525
1711
  const r = await Acta.canAdopt({ candidate, current })
@@ -1534,6 +1720,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1534
1720
  }
1535
1721
 
1536
1722
  /** Guarda la que gana y mira si este aparato sigue dentro (común a las dos formas de adoptar). */
1723
+ /** @param {Acta} candidate @param {string} reason */
1537
1724
  function installActa (candidate, reason) {
1538
1725
  saveActa(candidate)
1539
1726
  emitVault({ phase: 'acta', seq: candidate.seq, sealedBy: candidate.sealedBy, adopted: reason })
@@ -1560,12 +1747,13 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1560
1747
  * anclado a él cuando trae ancla.
1561
1748
  * Así toda la autoridad nace en el acta que ya tengo: una rama ajena no entra.
1562
1749
  */
1750
+ /** @param {any} sealerChain */
1563
1751
  async function adoptSealerChainNow (sealerChain) {
1564
1752
  const current = loadActa()
1565
1753
  if (!current) return { adopted: false, reason: 'no-current-record', seq: null }
1566
1754
  const links = (Array.isArray(sealerChain) ? sealerChain : [])
1567
- .filter((a) => a && a.profileId === current.profileId && typeof a.seq === 'number' && a.seq > current.seq)
1568
- .sort((a, b) => a.seq - b.seq)
1755
+ .filter((/** @type {any} */ a) => a && a.profileId === current.profileId && typeof a.seq === 'number' && a.seq > current.seq)
1756
+ .sort((/** @type {any} */ a, /** @type {any} */ b) => a.seq - b.seq)
1569
1757
  if (!links.length) return { adopted: false, reason: 'nothing-to-adopt', seq: current.seq }
1570
1758
  const first = await Acta.canAdopt({ candidate: links[0], current })
1571
1759
  if (!first.adopt) return { adopted: false, reason: 'sealer-chain:' + first.reason, seq: current.seq }
@@ -1584,6 +1772,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1584
1772
  for (const a of links.slice(0, -1)) pushHistory(a)
1585
1773
  return installActa(links[links.length - 1], 'sealer-chain')
1586
1774
  }
1775
+ /** @param {any} sealerChain */
1587
1776
  function adoptSealerChain (sealerChain) {
1588
1777
  const run = adoptQueue.then(() => adoptSealerChainNow(sealerChain))
1589
1778
  adoptQueue = run.catch(() => {})
@@ -1648,10 +1837,12 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1648
1837
 
1649
1838
  // ----- me (kv-backed) -----
1650
1839
 
1840
+ /** @returns {Record<string, any> | null} */
1651
1841
  function loadMe () {
1652
1842
  try { const raw = kv.getItem(ME_STORAGE); return raw ? JSON.parse(raw) : null }
1653
1843
  catch (_) { return null }
1654
1844
  }
1845
+ /** @param {Record<string, any>} next */
1655
1846
  function saveMe (next) {
1656
1847
  kv.setItem(ME_STORAGE, JSON.stringify(next))
1657
1848
  me = next
@@ -1660,6 +1851,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1660
1851
 
1661
1852
  // ----- endorsement verify / merge (sync) -----
1662
1853
 
1854
+ /** @param {any} env @returns {Promise<boolean>} */
1663
1855
  async function verifyEndorsement (env) {
1664
1856
  if (!env || typeof env !== 'object') return false
1665
1857
  const { subject, rating, notes, ratedBy, issuedAt, signature } = env
@@ -1669,6 +1861,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1669
1861
  catch { return false }
1670
1862
  }
1671
1863
 
1864
+ /** @param {Record<string, any>} localPeers @param {Record<string, any>} remotePeers */
1672
1865
  async function mergePeerMaps (localPeers, remotePeers) {
1673
1866
  const out = { ...localPeers }
1674
1867
  let changed = false
@@ -1749,6 +1942,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1749
1942
  }
1750
1943
  }
1751
1944
 
1945
+ /** @param {'sign' | 'enc'} kind @param {string} storageKey @param {JsonWebKey} privateJwk @param {JsonWebKey} publicJwk */
1752
1946
  async function adoptJwkPair (kind, storageKey, privateJwk, publicJwk) {
1753
1947
  const { algo, privUses } = ALGO_OF[kind]
1754
1948
  if (keyStore) {
@@ -1760,6 +1954,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1760
1954
  }
1761
1955
  }
1762
1956
 
1957
+ /** @param {any} merged */
1763
1958
  async function applyMergedFromSync (merged) {
1764
1959
  const localKeys = kv.getItem(KEY_STORAGE) || (keyStore && (await keyStore.get(_scoped(KEY_STORAGE)).catch(() => null)))
1765
1960
  if (!localKeys && merged.privateJwk && merged.publicJwk) {
@@ -1781,6 +1976,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1781
1976
  if (merged.peers && typeof merged.peers === 'object') setPeersDirect(merged.peers)
1782
1977
  }
1783
1978
 
1979
+ /** @param {any} local @param {any} remote */
1784
1980
  async function mergeForSync (local, remote) {
1785
1981
  if (!remote) return { merged: local, changed: false }
1786
1982
  const { merged: mergedPeers, changed } = await mergePeerMaps(local.peers || {}, remote.peers || {})
@@ -1799,17 +1995,26 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1799
1995
 
1800
1996
  // ----- runtime state -----
1801
1997
 
1802
- let keypair = null
1803
- let publickeyJwkStr = null
1804
- let encKeypair = null
1805
- let encPublickeyJwkStr = null
1998
+ // Las cuatro se rellenan al arrancar (`openProfileInMemory` y el final de este archivo),
1999
+ // ANTES de que se atienda ninguna petición: por eso su tipo no lleva `null`.
2000
+ /** @type {LoadedPair} */
2001
+ let keypair = /** @type {any} */ (null)
2002
+ /** @type {string} */
2003
+ let publickeyJwkStr = /** @type {any} */ (null)
2004
+ /** @type {LoadedPair} */
2005
+ let encKeypair = /** @type {any} */ (null)
2006
+ /** @type {string} */
2007
+ let encPublickeyJwkStr = /** @type {any} */ (null)
2008
+ /** @type {any} el respaldo en Drive (`createSync`), si lo hay */
1806
2009
  let sync = null
1807
- let me = null
2010
+ /** @type {Record<string, any>} el perfil: apodo, avatar, campos (se rellena al arrancar) */
2011
+ let me = /** @type {any} */ (null)
1808
2012
 
1809
2013
  // ----- handlers (idénticos a la versión iframe) -----
1810
2014
 
1811
2015
  // Merge de un patch de perfil en `me` (preserva lo demás), saneado. Refleja el nombre en la
1812
2016
  // meta del perfil (para el switcher). Devuelve el `me` resultante.
2017
+ /** @param {Record<string, any> | null | undefined} patch */
1813
2018
  function applyMeUpdate (patch) {
1814
2019
  const clean = sanitizeProfilePatch(patch || {})
1815
2020
  me = { ...(me || {}), ...clean, publickey: publickeyJwkStr, encryptionPubkey: encPublickeyJwkStr, updatedAt: Date.now() }
@@ -1835,10 +2040,13 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1835
2040
  * quien pregunta desde fuera. Lo que cambia es que ahora esa marca decide **cómo se
1836
2041
  * guarda** —en claro o en sobre— y no solo qué se enseña (`docs/datos-del-perfil.md` §2).
1837
2042
  *
2043
+ * @param {Record<string, any>} m
1838
2044
  * @returns {Array<{key:string, value:string, cls:'public'|'private'}>}
1839
2045
  */
1840
2046
  function profileFields (m) {
2047
+ /** @type {Array<{key:string, value:string, cls:'public'|'private'}>} */
1841
2048
  const out = []
2049
+ /** @param {string} key @param {unknown} value @param {boolean} esPublico */
1842
2050
  const add = (key, value, esPublico) => {
1843
2051
  if (typeof value !== 'string' || !value) return
1844
2052
  out.push({ key, value, cls: esPublico ? 'public' : 'private' })
@@ -1849,7 +2057,9 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1849
2057
  for (const [k, cls] of Object.entries(clases)) add(k, m[k], cls === 'public')
1850
2058
  // Enlaces y campos libres viajan como UN dato cada lista: son arrays y partirlos por
1851
2059
  // elemento haría que reordenarlos pareciera media docena de cambios.
2060
+ /** @param {any[] | null | undefined} arr */
1852
2061
  const visibles = (arr) => (arr || []).filter((x) => x.visible !== false).map(({ visible, ...r }) => r)
2062
+ /** @param {any[] | null | undefined} arr */
1853
2063
  const ocultos = (arr) => (arr || []).filter((x) => x.visible === false)
1854
2064
  if (Array.isArray(m.links)) {
1855
2065
  const v = visibles(m.links); if (v.length) add('links', JSON.stringify(v), true)
@@ -1873,12 +2083,14 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1873
2083
  * Solo se manda LO QUE CAMBIÓ: cada escritura estrena generación, y reescribir un dato
1874
2084
  * que no cambió llenaría el llavero y el histórico de ruido.
1875
2085
  */
2086
+ /** @param {VaultLink} v @param {DeviceKey} device */
1876
2087
  async function pushProfileFields (v, device) {
1877
2088
  const campos = profileFields(me || {})
1878
2089
  const pendientes = campos.filter((c) => lastPushedFields[c.key] !== c.cls + '\u0000' + c.value)
1879
2090
  if (!pendientes.length) return
1880
2091
 
1881
2092
  const privados = pendientes.filter((c) => c.cls === 'private')
2093
+ /** @type {any} */
1882
2094
  let destinatarios = null
1883
2095
  if (privados.length) {
1884
2096
  destinatarios = await remoteStore({
@@ -1891,6 +2103,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1891
2103
  }
1892
2104
 
1893
2105
  for (const c of pendientes) {
2106
+ /** @type {{ key: string, cls: string, value?: string, sobre?: any }} */
1894
2107
  const args = { key: c.key, cls: c.cls }
1895
2108
  if (c.cls === 'public') {
1896
2109
  args.value = c.value
@@ -1899,6 +2112,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1899
2112
  // navegador, sin que ninguna privada ande suelta.
1900
2113
  const cek = await Content.makeContentKey()
1901
2114
  const e = await Content.encryptWithCek({ cek, gen: 0, plaintext: c.value })
2115
+ /** @type {Record<string, any>} */
1902
2116
  const wraps = { '#recovery': await Content.wrapForMember({ cek, memberEncPub: destinatarios.recoveryPub }) }
1903
2117
  for (const m of destinatarios.members || []) {
1904
2118
  if (m.encPub) wraps[m.pub] = await Content.wrapForMember({ cek, memberEncPub: m.encPub })
@@ -1911,9 +2125,11 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1911
2125
  }
1912
2126
 
1913
2127
  /** Lo último que se consiguió empujar de cada dato, para no reescribir lo que no cambió. */
2128
+ /** @type {Record<string, string>} */
1914
2129
  const lastPushedFields = Object.create(null)
1915
2130
 
1916
- let profilePushTimer = null
2131
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
2132
+ let profilePushTimer
1917
2133
  /**
1918
2134
  * CÓMO FUE EL ÚLTIMO EMPUJÓN. Se guarda para que la UI pueda decir «esto no se guardó»
1919
2135
  * en vez de enseñar un perfil que solo existe en este aparato. Sin esto, el usuario ve
@@ -1923,6 +2139,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1923
2139
  // intentó» y «salió bien» se veían igual — un valor por defecto que dice que sí, en la
1924
2140
  // función que existe justamente para no tragarse el fallo. Quien pregunte tiene que
1925
2141
  // poder distinguir las tres cosas, y por eso son tres valores y no dos.
2142
+ /** @type {{ ok: boolean | null, at: number, error: string | null }} */
1926
2143
  let lastProfilePush = { ok: null, at: 0, error: null }
1927
2144
  function pushProfileToVault () {
1928
2145
  const v = loadVaultCert(); const device = loadVaultDevice()
@@ -1937,7 +2154,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1937
2154
  // edición se encontraba la bóveda cerrada otra vez, y mientras tanto el aparato
1938
2155
  // se quedaba con datos que nadie más tenía. Es exactamente lo que produjo el
1939
2156
  // «edito y no funciona, y cada dispositivo ve algo distinto».
1940
- lastProfilePush = { ok: false, at: Date.now(), error: e?.message || String(e) }
2157
+ lastProfilePush = { ok: false, at: Date.now(), error: /** @type {any} */ (e)?.message || String(e) }
1941
2158
  try { console.warn('[identity] the profile change did NOT reach the vault:', lastProfilePush.error) } catch (_) {}
1942
2159
  })
1943
2160
  }, 800) // debounce: ediciones seguidas = un solo push
@@ -1968,13 +2185,13 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1968
2185
  if (v?.cert && loadVaultDevice()) return // con papel, ya lo comprueba el camino normal
1969
2186
  const r = await remoteCheck({
1970
2187
  acta,
1971
- master: Acta.sealersOf(acta)[0] || null,
2188
+ master: /** @type {string} */ (Acta.sealersOf(acta)[0] || null),
1972
2189
  proxy: v?.proxy || 'wss://proxy.dotrino.com',
1973
2190
  device: { publickey: publickeyJwkStr, privateKey: masterKey() },
1974
2191
  onRevoked: wipeVaultLink
1975
2192
  })
1976
2193
  if (r?.error) console.warn('[identity] could not confirm membership with the vault:', r.error)
1977
- } catch (e) { console.warn('[identity] could not confirm membership with the vault:', e?.message || e) }
2194
+ } catch (e) { console.warn('[identity] could not confirm membership with the vault:', /** @type {any} */ (e)?.message || e) }
1978
2195
  }
1979
2196
 
1980
2197
  /**
@@ -1992,11 +2209,13 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
1992
2209
  * `links`/`fields` viajan como UN dato cada lista (y su gemelo privado), así que aquí se
1993
2210
  * vuelven a juntar con su marca de visibilidad — que es de dónde salió la separación.
1994
2211
  */
2212
+ /** @param {Record<string, any>} content @returns {boolean} */
1995
2213
  function applyPulledProfile (content) {
1996
2214
  const antes = JSON.stringify(me || {})
1997
2215
  const next = { ...(me || {}) }
2216
+ /** @param {string} json @param {boolean} visible */
1998
2217
  const lista = (json, visible) => {
1999
- try { return (JSON.parse(json) || []).map((x) => ({ ...x, visible })) } catch (_) { return [] }
2218
+ try { return (JSON.parse(json) || []).map((/** @type {any} */ x) => ({ ...x, visible })) } catch (_) { return [] }
2000
2219
  }
2001
2220
  for (const [k, v] of Object.entries(content)) {
2002
2221
  if (k === 'links' || k === 'fields' || k === 'links_private' || k === 'fields_private') continue
@@ -2038,9 +2257,10 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2038
2257
  if (me?.nickname || me?.avatar) pushProfileToVault()
2039
2258
  return
2040
2259
  }
2041
- const keyring = (b.wraps || []).map((w) => ({ gen: w.gen, wraps: { [publickeyJwkStr]: w.wrap } }))
2260
+ const keyring = (b.wraps || []).map((/** @type {any} */ w) => ({ gen: w.gen, wraps: { [publickeyJwkStr]: w.wrap } }))
2261
+ /** @type {Record<string, any>} */
2042
2262
  const content = {}
2043
- for (const [key, e] of Object.entries(entries)) {
2263
+ for (const [key, e] of Object.entries(/** @type {Record<string, any>} */ (entries))) {
2044
2264
  try {
2045
2265
  if (e.cls === 'public') { content[key] = e.pubv; continue }
2046
2266
  content[key] = await Content.decryptWithKeyring({
@@ -2066,7 +2286,9 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2066
2286
  const PWD_SESSION = 'dotrino.identity.pwd.proof'
2067
2287
  const PWD_ITER = 300000
2068
2288
  let locked = false
2289
+ /** @param {ArrayBuffer | Uint8Array} buf */
2069
2290
  const b64 = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf)))
2291
+ /** @param {unknown} password @param {string} saltB64 @param {number} iter @returns {Promise<string>} */
2070
2292
  async function derivePwd (password, saltB64, iter) {
2071
2293
  const salt = Uint8Array.from(atob(saltB64), (c) => c.charCodeAt(0))
2072
2294
  const km = await crypto.subtle.importKey('raw', new TextEncoder().encode(String(password)), 'PBKDF2', false, ['deriveBits'])
@@ -2104,6 +2326,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2104
2326
  * lo que ya estuviera concedido y nada más. **No se amplía en silencio**: sin respuesta,
2105
2327
  * la respuesta es no.
2106
2328
  */
2329
+ /** @param {unknown} origin @param {string[]} pedidos @param {unknown} [onBehalfOf] @returns {Promise<string[]>} */
2107
2330
  async function consentFor (origin, pedidos, onBehalfOf = null) {
2108
2331
  const org = String(origin || '').trim()
2109
2332
  const behalf = behalfName(onBehalfOf)
@@ -2157,6 +2380,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2157
2380
  refreshLockState()
2158
2381
  return { protected: !!loadPwd(), locked }
2159
2382
  },
2383
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2160
2384
  async unlockProfile ({ password }) {
2161
2385
  const pwd = loadPwd()
2162
2386
  if (!pwd) { locked = false; return { ok: true, locked: false } }
@@ -2183,6 +2407,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2183
2407
  return { ok: true, locked: false }
2184
2408
  },
2185
2409
  // Poner/cambiar contraseña (requiere estar desbloqueado; cambiar exige la actual vía unlock previo).
2410
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2186
2411
  async setProfilePassword ({ password }) {
2187
2412
  if (locked) throw new Error('profile locked')
2188
2413
  if (!password || String(password).length < 4) throw new Error('password must be at least 4 characters')
@@ -2205,6 +2430,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2205
2430
  return { nonce }
2206
2431
  },
2207
2432
 
2433
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2208
2434
  async signChallenge ({ nonce }) {
2209
2435
  if (!nonce || typeof nonce !== 'string') throw new Error('nonce required')
2210
2436
  const bytes = new TextEncoder().encode(nonce)
@@ -2212,6 +2438,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2212
2438
  return { nonce, publickey: publickeyJwkStr, encryptionPubkey: encPublickeyJwkStr, signature }
2213
2439
  },
2214
2440
 
2441
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2215
2442
  async verifyResponse ({ nonce, publickey, signature, encryptionPubkey }) {
2216
2443
  if (!nonce || !publickey || !signature) return { ok: false }
2217
2444
  if (!isFreshNonce(nonce)) return { ok: false, reason: 'nonce expired or unknown' }
@@ -2224,6 +2451,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2224
2451
  return { ok: true, publickey, encryptionPubkey: encryptionPubkey || null, peer }
2225
2452
  },
2226
2453
 
2454
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2227
2455
  async getPeer ({ publickey }) {
2228
2456
  const p = loadPeers()
2229
2457
  return p[publickey] || null
@@ -2235,16 +2463,19 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2235
2463
  * recibirla—, viaja con el libro de contactos a tu bóveda y a tus aparatos, y lo respeta
2236
2464
  * cada app que recibe mensajes (el messenger, el primero). Desbloquear deja `false` y no
2237
2465
  * borra el campo: así el cambio también llega a los demás aparatos.
2466
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2238
2467
  */
2239
2468
  async setBlocked ({ publickey, blocked }) {
2240
2469
  if (!publickey) throw new Error('publickey required')
2241
2470
  return upsertPeer(publickey, { blocked: !!blocked, changedAt: Date.now() })
2242
2471
  },
2243
2472
 
2473
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2244
2474
  async setNickname ({ publickey, nickname }) {
2245
2475
  return upsertPeer(publickey, { nickname: String(nickname || '').slice(0, 40) })
2246
2476
  },
2247
2477
 
2478
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2248
2479
  async setRating ({ publickey, rating, notes }) {
2249
2480
  const r = Math.max(0, Math.min(5, Number(rating) || 0))
2250
2481
  const safeNotes = typeof notes === 'string' ? notes.slice(0, 500) : ''
@@ -2256,6 +2487,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2256
2487
  return upsertPeer(publickey, { myRating, rating: r, notes: safeNotes })
2257
2488
  },
2258
2489
 
2490
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2259
2491
  async mergeEndorsements ({ subject, endorsements, askerPubkey }) {
2260
2492
  if (!subject || !Array.isArray(endorsements)) return { merged: 0, total: 0 }
2261
2493
  const peersMap = loadPeers()
@@ -2294,12 +2526,14 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2294
2526
  return { merged, total: all.length }
2295
2527
  },
2296
2528
 
2529
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2297
2530
  async getRatingsForSubject ({ subject }) {
2298
2531
  const p = loadPeers()
2299
2532
  const r = p[subject]
2300
2533
  return { mine: r?.myRating || null, endorsements: Array.isArray(r?.endorsements) ? r.endorsements : [] }
2301
2534
  },
2302
2535
 
2536
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2303
2537
  async recordQuery ({ askerPubkey, subject }) {
2304
2538
  if (!askerPubkey || askerPubkey === publickeyJwkStr) return null
2305
2539
  const peersMap = loadPeers()
@@ -2320,14 +2554,17 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2320
2554
  return Object.values(loadPeers()).sort((a, b) => (b.lastSeen || 0) - (a.lastSeen || 0))
2321
2555
  },
2322
2556
 
2557
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2323
2558
  async forgetPeer ({ publickey }) {
2324
2559
  const p = loadPeers()
2325
2560
  delete p[publickey]
2326
2561
  savePeers(p)
2327
2562
  },
2328
2563
 
2564
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2329
2565
  async addContact ({ publickey, nickname, encryptionPubkey, lastToken, notes }) {
2330
2566
  if (!publickey) throw new Error('publickey required')
2567
+ /** @type {Record<string, any>} */
2331
2568
  const patch = { isContact: true }
2332
2569
  if (nickname != null) patch.nickname = String(nickname).slice(0, 40)
2333
2570
  if (encryptionPubkey) patch.encryptionPubkey = encryptionPubkey
@@ -2336,14 +2573,17 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2336
2573
  return upsertPeer(publickey, patch)
2337
2574
  },
2338
2575
 
2576
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2339
2577
  async updateContact ({ publickey, patch }) {
2340
2578
  if (!publickey) throw new Error('publickey required')
2341
2579
  if (!patch || typeof patch !== 'object') return null
2580
+ /** @type {Record<string, any>} */
2342
2581
  const allowed = {}
2343
2582
  for (const k of ['nickname', 'encryptionPubkey', 'lastToken', 'contactNotes']) if (k in patch) allowed[k] = patch[k]
2344
2583
  return upsertPeer(publickey, allowed)
2345
2584
  },
2346
2585
 
2586
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2347
2587
  async removeContact ({ publickey }) {
2348
2588
  const p = loadPeers()
2349
2589
  const rec = p[publickey]
@@ -2365,6 +2605,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2365
2605
  * El `identify` del transporte es la excepción y SIEMPRE se firma en local: es lo que
2366
2606
  * identifica esta conexión ante el proxy, no una firma tuya de cara a nadie, y sin él
2367
2607
  * el dispositivo no podría ni hablar con la bóveda para pedirle que firme.
2608
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2368
2609
  */
2369
2610
  async signData ({ data }) {
2370
2611
  if (data == null) throw new Error('data required')
@@ -2447,6 +2688,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2447
2688
  * Retirar lo concedido a una aplicación. La próxima vez que pida, se vuelve a preguntar.
2448
2689
  * `onBehalfOf` es obligatorio para las que piden por otro (el puente): retirar el permiso
2449
2690
  * de UNA no puede quitárselo a todas las que entran por el mismo sitio.
2691
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2450
2692
  */
2451
2693
  async revokeGrant ({ origin, onBehalfOf } = {}) {
2452
2694
  const g = loadGrants()
@@ -2464,6 +2706,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2464
2706
  * Es una AFIRMACIÓN del origen, no un hecho comprobable — y por eso se enseña siempre
2465
2707
  * subordinado a él («sso.dotrino.com dice: Tal App»), nunca en su lugar. Quien
2466
2708
  * responde por lo que pase sigue siendo el origen.
2709
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2467
2710
  */
2468
2711
  async requestAssertion ({ audience, nonce, scopes, ttlMs, onBehalfOf, __origin } = {}) {
2469
2712
  if (typeof audience !== 'string' || !audience.trim()) throw new Error('audience required')
@@ -2473,8 +2716,10 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2473
2716
  const sub = acta?.profileId || publickeyJwkStr
2474
2717
  const granted = await consentFor(__origin, cleanScopes(scopes), onBehalfOf)
2475
2718
  const permitido = claimsAllowed(granted)
2719
+ /** @type {Record<string, unknown>} */
2476
2720
  const claims = {}
2477
2721
  if (permitido.size) {
2722
+ /** @type {Record<string, any>} */
2478
2723
  const pub = await handlers.publicMe()
2479
2724
  if (permitido.has('name')) {
2480
2725
  const n = pub.nickname || [pub.nombres, pub.apellidos].filter(Boolean).join(' ').trim()
@@ -2505,6 +2750,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2505
2750
  * `ttlMs`/`exp` se aceptan y se IGNORAN a propósito, para no romper a quien todavía los
2506
2751
  * pasa (el daemon, `enroll.js`). Reventar ahí dejaría sin emparejar a media cadena por
2507
2752
  * un parámetro que ya no significa nada.
2753
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2508
2754
  */
2509
2755
  async signDelegation ({ sub, scope, nonce, label, supersede }) {
2510
2756
  if (!sub || typeof sub !== 'string') throw new Error('sub (device pubkey) required')
@@ -2518,7 +2764,8 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2518
2764
  // `iss` se FUERZA a la propia maestra: el usuario no puede emitir cert para otro emisor.
2519
2765
  const cert = await signDelegationWith(masterKey(), publickeyJwkStr, { sub, scope, iat, seq: acta.seq, nonce: nonce || crypto.randomUUID() })
2520
2766
  const store = loadDelegations()
2521
- store[cert.nonce] = { nonce: cert.nonce, sub, scope, iat, seq: acta.seq, label: typeof label === 'string' ? label.slice(0, 60) : '' }
2767
+ // `nonce` va siempre: se pasa arriba, dado o recién sacado.
2768
+ store[/** @type {string} */ (cert.nonce)] = { nonce: cert.nonce, sub, scope, iat, seq: acta.seq, label: typeof label === 'string' ? label.slice(0, 60) : '' }
2522
2769
  saveDelegations(store)
2523
2770
  // UNA LLAVE, UN CERTIFICADO VIGENTE. Renovar emitía uno nuevo y dejaba vivo el
2524
2771
  // anterior: el mismo aparato salía dos veces en la lista (parecían dos máquinas) y,
@@ -2534,12 +2781,14 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2534
2781
  * Retira TODOS los certificados vigentes de un dispositivo (por su llave `sub`).
2535
2782
  * Es lo que significa «quitar el dispositivo»: revocar por `nonce` retira un papel,
2536
2783
  * no al aparato, que puede tener otros.
2784
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2537
2785
  */
2538
2786
  async revokeDevice ({ sub }) {
2539
2787
  if (!sub || typeof sub !== 'string') throw new Error('sub (device pubkey) required')
2540
2788
  return removeDevice(sub)
2541
2789
  },
2542
2790
 
2791
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2543
2792
  async revokeDelegation ({ nonce }) {
2544
2793
  if (!nonce || typeof nonce !== 'string') throw new Error('nonce required')
2545
2794
  const rev = loadRevocations()
@@ -2588,23 +2837,27 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2588
2837
  // no le corresponde»). Un acta guardada que no nombra la llave del propio perfil no es la de
2589
2838
  // su cuenta —una copia cruzada o de antes—, y sus bóvedas no son de ese perfil: no se listan.
2590
2839
  // Lo mismo el papel: solo vale el que se emitió para la llave de ese perfil.
2840
+ /** @param {string} pid @param {string | null} mine @param {string | null} certMaster */
2591
2841
  const vaultsOf = async (pid, mine, certMaster) => {
2592
2842
  if (!mine) return []
2843
+ /** @type {import('./acta.js').ActaMember[]} */
2593
2844
  let members = []
2594
2845
  try {
2595
2846
  const raw = pid === currentPid ? kv.getItem(ACTA_STORAGE) : rawKv.getItem(`dotrino.identity.p.${pid}.acta`)
2596
2847
  members = (raw ? JSON.parse(raw) : null)?.members || []
2597
2848
  } catch (_) { members = [] }
2598
2849
  if (!members.some((m) => m.pub === mine)) members = []
2850
+ /** @type {Array<{ comm: string | null, master: string, id: string, label: string }>} */
2599
2851
  const out = await Promise.all(members.filter((m) => m.cn === Acta.VAULT_CN && m.vault).map(async (m) => {
2600
2852
  const owner = members.find((x) => x.pub === m.vault)
2601
- return { comm: m.pub, master: m.vault, id: await Acta.memberId(m.vault), label: owner?.label || '' }
2853
+ const master = /** @type {string} */ (m.vault)
2854
+ return { comm: m.pub, master, id: await Acta.memberId(master), label: owner?.label || '' }
2602
2855
  }))
2603
2856
  if (certMaster && !out.some((v) => v.master === certMaster)) {
2604
2857
  // Un papel con una maestra ilegible no puede tumbar la lista entera, que es el menú de
2605
2858
  // perfiles de todas las apps: esa bóveda no sale, y se dice.
2606
2859
  let id = null
2607
- try { id = await Acta.memberId(certMaster) } catch (e) { console.warn(`[identity] profile ${pid}: the vault named by its certificate is not a key (${e.message})`) }
2860
+ try { id = await Acta.memberId(certMaster) } catch (e) { console.warn(`[identity] profile ${pid}: the vault named by its certificate is not a key (${/** @type {any} */ (e).message})`) }
2608
2861
  if (id) out.push({ comm: null, master: certMaster, id, label: members.find((x) => x.pub === certMaster)?.label || '' })
2609
2862
  }
2610
2863
  return out
@@ -2645,6 +2898,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2645
2898
  }))
2646
2899
  },
2647
2900
  async currentProfile () {
2901
+ /** @type {Partial<ProfileEntry>} */
2648
2902
  const e = loadProfiles().find((p) => p.id === currentPid) || {}
2649
2903
  return { id: currentPid, name: e.name || me?.nickname || '', pubkey: publickeyJwkStr }
2650
2904
  },
@@ -2654,6 +2908,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2654
2908
  * `forVault: true` la marca como **nacida para adoptar** la cuenta de una bóveda
2655
2909
  * (camino B): es el único permiso que acepta `joinProfile`, y se consume al unirse.
2656
2910
  * Sin la marca, la cuenta es de este dispositivo y nadie se la puede llevar.
2911
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2657
2912
  */
2658
2913
  async createProfile ({ name, forVault = false } = {}) {
2659
2914
  const pid = 'p' + crypto.randomUUID().slice(0, 8)
@@ -2670,6 +2925,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2670
2925
  await ensureActa(me.nickname) // el perfil nuevo nace con su acta (él mismo es el master)
2671
2926
  return { id: pid, name: me.nickname, pubkey: publickeyJwkStr, pendingJoin: !!forVault }
2672
2927
  },
2928
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2673
2929
  async switchProfile ({ id } = {}) {
2674
2930
  if (!loadProfiles().find((p) => p.id === id)) throw new Error('profile does not exist')
2675
2931
  // Una cuenta volátil no puede ser «la activa» de este navegador: vive en la memoria de
@@ -2683,6 +2939,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2683
2939
  rawKv.setItem(CURRENT_STORAGE, id) // la app recarga la página → re-init con el nuevo perfil
2684
2940
  return { id }
2685
2941
  },
2942
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2686
2943
  async renameProfile ({ id, name } = {}) {
2687
2944
  const list = loadProfiles(); const e = list.find((p) => p.id === (id || currentPid))
2688
2945
  if (!e) throw new Error('profile does not exist')
@@ -2696,6 +2953,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2696
2953
  * La alerta es de la INTERFAZ, que pregunta antes. Si era la activa, `current` dice cuál
2697
2954
  * queda, y la app tiene que RECARGAR; si no queda ninguna, el arranque estrena una nueva
2698
2955
  * y vacía (ver `purgeProfile`).
2956
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2699
2957
  */
2700
2958
  async deleteProfile ({ id } = {}) {
2701
2959
  if (!loadProfiles().find((p) => p.id === id)) throw new Error('profile does not exist')
@@ -2717,6 +2975,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2717
2975
  *
2718
2976
  * La contraseña NO viaja: lo que viaja son los mensajes de OPAQUE, que no la llevan ni
2719
2977
  * dejan adivinarla (`@dotrino/vault/login-client`).
2978
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2720
2979
  */
2721
2980
  async loginWithPassword ({ address, password, remember = false, label = '', proxyUrl = null } = {}) {
2722
2981
  const url = proxyUrl || DEFAULT_PROXY
@@ -2734,6 +2993,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2734
2993
  /**
2735
2994
  * SALIR del inicio de sesión con contraseña: se le dice a la bóveda que suelte la plaza
2736
2995
  * y la cuenta desaparece de este navegador. Sin `id`, el activo.
2996
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2737
2997
  */
2738
2998
  async logoutLogin ({ id = null } = {}) {
2739
2999
  const pid = id || currentPid
@@ -2785,6 +3045,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2785
3045
  *
2786
3046
  * Es opt-in a propósito: una identidad de navegador no sella nada, y un acta sin llave
2787
3047
  * de sellado es perfectamente válida.
3048
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2788
3049
  */
2789
3050
  setSealKeyProvider ({ provider } = {}) {
2790
3051
  sealKeyProvider = typeof provider === 'function' ? provider : null
@@ -2802,7 +3063,10 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2802
3063
  return { ok: true, seq: acta.seq, sealPub: acta.sealPub }
2803
3064
  },
2804
3065
 
2805
- /** La llave con la que se firmaron los sobres de un acta dada. Para VERIFICARLOS. */
3066
+ /**
3067
+ * La llave con la que se firmaron los sobres de un acta dada. Para VERIFICARLOS.
3068
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3069
+ */
2806
3070
  sealKeyAt ({ seq, vault = null } = {}) {
2807
3071
  return Acta.sealKeyAt(loadActa(), seq, vault)
2808
3072
  },
@@ -2858,6 +3122,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2858
3122
  * estrena pubkey, y su cajón de variables va indexado por la vieja, así que
2859
3123
  * arrancaría sin configuración y sin decirlo. Esto le pone la llave sin moverle
2860
3124
  * nada más.
3125
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2861
3126
  */
2862
3127
  async setMemberEncPub ({ pub, encPub } = {}) {
2863
3128
  const acta = await sealChanges([{ op: 'encpub', pub, encPub }])
@@ -2867,6 +3132,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2867
3132
  /**
2868
3133
  * Admite un miembro (solo el master). El cert lo emite quien llama, antes o después.
2869
3134
  * `continuity`: si esa identidad ya existía por su cuenta, su puente firmado (F3).
3135
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2870
3136
  */
2871
3137
  async admitMember ({ pub, encPub = null, label = '', cn = null, caps = null, cert = null, continuity = null, machine = null, vault = null } = {}) {
2872
3138
  // `cn`: si viene, este miembro es un SERVICIO: abre el cajón de secretos de ESE nombre
@@ -2893,12 +3159,14 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2893
3159
  * DE QUÉ BÓVEDA ES una llave de comunicación (`vault`: su maestra). La pone la propia
2894
3160
  * bóveda a la llave que entró antes de existir el campo; sin él, con dos bóvedas en la
2895
3161
  * cuenta no hay forma de escribirle a una sola.
3162
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2896
3163
  */
2897
3164
  async setMemberVault ({ pub, vault } = {}) {
2898
3165
  const acta = await sealChanges([{ op: 'vault', pub, vault }])
2899
3166
  return { ok: true, seq: acta.seq }
2900
3167
  },
2901
3168
 
3169
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2902
3170
  async setCaps ({ pub, caps } = {}) {
2903
3171
  const acta = await sealChanges([{ op: 'caps', pub, caps }])
2904
3172
  return { ok: true, seq: acta.seq }
@@ -2908,7 +3176,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2908
3176
  * LOS PERMISOS DE VARIOS APARATOS EN UNA SOLA ACTA (dueño, 2026-09-26). Editar tres
2909
3177
  * aparatos eran tres actas y tres avisos; ahora el borrador entero se sella de golpe.
2910
3178
  * `changes`: `[{ pub, caps }]`, cada `caps` la lista COMPLETA de ese aparato.
2911
- * @param {{ changes?: Array<{ pub: string, caps: string[] }> }} [args]
3179
+ * @param {{ changes?: Array<{ pub: string, caps?: string[], cn?: string | null }> }} [args] lo que llega por `postMessage` o la API: sin comprobar todavía
2912
3180
  */
2913
3181
  async setCapsMany ({ changes } = {}) {
2914
3182
  if (!Array.isArray(changes) || !changes.length) throw new Error('setCapsMany: no changes')
@@ -2942,6 +3210,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2942
3210
  * TAMBIÉN en la delegación: son dos registros distintos —el acta dice quién es del
2943
3211
  * perfil, las delegaciones qué certs se emitieron— y las listas de dispositivos leen
2944
3212
  * la segunda, así que tocar solo una deja el nombre viejo a la vista.
3213
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2945
3214
  */
2946
3215
  async setLabel ({ pub, label } = {}) {
2947
3216
  const limpio = String(label || '').slice(0, 60)
@@ -2953,6 +3222,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2953
3222
  return { ok: true, seq: acta.seq, label: limpio, delegations: tocadas }
2954
3223
  },
2955
3224
 
3225
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
2956
3226
  async removeMember ({ pub } = {}) {
2957
3227
  return removeDevice(pub)
2958
3228
  },
@@ -2968,6 +3238,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2968
3238
  * poder sellar uno mismo, en el mismo acto— ya no se puede: nadie se quita el sello a
2969
3239
  * sí mismo (dejaría un acta que él firma sin poder firmarla). Si quieres salir, se lo
2970
3240
  * pides al otro cuando ya pueda sellar.
3241
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2971
3242
  */
2972
3243
  async handoverMaster ({ to, member = null } = {}) {
2973
3244
  const changes = []
@@ -2986,6 +3257,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2986
3257
  * RENUNCIA (§2.2): este dispositivo se quita capacidades a sí mismo. No pasa por el
2987
3258
  * master —por eso funciona con la bóveda apagada, que es justo cuando hace falta (te
2988
3259
  * robaron el aparato)— y solo puede QUITAR, así que cualquiera puede honrarla.
3260
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
2989
3261
  */
2990
3262
  async renounceCaps ({ caps } = {}) {
2991
3263
  const acta = loadActa()
@@ -3017,7 +3289,10 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3017
3289
  return { ok: true, record, caps: Acta.effectiveCaps(loadActa(), publickeyJwkStr, loadRenounces()) }
3018
3290
  },
3019
3291
 
3020
- /** Absorbe en el acta una renuncia ajena ya verificada (solo el master). */
3292
+ /**
3293
+ * Absorbe en el acta una renuncia ajena ya verificada (solo el master).
3294
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3295
+ */
3021
3296
  async absorbRenounce ({ record } = {}) {
3022
3297
  if (!(await Acta.verifyRenounce(record))) throw new Error('invalid renounce: the signature is not the member own')
3023
3298
  const acta = await sealChanges([{ op: 'renounce', record }])
@@ -3034,6 +3309,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3034
3309
  * Cifra algo con la clave de contenido del perfil. Devuelve el sobre MARCADO
3035
3310
  * `{ t: 'dotrino-cek', gen, iv, ct }` (la marca deja a la bóveda reconocerlo y volver a
3036
3311
  * cerrarlo al rotar). La llave privada de cifrado NUNCA sale de aquí.
3312
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3037
3313
  */
3038
3314
  async sealContent ({ plaintext } = {}) {
3039
3315
  const mine = await myCek()
@@ -3052,6 +3328,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3052
3328
  *
3053
3329
  * Distinto de `openContent`, que usa el llavero del PERFIL (el contenido del usuario);
3054
3330
  * aquí la envoltura viene suelta, del llavero de un cajón de secretos.
3331
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3055
3332
  */
3056
3333
  async openSealedValue ({ wrap, envelope } = {}) {
3057
3334
  if (!wrap || !envelope) throw new Error('openSealedValue: missing the wrap or the envelope')
@@ -3072,8 +3349,8 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3072
3349
  * es a alguien que el ACTA —firmada por la maestra— ya reconoce como miembro. La
3073
3350
  * autorización es el acta; esto solo es el sobre.
3074
3351
  *
3075
- * @param {{ wrap: any, encPub: string }} o `wrap`: mi envoltura · `encPub`: la
3076
- * pública de cifrado del miembro al que hay que envolvérsela.
3352
+ * @param {{ wrap?: any, encPub?: string }} [o] `wrap`: mi envoltura · `encPub`: la
3353
+ * pública de cifrado del miembro al que hay que envolvérsela. Llega sin comprobar.
3077
3354
  * @returns {Promise<any>} la envoltura nueva, para que la bóveda la guarde.
3078
3355
  */
3079
3356
  async rewrapFor ({ wrap, encPub } = {}) {
@@ -3082,7 +3359,10 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3082
3359
  return Content.wrapForMember({ cek, memberEncPub: encPub })
3083
3360
  },
3084
3361
 
3085
- /** Abre un sobre de contenido con el llavero del perfil (todas las generaciones). */
3362
+ /**
3363
+ * Abre un sobre de contenido con el llavero del perfil (todas las generaciones).
3364
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3365
+ */
3086
3366
  async openContent ({ envelope } = {}) {
3087
3367
  return Content.decryptWithKeyring({
3088
3368
  envelope, keyring: loadActa()?.keyring, myPub: publickeyJwkStr, myEncPrivateKey: encKeypair.privateKey
@@ -3116,6 +3396,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3116
3396
  * conexión de la bóveda con un 1009 y la dejaba muda para TODO el ecosistema, sin un
3117
3397
  * solo log de su lado (2026-08-24: el bot social dejó de publicar y eco se quedó sin un
3118
3398
  * eco que mostrar).
3399
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3119
3400
  */
3120
3401
  async actaHistory ({ sinceSeq = 0 } = {}) {
3121
3402
  const cur = loadActa()
@@ -3170,6 +3451,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3170
3451
  * Guarda la tarjeta de OTRA persona en su ficha de contacto. La primera vez se acepta
3171
3452
  * (es el mismo criterio con el que agregaste el contacto); después solo si no retrocede
3172
3453
  * y la firmó el mismo master. Si el master cambió, se avisa en vez de aceptarlo callando.
3454
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3173
3455
  */
3174
3456
  async adoptPeerCard ({ card } = {}) {
3175
3457
  if (!card?.profileId) throw new Error('invalid card')
@@ -3181,26 +3463,44 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3181
3463
  return { adopted: true, reason: r.reason, devices: card.keys.length }
3182
3464
  },
3183
3465
 
3184
- /** Adopta un acta que llega de otro miembro (gana el seq mayor; a igual seq, el traspaso). */
3466
+ /**
3467
+ * Adopta un acta que llega de otro miembro (gana el seq mayor; a igual seq, el traspaso).
3468
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3469
+ */
3185
3470
  async adoptActa ({ acta } = {}) { return adoptActa(acta) },
3186
3471
 
3187
- /** Adopta una cadena completa (para ponerse al día tras estar apagado). */
3472
+ /**
3473
+ * Adopta una cadena completa (para ponerse al día tras estar apagado).
3474
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3475
+ */
3188
3476
  async adoptActaChain ({ chain } = {}) { return adoptChain(chain) },
3189
3477
 
3190
- /** Se pone al día por la cadena de selladoras (`adoptSealerChainNow`). */
3478
+ /**
3479
+ * Se pone al día por la cadena de selladoras (`adoptSealerChainNow`).
3480
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3481
+ */
3191
3482
  async adoptActaBySealerChain ({ sealerChain } = {}) { return adoptSealerChain(sealerChain) },
3192
3483
 
3193
- /** Completa el historial con las actas que falten detrás de la vigente (`fillHistoryNow`). */
3484
+ /**
3485
+ * Completa el historial con las actas que falten detrás de la vigente (`fillHistoryNow`).
3486
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3487
+ */
3194
3488
  async fillActaHistory ({ actas } = {}) { return fillHistory(actas) },
3195
3489
 
3196
- /** Las últimas actas que guardo, con la vigente: lo que otra bóveda necesita para rellenar. */
3490
+ /**
3491
+ * Las últimas actas que guardo, con la vigente: lo que otra bóveda necesita para rellenar.
3492
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3493
+ */
3197
3494
  async recentActas ({ count = 10 } = {}) {
3198
3495
  const cur = loadActa()
3199
3496
  if (!cur) return { actas: [] }
3200
3497
  return { actas: [...loadHistory().filter((a) => a.seq < cur.seq).slice(-Math.max(0, count - 1)), cur] }
3201
3498
  },
3202
3499
 
3203
- /** Une este dispositivo al perfil de otra bóveda (solo si aquí no hay nada que perder). */
3500
+ /**
3501
+ * Une este dispositivo al perfil de otra bóveda (solo si aquí no hay nada que perder).
3502
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3503
+ */
3204
3504
  async joinProfile ({ acta } = {}) { return joinProfile(acta) },
3205
3505
 
3206
3506
  // ----- emparejar ESTE dispositivo con el vault del usuario (Fase 1) -----
@@ -3227,6 +3527,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3227
3527
  * `profileId`); lo que cambia es quién sella. Solo puede hacerlo el
3228
3528
  * master: si esta cuenta ya la manda otra bóveda, no hay nada que
3229
3529
  * regalar y falla en voz alta.
3530
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3230
3531
  */
3231
3532
  async vaultPair ({ qr, label = '', join = 'current', machine = undefined, account = null, requireCaps = null }) {
3232
3533
  if (join === 'adopt') return handlers.vaultAdopt({ qr, label, machine })
@@ -3282,6 +3583,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3282
3583
  * Requisito (§2 del doc): solo puede hacerlo el master. Si esta cuenta ya la manda otra
3283
3584
  * bóveda, este aparato no puede regalar lo que no tiene; el traspaso se hace desde la
3284
3585
  * que manda hoy.
3586
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3285
3587
  */
3286
3588
  async vaultAdopt ({ qr, label = '', machine = undefined } = {}) {
3287
3589
  const mine = loadActa()
@@ -3301,6 +3603,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3301
3603
  // Admitir + envolver + traspasar, en UN solo sello. Se ejecuta cuando la bóveda ya
3302
3604
  // fue aprobada por un humano (el código de 6 dígitos volvió correcto).
3303
3605
  onAdopt: async ({ pub, encPub, label: vlabel }) => {
3606
+ /** @type {any[]} */
3304
3607
  const cambios = [{ op: 'admit', member: { pub, encPub, label: vlabel || 'bóveda', caps: ['sign', 'store', 'read'] } }]
3305
3608
  // Sin la clave de contenido envuelta, la bóveda entraría mandando pero sin poder
3306
3609
  // leer nada de lo que guarda la cuenta que acaba de recibir.
@@ -3342,7 +3645,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3342
3645
 
3343
3646
  /**
3344
3647
  * La página dice dónde corre (`machine.js`); se manda con los pedidos a la bóveda.
3345
- * @param {any} [args]
3648
+ * @param {HandlerParams} [args] lo que llega por `postMessage` o la API: sin comprobar todavía
3346
3649
  */
3347
3650
  async setMachine ({ machine } = {}) {
3348
3651
  pageMachine = Acta.cleanMachine(machine)
@@ -3366,6 +3669,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3366
3669
  // Firma DELEGADA: pide a la maestra del vault que firme `payload` (con el cert de
3367
3670
  // este dispositivo). Aditivo y explícito — NO cambia `signData` (que sigue local),
3368
3671
  // así nada se rompe si no estás emparejado o si el vault está apagado.
3672
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
3369
3673
  async vaultSign ({ payload }) {
3370
3674
  const v = loadVaultCert(); const device = loadVaultDevice()
3371
3675
  if (!v?.cert || !device) throw new Error('this device is not paired with a vault')
@@ -3386,6 +3690,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3386
3690
  * envuelto la clave. Ahora falla con `no-content-key`, que se arregla entrando al
3387
3691
  * perfil desde un aparato que ya la tenga — y se ve, en vez de viajar a la vista.
3388
3692
  * Por lo mismo, una respuesta sin cifrar tampoco se acepta.
3693
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3389
3694
  */
3390
3695
  async vaultStore ({ method, args, wake = true }) {
3391
3696
  const v = loadVaultCert(); const device = loadVaultDevice()
@@ -3429,6 +3734,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3429
3734
  * `op`: `pending` · `pair` · `approve` · `reject` · `revoke` · `audit`. Cambiar
3430
3735
  * permisos y traspasar el mando NO están, y no es un olvido: eso sigue siendo del
3431
3736
  * master, en su máquina.
3737
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3432
3738
  */
3433
3739
  async vaultAdmin ({ op, to = null, ...rest } = {}) {
3434
3740
  const link = adminLink()
@@ -3444,6 +3750,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3444
3750
  }
3445
3751
  // LAS CONCESIONES (`grants`) traen el comando sellado a este aparato, como los pedidos:
3446
3752
  // se abre aquí, donde está la llave. Lo que no trae nada sellado pasa tal cual.
3753
+ /** @param {any} r */
3447
3754
  const opened = async (r) => (Array.isArray(r?.items) ? { ...r, items: await abrirContextos(r.items, currentPid) } : r)
3448
3755
  if (link.self) return opened(await remoteAdmin({ acta: loadActa(), master: v.master, proxy: v.proxy, device, cert: v.cert, op, ...rest }))
3449
3756
  maybeRenewVaultCert()
@@ -3458,6 +3765,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3458
3765
  *
3459
3766
  * `profile` apunta a OTRA cuenta de este mismo dispositivo (ver `vaultApprovalsAll`):
3460
3767
  * sin él es la activa, como siempre.
3768
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3461
3769
  */
3462
3770
  async vaultApprovals ({ op, id, profile = null, notify } = {}) {
3463
3771
  if (profile && profile !== currentPid) return approvalsDeOtroPerfil(profile, { op, id })
@@ -3470,6 +3778,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3470
3778
  return r
3471
3779
  }
3472
3780
  maybeRenewVaultCert()
3781
+ /** @param {any} cert */
3473
3782
  const ask = (cert) => remoteApproval({ acta: loadActa(), master: v.master, proxy: v.proxy, device, cert, op, id, notify, onRevoked: wipeVaultLink })
3474
3783
  try {
3475
3784
  let r
@@ -3480,7 +3789,8 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3480
3789
  // «unauthorized: scope» para siempre. Se renueva UNA vez y se reintenta; la bóveda
3481
3790
  // decide qué papel toca según SU acta. Un aparato revocado o sin el permiso no se
3482
3791
  // reintenta: renovar no lo arregla y esconder el motivo sería peor.
3483
- if (e?.code !== 'unauthorized' || !PAPER_REASONS.has(e.reason)) throw e
3792
+ const err = /** @type {any} */ (e)
3793
+ if (err?.code !== 'unauthorized' || !PAPER_REASONS.has(err.reason)) throw e
3484
3794
  r = await ask(await renovarCert())
3485
3795
  }
3486
3796
  // El comando de cada pedido viene sellado a este aparato: se abre aquí, que es
@@ -3509,7 +3819,8 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3509
3819
  * (eso escribe, y escribir en otra cuenta desde la pantalla de otra es pedir un lío).
3510
3820
  * Mirar es de solo lectura; si el papel de una cuenta está desfasado, se dice y punto.
3511
3821
  *
3512
- * @returns {Promise<Array<{ profile, name, items, error? }>>} una entrada por cuenta que
3822
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3823
+ * @returns {Promise<Array<{ profile: string, name: string, current: boolean, items: any[], error?: string }>>} una entrada por cuenta que
3513
3824
  * aprueba — con sus pedidos, o con el motivo por el que no se pudo preguntar.
3514
3825
  */
3515
3826
  async vaultApprovalsAll ({ notify } = {}) {
@@ -3525,7 +3836,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3525
3836
  const base = { profile: p.id, name: p.name || '', current: p.id === currentPid }
3526
3837
  let device = null
3527
3838
  try { device = p.id === currentPid ? (propia?.device || loadVaultDevice()) : await signerForProfile(p.id) } catch (e) {
3528
- return { ...base, items: [], error: e?.code || 'no-key' }
3839
+ return { ...base, items: [], error: /** @type {any} */ (e)?.code || 'no-key' }
3529
3840
  }
3530
3841
  if (!device) return { ...base, items: [], error: 'no-key' }
3531
3842
  try {
@@ -3535,16 +3846,18 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3535
3846
  const items = Array.isArray(r?.items) ? await abrirContextos(r.items, p.id) : []
3536
3847
  return { ...base, items }
3537
3848
  } catch (e) {
3538
- return { ...base, items: [], error: e?.code || e?.message || 'error' }
3849
+ const err = /** @type {any} */ (e)
3850
+ return { ...base, items: [], error: err?.code || err?.message || 'error' }
3539
3851
  }
3540
3852
  }))
3541
- return salida.filter(Boolean)
3853
+ return /** @type {Array<{ profile: string, name: string, current: boolean, items: any[], error?: string }>} */ (salida.filter(Boolean))
3542
3854
  },
3543
3855
 
3544
3856
  /**
3545
3857
  * PUSH DE LA APP NATIVA: registra el token (FCM/APNs) de este aparato en el proxio,
3546
3858
  * bajo la llave del dispositivo, para que la bóveda pueda «timbrarlo» cuando haya
3547
3859
  * un pedido. La app nativa le pasa el token a la página; la página lo trae aquí.
3860
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3548
3861
  */
3549
3862
  async registerPush ({ kind = 'fcm', token } = {}) {
3550
3863
  const device = loadVaultDevice()
@@ -3593,6 +3906,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3593
3906
  * administra. Sin él contesta la que emitió mi papel. Antes la lista iba siempre a esa,
3594
3907
  * aunque la consola administrara la otra: la cabecera era de la Nube y los aparatos, sus
3595
3908
  * papeles y sus versiones eran del PC (2026-10-27: «parece que mezcla cosas»).
3909
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3596
3910
  */
3597
3911
  async listVaultDevices ({ to = null } = {}) {
3598
3912
  const v = loadVaultCert(); const device = loadVaultDevice()
@@ -3604,7 +3918,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3604
3918
  // que da el binario (qué versión corre cada aparato, dónde corre, si le llegan avisos).
3605
3919
  // El acta es la nuestra: no hay nada que adoptar.
3606
3920
  if ((!v?.cert || !device) && adminLink()?.self) {
3607
- const self = adminLink()
3921
+ const self = /** @type {NonNullable<ReturnType<typeof adminLink>>} */ (adminLink())
3608
3922
  const res = await remoteDevices({ acta: loadActa(), master: self.v.master, proxy: self.v.proxy, device: self.device, cert: self.v.cert, sinceSeq: loadActa()?.seq ?? 0, ...target })
3609
3923
  return { ...res, acta: loadActa() }
3610
3924
  }
@@ -3644,7 +3958,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3644
3958
  if (r && !r.adopted && !r.joined && llega != null && antes != null && llega > antes) {
3645
3959
  console.warn(`[identity] the vault is on record #${llega} and this device stays on #${antes}: ${r.reason}`)
3646
3960
  }
3647
- } catch (e) { console.warn('[identity] could not adopt the record from the vault: ' + e.message) }
3961
+ } catch (e) { console.warn('[identity] could not adopt the record from the vault: ' + /** @type {any} */ (e).message) }
3648
3962
  // El acta acaba de llegar: si trae permisos que el cert no lleva, se renueva YA. La
3649
3963
  // comprobación de arriba corrió ANTES de tenerla, así que sin esto haría falta una
3650
3964
  // segunda visita para estrenar un permiso recién concedido.
@@ -3676,12 +3990,14 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3676
3990
  return Object.values(loadPeers()).filter(p => p && p.isContact).sort((a, b) => (b.lastSeen || 0) - (a.lastSeen || 0))
3677
3991
  },
3678
3992
 
3993
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
3679
3994
  async setMyNickname ({ nickname }) {
3680
3995
  return { me: applyMeUpdate({ nickname }) }
3681
3996
  },
3682
3997
 
3683
3998
  // Perfil completo (avatar 250x250, links de redes, datos), cada ítem con `visible`
3684
3999
  // (oculto = no se comparte). Merge: no pisa lo que no venga en el patch.
4000
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
3685
4001
  async updateMe ({ patch } = {}) {
3686
4002
  return { me: applyMeUpdate(patch || {}) }
3687
4003
  },
@@ -3696,6 +4012,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3696
4012
  // Subconjunto PÚBLICO del perfil (solo lo marcado visible) — para compartir/publicar.
3697
4013
  async publicMe () {
3698
4014
  const m = me || {}
4015
+ /** @type {Record<string, any>} */
3699
4016
  const out = { publickey: m.publickey, encryptionPubkey: m.encryptionPubkey }
3700
4017
  if (m.nickname) out.nickname = m.nickname
3701
4018
  if (m.avatar && m.avatarVisible !== false) out.avatar = m.avatar
@@ -3705,8 +4022,8 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3705
4022
  const shown = STD_FIELDS_SENSITIVE.has(k) ? (m[k + 'Visible'] === true) : (m[k + 'Visible'] !== false)
3706
4023
  if (shown) out[k] = m[k]
3707
4024
  }
3708
- if (Array.isArray(m.links)) { const v = m.links.filter((l) => l.visible !== false).map(({ visible, ...r }) => r); if (v.length) out.links = v }
3709
- if (Array.isArray(m.fields)) { const v = m.fields.filter((f) => f.visible !== false).map(({ visible, ...r }) => r); if (v.length) out.fields = v }
4025
+ if (Array.isArray(m.links)) { const v = m.links.filter((/** @type {any} */ l) => l.visible !== false).map(({ visible, ...r }) => r); if (v.length) out.links = v }
4026
+ if (Array.isArray(m.fields)) { const v = m.fields.filter((/** @type {any} */ f) => f.visible !== false).map(({ visible, ...r }) => r); if (v.length) out.fields = v }
3710
4027
  return out
3711
4028
  },
3712
4029
 
@@ -3720,6 +4037,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3720
4037
  * puede abrirla también un dispositivo que no estaba conectado cuando se envió.
3721
4038
  * 2. **Se cifra a TODOS los dispositivos de esa persona**, si conocemos su tarjeta de
3722
4039
  * perfil (§tarjeta). Le escribes a la persona, no al aparato desde el que te habló.
4040
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3723
4041
  */
3724
4042
  async encrypt ({ recipients, plaintext }) {
3725
4043
  if (!Array.isArray(recipients) || recipients.length === 0) throw new Error('recipients required')
@@ -3739,6 +4057,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3739
4057
  for (const kk of (card?.keys || [])) if (kk.encPub) encPubs.add(kk.encPub)
3740
4058
  }
3741
4059
 
4060
+ /** @type {Record<string, { iv: string, ct: string }>} */
3742
4061
  const wrap = {}
3743
4062
  for (const encPub of encPubs) {
3744
4063
  try {
@@ -3755,6 +4074,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3755
4074
  /**
3756
4075
  * Descifra. Busca MI envoltura por el id de mi llave de cifrado (v2); `myToken` ya no
3757
4076
  * hace falta y se acepta solo por compatibilidad de llamada.
4077
+ * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
3758
4078
  */
3759
4079
  async decrypt ({ senderEncryptionPubkey, myToken, envelope }) {
3760
4080
  if (!senderEncryptionPubkey) throw new Error('senderEncryptionPubkey required')
@@ -3791,13 +4111,16 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3791
4111
  }
3792
4112
  },
3793
4113
 
4114
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
3794
4115
  async syncConnect ({ clientId }) { if (!sync) throw new Error('sync not ready'); return sync.connectGoogle(clientId) },
3795
4116
  async syncDisconnect () { if (!sync) return; return sync.disconnectGoogle() },
4117
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
3796
4118
  async syncUnlock ({ passphrase }) { if (!sync) throw new Error('sync not ready'); return sync.unlock(passphrase) },
3797
4119
  async syncLock () { if (!sync) return; return sync.lock() },
3798
4120
  async syncStatus () { return sync ? sync.getStatus() : { connected: false, unlocked: false, dirty: false } },
3799
4121
  async syncNow () { if (!sync) throw new Error('sync not ready'); await sync.pull(); await sync.push(); return sync.getStatus() },
3800
4122
 
4123
+ /** @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía */
3801
4124
  async importIdentity ({ privateJwk, publicJwk, encPrivateJwk, encPublicJwk, me: meIn, peers: peersIn }) {
3802
4125
  if (!privateJwk || !publicJwk) throw new Error('privateJwk and publicJwk required')
3803
4126
  await crypto.subtle.importKey('jwk', publicJwk, { name: 'ECDSA', namedCurve: 'P-256' }, true, ['verify'])
@@ -3835,6 +4158,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3835
4158
  // marca se consume, así que ninguna cuenta de verdad entra en este barrido.
3836
4159
  {
3837
4160
  const list = loadProfiles()
4161
+ /** @param {ProfileEntry} p */
3838
4162
  const orphan = (p) => p.pendingJoin && !vaultCertOf(p.id)
3839
4163
  const dead = list.filter(orphan)
3840
4164
  const alive = list.filter((p) => !orphan(p))
@@ -3842,7 +4166,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3842
4166
  const stored = rawKv.getItem(CURRENT_STORAGE)
3843
4167
  const back = dead.find((p) => p.id === stored)?.from
3844
4168
  for (const p of dead) {
3845
- try { await purgeProfile(p.id) } catch (e) { console.warn('[identity] could not discard a ghost account:', e?.message || e) }
4169
+ try { await purgeProfile(p.id) } catch (e) { console.warn('[identity] could not discard a ghost account:', /** @type {any} */ (e)?.message || e) }
3846
4170
  }
3847
4171
  if (back && alive.some((p) => p.id === back)) rawKv.setItem(CURRENT_STORAGE, back)
3848
4172
  }
@@ -3887,7 +4211,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3887
4211
  for (const [pid, visto] of Object.entries(vivas)) {
3888
4212
  if (pid === reclamada || (ahora - visto) < VOLATILE_STALE_MS) continue
3889
4213
  try { await purgeProfile(pid) }
3890
- catch (e) { console.warn('[identity] could not sweep an abandoned walk-in account:', e?.message || e) }
4214
+ catch (e) { console.warn('[identity] could not sweep an abandoned walk-in account:', /** @type {any} */ (e)?.message || e) }
3891
4215
  delete vivas[pid]; cambio = true
3892
4216
  }
3893
4217
  if (cambio) saveVolatile(vivas)
@@ -3940,7 +4264,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3940
4264
  kv.setItem(ME_STORAGE, JSON.stringify(me))
3941
4265
  }
3942
4266
  // Acta de perfil: si no existe, nace ahora (un miembro, este dispositivo, que es el master).
3943
- try { await ensureActa() } catch (e) { console.warn('[identity] could not create the profile record:', e.message) }
4267
+ try { await ensureActa() } catch (e) { console.warn('[identity] could not create the profile record:', /** @type {any} */ (e).message) }
3944
4268
 
3945
4269
  // Perfil compartido: jalar del vault en background (gana el más nuevo).
3946
4270
  pullProfileFromVault()
@@ -3972,8 +4296,10 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3972
4296
  //
3973
4297
  // Solo con bóveda y con la clave de contenido; una cuenta volátil no guarda contactos en ningún
3974
4298
  // sitio, tampoco en la bóveda. Sin bóveda no es un error: es el estado normal, y no se dice.
3975
- let peerSyncTimer = null
4299
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
4300
+ let peerSyncTimer
3976
4301
  let peerSyncRunning = false
4302
+ /** @param {number} delay */
3977
4303
  function schedulePeerSync (delay) {
3978
4304
  if (volatilePids.has(currentPid)) return
3979
4305
  clearTimeout(peerSyncTimer)
@@ -3993,7 +4319,8 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3993
4319
  if (changed) setPeersDirect(merged)
3994
4320
  }
3995
4321
  } catch (e) {
3996
- if (!['not-paired', 'no-content-key'].includes(e?.code)) console.warn(`[cc-identity] contact book ↔ vault failed (${e?.code || 'error'}): ${e?.message}`)
4322
+ const err = /** @type {any} */ (e)
4323
+ if (!['not-paired', 'no-content-key'].includes(err?.code)) console.warn(`[cc-identity] contact book ↔ vault failed (${err?.code || 'error'}): ${err?.message}`)
3997
4324
  } finally { peerSyncRunning = false }
3998
4325
  }
3999
4326
  schedulePeerSync(4000)
@@ -4003,8 +4330,9 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
4003
4330
  refreshLockState()
4004
4331
  for (const name of Object.keys(handlers)) {
4005
4332
  if (LOCK_EXEMPT.has(name)) continue
4006
- const fn = handlers[name]
4007
- handlers[name] = async (params) => {
4333
+ const h = /** @type {Record<string, (params: any) => any>} */ (handlers)
4334
+ const fn = h[name]
4335
+ h[name] = async (params) => {
4008
4336
  if (locked) refreshLockState() // otra pestaña pudo desbloquear… no: session es por pestaña; re-chequea por si se quitó el pwd
4009
4337
  if (locked) throw new Error('profile locked: unlock it with your password (unlockProfile)')
4010
4338
  return fn(params)
@@ -4043,6 +4371,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
4043
4371
  * pararse (ver `adminLink`). En el núcleo y no en `handlers`: ninguna
4044
4372
  * aplicación tiene por qué poder decir dónde está la bóveda de esta cuenta.
4045
4373
  */
4374
+ /** @param {{ cert: any, proxy: string, open: (onReply: (reply: any) => void) => { send (payload: any): void, close (): void } } | null} [self] */
4046
4375
  setSelfVault (self = null) {
4047
4376
  if (self && (!self.cert || typeof self.proxy !== 'string' || typeof self.open !== 'function')) throw new Error('setSelfVault: cert, proxy and open are required')
4048
4377
  try { selfLinkOff?.() } catch (_) {}
@@ -4050,7 +4379,9 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
4050
4379
  selfLink = self ? { cert: self.cert, proxy: self.proxy } : null
4051
4380
  if (self && publickeyJwkStr) selfLinkOff = registerLocalVault(publickeyJwkStr, self.open)
4052
4381
  },
4382
+ /** @param {(status: any) => void} fn */
4053
4383
  onSyncStatus (fn) { if (sync) sync.onStatus(fn) },
4384
+ /** @param {(payload: any) => void} fn */
4054
4385
  onVaultEvent (fn) { vaultListeners.add(fn); return () => vaultListeners.delete(fn) }
4055
4386
  }
4056
4387
  }