@dotrino/identity 0.136.0 → 0.136.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/package.json +3 -2
  2. package/src/index.d.ts +60 -2
  3. package/src/index.js +364 -81
  4. package/src/node.js +29 -5
  5. package/types/acta.d.ts +397 -175
  6. package/types/assertion.d.ts +25 -18
  7. package/types/avatar.d.ts +14 -3
  8. package/types/capabilities.d.ts +110 -61
  9. package/types/content.d.ts +88 -45
  10. package/types/core.d.ts +578 -383
  11. package/types/keyid.d.ts +10 -3
  12. package/types/machine.d.ts +5 -1
  13. package/types/peerStore.d.ts +80 -0
  14. package/types/peerSync.d.ts +20 -6
  15. package/types/remote.d.ts +170 -42
  16. package/types/session.d.ts +74 -81
  17. package/types/sessionFlow.d.ts +108 -33
  18. package/types/vaultSeal.d.ts +21 -9
  19. package/vault/acta.js +245 -29
  20. package/vault/assertion.js +13 -4
  21. package/vault/avatar.js +12 -1
  22. package/vault/capabilities.js +56 -6
  23. package/vault/channel.js +18 -2
  24. package/vault/content.js +60 -6
  25. package/vault/core.js +419 -88
  26. package/vault/externalKeys.js +34 -2
  27. package/vault/facade.js +182 -24
  28. package/vault/globals.d.ts +60 -0
  29. package/vault/keyid.js +10 -1
  30. package/vault/machine.js +7 -1
  31. package/vault/nativeStore.js +21 -4
  32. package/vault/originPolicy.js +13 -2
  33. package/vault/peerStore.js +57 -10
  34. package/vault/peerSync.js +23 -4
  35. package/vault/remote.js +132 -32
  36. package/vault/session.js +24 -7
  37. package/vault/sessionFlow.js +43 -9
  38. package/vault/sync.js +59 -15
  39. package/vault/vault.js +78 -49
  40. package/vault/vaultSeal.js +18 -7
  41. package/vault/vendor/compat/VERSION.txt +1 -1
  42. package/vault/vendor/compat/advisory.js +58 -8
  43. package/vault/vendor/compat/index.js +57 -6
  44. package/vault/vendor/compat/ranges.js +12 -2
  45. package/vault/vendor/proxy-client/VERSION.txt +1 -1
  46. package/vault/vendor/proxy-client/client.js +41 -19
  47. package/vault/vendor/roadmap/manifests.js +23 -23
  48. package/vault/vendor/store/VERSION.txt +1 -1
  49. package/vault/vendor/vault/VERSION.txt +1 -1
  50. package/vault/vendor/vault/core/libVersion.js +1 -1
  51. package/vault/vendor/vault/core/transport.js +15 -3
  52. package/vault/vendor/vault/core/vault.js +71 -1
  53. package/vault/vendor/vault/protocol.js +25 -0
package/src/index.js CHANGED
@@ -9,23 +9,41 @@
9
9
 
10
10
  import { browserMachine } from '../vault/machine.js'
11
11
 
12
+ /** @typedef {import('./index.js').Identity} IdentityApi la API pública, tal como la publica `index.d.ts` */
13
+
12
14
  const DEFAULT_VAULT_URL = 'https://id.dotrino.com/'
13
15
 
16
+ /** @type {Identity | null} */
14
17
  let singleton = null
15
18
 
16
19
  export class Identity {
20
+ /** @param {import('./index.js').IdentityOptions} [options] */
17
21
  constructor (options = {}) {
18
22
  this.vaultUrl = options.vaultUrl || DEFAULT_VAULT_URL
19
23
  this.timeoutMs = options.timeoutMs ?? 5000
24
+ /** @type {HTMLIFrameElement | null} */
20
25
  this._iframe = null
26
+ /** @type {Promise<IdentityApi> | null} */
21
27
  this._ready = null
28
+ /** @type {((id: IdentityApi) => void) | null} */
22
29
  this._readyResolve = null
23
30
  this._nextId = 1
31
+ /** @type {Map<string, { resolve: (v: any) => void, reject: (e: Error) => void, timer: ReturnType<typeof setTimeout> }>} */
24
32
  this._pending = new Map()
33
+ /** @type {((event: MessageEvent) => void) | null} */
25
34
  this._handler = null
35
+ /** @type {import('./index.js').Me | null} */
26
36
  this._me = null
37
+ /** @type {boolean | undefined} el perfil está bajo contraseña (lo dice el `ready` del iframe) */
38
+ this._locked // eslint-disable-line no-unused-expressions
39
+ /** @type {Map<string, Set<(payload: any) => void>> | undefined} */
40
+ this._listeners // eslint-disable-line no-unused-expressions
27
41
  }
28
42
 
43
+ /**
44
+ * @param {import('./index.js').IdentityOptions} [options]
45
+ * @returns {Promise<Identity>}
46
+ */
29
47
  static async connect (options = {}) {
30
48
  if (!singleton) singleton = new Identity(options)
31
49
  // Esperar SIEMPRE a ready(): si otro caller creó el singleton pero su
@@ -44,6 +62,7 @@ export class Identity {
44
62
  }
45
63
 
46
64
  /** Overlay mínimo de desbloqueo (PIN/contraseña). Resuelve al desbloquear. */
65
+ /** @returns {Promise<Identity>} */
47
66
  async _promptUnlock () {
48
67
  const es = !(navigator.language || 'es').startsWith('en')
49
68
  const T = es
@@ -59,9 +78,10 @@ export class Identity {
59
78
  <div data-err style="color:#e5484d;font-size:13px;min-height:18px;margin:6px 0 8px"></div>
60
79
  <button type="submit" style="width:100%;padding:10px;border-radius:10px;border:0;background:#7c3aed;color:#fff;font:inherit;font-weight:600;cursor:pointer">${T.b}</button>
61
80
  </form>`
62
- const form = back.firstElementChild
63
- const input = form.querySelector('input')
64
- const err = form.querySelector('[data-err]')
81
+ // El formulario se acaba de escribir arriba: los tres elementos están.
82
+ const form = /** @type {HTMLFormElement} */ (back.firstElementChild)
83
+ const input = /** @type {HTMLInputElement} */ (form.querySelector('input'))
84
+ const err = /** @type {HTMLElement} */ (form.querySelector('[data-err]'))
65
85
  form.addEventListener('submit', async (e) => {
66
86
  e.preventDefault()
67
87
  err.textContent = ''
@@ -72,7 +92,8 @@ export class Identity {
72
92
  back.remove()
73
93
  resolve(this)
74
94
  } catch (ex) {
75
- err.textContent = /incorrecta/.test(ex.message) ? T.e : ex.message
95
+ const msg = /** @type {{ message?: string }} */ (ex).message
96
+ err.textContent = /incorrecta/.test(/** @type {string} */ (msg)) ? T.e : /** @type {string} */ (msg)
76
97
  input.select()
77
98
  }
78
99
  })
@@ -81,24 +102,38 @@ export class Identity {
81
102
  })
82
103
  }
83
104
 
84
- /** Estado del candado del perfil activo: { protected, locked }. */
105
+ /**
106
+ * Estado del candado del perfil activo: { protected, locked }.
107
+ * @type {IdentityApi['profileLockStatus']}
108
+ */
85
109
  async profileLockStatus () { return this._call('profileLockStatus') }
86
- /** Desbloquea el perfil (la prueba queda en sessionStorage: por pestaña). */
110
+ /**
111
+ * Desbloquea el perfil (la prueba queda en sessionStorage: por pestaña).
112
+ * @type {IdentityApi['unlockProfile']}
113
+ */
87
114
  async unlockProfile (password) {
88
115
  const r = await this._call('unlockProfile', { password })
89
116
  this._locked = false
90
117
  try { this._me = await this._call('getMe') } catch (_) {}
91
118
  return r
92
119
  }
93
- /** Protege el perfil ACTIVO con contraseña/PIN — LOCAL de este dispositivo. */
120
+ /**
121
+ * Protege el perfil ACTIVO con contraseña/PIN — LOCAL de este dispositivo.
122
+ * @type {IdentityApi['setProfilePassword']}
123
+ */
94
124
  async setProfilePassword (password) { return this._call('setProfilePassword', { password }) }
95
- /** Quita la protección (requiere estar desbloqueado). */
125
+ /**
126
+ * Quita la protección (requiere estar desbloqueado).
127
+ * @type {IdentityApi['removeProfilePassword']}
128
+ */
96
129
  async removeProfilePassword () { return this._call('removeProfilePassword') }
97
130
 
131
+ /** @returns {Identity | null} */
98
132
  static current () {
99
133
  return singleton
100
134
  }
101
135
 
136
+ /** @type {IdentityApi['ready']} */
102
137
  ready () {
103
138
  if (this._ready) return this._ready
104
139
 
@@ -126,7 +161,7 @@ export class Identity {
126
161
  clearTimeout(timeout)
127
162
  this._me = msg.me || null
128
163
  this._locked = !!msg.locked
129
- this._readyResolve(this)
164
+ ;/** @type {(id: IdentityApi) => void} */ (this._readyResolve)(this)
130
165
  // Dónde corre esta página (`vault/machine.js`), para los pedidos a la bóveda. Un
131
166
  // iframe viejo no conoce el método: no pasa nada, solo no se manda.
132
167
  this._call('setMachine', { machine: browserMachine() }).catch(() => {})
@@ -141,7 +176,7 @@ export class Identity {
141
176
  // El rechazo llega con su `code` (y `detail`) puestos, como si el error se hubiera
142
177
  // lanzado aquí: quien lo atrapa comprueba `e.code`, nunca la frase.
143
178
  if (msg.error) {
144
- const err = new Error(msg.error)
179
+ const err = /** @type {Error & { code?: string, detail?: any, reason?: string }} */ (new Error(msg.error))
145
180
  if (msg.code) err.code = msg.code
146
181
  if (msg.detail) err.detail = msg.detail
147
182
  if (msg.reason) err.reason = msg.reason
@@ -170,6 +205,7 @@ export class Identity {
170
205
  }
171
206
 
172
207
  /** Deja ver la bóveda (a pantalla completa) mientras pregunta, y la devuelve a su sitio. */
208
+ /** @param {boolean} visible */
173
209
  _showVault (visible) {
174
210
  const f = this._iframe
175
211
  if (!f) return
@@ -179,6 +215,7 @@ export class Identity {
179
215
  f.setAttribute('aria-hidden', visible ? 'false' : 'true')
180
216
  }
181
217
 
218
+ /** @type {IdentityApi['destroy']} */
182
219
  destroy () {
183
220
  if (this._handler) window.removeEventListener('message', this._handler)
184
221
  if (this._iframe && this._iframe.parentNode) this._iframe.parentNode.removeChild(this._iframe)
@@ -197,40 +234,51 @@ export class Identity {
197
234
  *
198
235
  * The host app is responsible for delivering the challenge to the peer
199
236
  * and bringing back the signed response — see makeChallenge / verifyResponse.
237
+ * @type {IdentityApi['makeChallenge']}
200
238
  */
201
239
  async makeChallenge () {
202
240
  return this._call('makeChallenge')
203
241
  }
204
242
 
243
+ /** @type {IdentityApi['signChallenge']} */
205
244
  async signChallenge (nonce) {
206
245
  return this._call('signChallenge', { nonce })
207
246
  }
208
247
 
248
+ /** @type {IdentityApi['verifyResponse']} */
209
249
  async verifyResponse ({ nonce, publickey, signature }) {
210
250
  return this._call('verifyResponse', { nonce, publickey, signature })
211
251
  }
212
252
 
253
+ /** @type {IdentityApi['getPeer']} */
213
254
  async getPeer (publickey) {
214
255
  return this._call('getPeer', { publickey })
215
256
  }
216
257
 
217
- /** Bloquear (o desbloquear) a alguien: privado, viaja con tus contactos y no se publica. */
258
+ /**
259
+ * Bloquear (o desbloquear) a alguien: privado, viaja con tus contactos y no se publica.
260
+ * @type {IdentityApi['setBlocked']}
261
+ */
218
262
  async setBlocked (publickey, blocked) {
219
263
  return this._call('setBlocked', { publickey, blocked })
220
264
  }
221
265
 
266
+ /** @type {IdentityApi['setNickname']} */
222
267
  async setNickname (publickey, nickname) {
223
268
  return this._call('setNickname', { publickey, nickname })
224
269
  }
225
270
 
271
+ /** @type {IdentityApi['setRating']} */
226
272
  async setRating (publickey, rating, notes) {
227
273
  return this._call('setRating', { publickey, rating, notes })
228
274
  }
229
275
 
276
+ /** @type {IdentityApi['listPeers']} */
230
277
  async listPeers () {
231
278
  return this._call('listPeers')
232
279
  }
233
280
 
281
+ /** @type {IdentityApi['forgetPeer']} */
234
282
  async forgetPeer (publickey) {
235
283
  return this._call('forgetPeer', { publickey })
236
284
  }
@@ -240,22 +288,32 @@ export class Identity {
240
288
  * existing peer records are upserted with the new metadata. Contacts are
241
289
  * stored alongside the rating/endorsement record for the same pubkey, so
242
290
  * any app in the ecosystem (chat, chess, messenger, …) sees the same list.
291
+ * @type {IdentityApi['addContact']}
243
292
  */
244
- async addContact ({ publickey, nickname, encryptionPubkey, lastToken, notes } = {}) {
293
+ async addContact ({ publickey, nickname, encryptionPubkey, lastToken, notes } = /** @type {any} */ ({})) {
245
294
  return this._call('addContact', { publickey, nickname, encryptionPubkey, lastToken, notes })
246
295
  }
247
296
 
248
- /** Patch contact metadata (nickname / lastToken / encryptionPubkey / contactNotes). */
297
+ /**
298
+ * Patch contact metadata (nickname / lastToken / encryptionPubkey / contactNotes).
299
+ * @type {IdentityApi['updateContact']}
300
+ */
249
301
  async updateContact (publickey, patch) {
250
302
  return this._call('updateContact', { publickey, patch })
251
303
  }
252
304
 
253
- /** Remove the `isContact` flag while preserving rating/endorsement history. */
305
+ /**
306
+ * Remove the `isContact` flag while preserving rating/endorsement history.
307
+ * @type {IdentityApi['removeContact']}
308
+ */
254
309
  async removeContact (publickey) {
255
310
  return this._call('removeContact', { publickey })
256
311
  }
257
312
 
258
- /** List peers flagged as contacts, sorted by lastSeen desc. */
313
+ /**
314
+ * List peers flagged as contacts, sorted by lastSeen desc.
315
+ * @type {IdentityApi['listContacts']}
316
+ */
259
317
  async listContacts () {
260
318
  return this._call('listContacts')
261
319
  }
@@ -265,6 +323,7 @@ export class Identity {
265
323
  * using canonical JSON encoding. Returns `{ signature, publickey }` —
266
324
  * compatible with the proxy's `verifySignatureWithJWK` (used by
267
325
  * `identify` to bind a stable pubkey to the proxy connection).
326
+ * @type {IdentityApi['signData']}
268
327
  */
269
328
  async signData (data) {
270
329
  return this._call('signData', { data })
@@ -283,16 +342,21 @@ export class Identity {
283
342
  * @returns {Promise<object>} la prueba, lista para mandar. Se comprueba con
284
343
  * `verifyAssertion(prueba, { audience, nonce })`.
285
344
  */
286
- /** Qué le has concedido a cada aplicación. Sin esto, conceder no significaría nada. */
345
+ /**
346
+ * Qué le has concedido a cada aplicación. Sin esto, conceder no significaría nada.
347
+ * @type {IdentityApi['listGrants']}
348
+ */
287
349
  async listGrants () { return this._call('listGrants') }
288
350
  /**
289
351
  * Retirar lo concedido a una aplicación: la próxima vez que pida, se vuelve a preguntar.
290
352
  * Las que entran por el puente llegan todas desde el mismo origen, así que a esas se las
291
353
  * nombra con `onBehalfOf` (el que trae su fila de `listGrants`).
354
+ * @type {IdentityApi['revokeGrant']}
292
355
  */
293
356
  async revokeGrant (origin, onBehalfOf) { return this._call('revokeGrant', { origin, ...(onBehalfOf ? { onBehalfOf } : {}) }) }
294
357
 
295
- async requestAssertion ({ audience, nonce, scopes, ttlMs, onBehalfOf } = {}) {
358
+ /** @type {IdentityApi['requestAssertion']} */
359
+ async requestAssertion ({ audience, nonce, scopes, ttlMs, onBehalfOf } = /** @type {any} */ ({})) {
296
360
  // ESPERA LO QUE TARDE UNA PERSONA. Los cinco segundos de siempre valen para una
297
361
  // llamada que solo hace cuentas; esta puede abrir la pantalla de permiso (§permiso por
298
362
  // origen) y ahí quien contesta es un humano. Con el plazo corto, el cliente se rendía
@@ -308,12 +372,16 @@ export class Identity {
308
372
  * `sub` (JWK string) a hacer `scope` en tu nombre, hasta `exp`, revocable por
309
373
  * `nonce`. La clave maestra NUNCA sale del vault. `opts`: { ttlMs?, exp?, label?, nonce? }.
310
374
  * @returns {Promise<{ cert: object }>}
375
+ * @type {IdentityApi['signDelegation']}
311
376
  */
312
377
  async signDelegation (sub, scope, opts = {}) {
313
378
  return this._call('signDelegation', { sub, scope, ...opts })
314
379
  }
315
380
 
316
- /** Revoca una delegación por su `nonce` (queda en la lista de revocación). */
381
+ /**
382
+ * Revoca una delegación por su `nonce` (queda en la lista de revocación).
383
+ * @type {IdentityApi['revokeDelegation']}
384
+ */
317
385
  async revokeDelegation (nonce) {
318
386
  return this._call('revokeDelegation', { nonce })
319
387
  }
@@ -321,12 +389,16 @@ export class Identity {
321
389
  /**
322
390
  * QUITA EL DISPOSITIVO: retira **todos** los certificados vigentes de esa llave.
323
391
  * Revocar por `nonce` retira un papel; un aparato puede tener otros y seguir entrando.
392
+ * @type {IdentityApi['revokeDevice']}
324
393
  */
325
394
  async revokeDevice (sub) {
326
395
  return this._call('revokeDevice', { sub })
327
396
  }
328
397
 
329
- /** Lista las delegaciones emitidas + la lista de revocación (para el gestor de dispositivos). */
398
+ /**
399
+ * Lista las delegaciones emitidas + la lista de revocación (para el gestor de dispositivos).
400
+ * @type {IdentityApi['listDelegations']}
401
+ */
330
402
  async listDelegations () {
331
403
  return this._call('listDelegations')
332
404
  }
@@ -336,76 +408,141 @@ export class Identity {
336
408
  // por UN solo sellador (el «master»). Ninguna llave privada viaja nunca.
337
409
  // Diseño: dotrino-vault/docs/acta-de-perfil.md
338
410
 
339
- /** El acta vigente + si este dispositivo es el master + sus capacidades efectivas. */
411
+ /**
412
+ * El acta vigente + si este dispositivo es el master + sus capacidades efectivas.
413
+ * @type {IdentityApi['profileActa']}
414
+ */
340
415
  async profileActa () { return this._call('profileActa') }
341
- /** La cadena de selladores, para mandarla con una firma (ver `vault/acta.js`). */
416
+ /**
417
+ * La cadena de selladores, para mandarla con una firma (ver `vault/acta.js`).
418
+ * @type {IdentityApi['sealerChain']}
419
+ */
342
420
  async sealerChain () { return this._call('sealerChain') }
343
421
 
344
- /** Miembros del perfil, ya con id legible y capacidades efectivas. */
422
+ /**
423
+ * Miembros del perfil, ya con id legible y capacidades efectivas.
424
+ * @type {IdentityApi['profileMembers']}
425
+ */
345
426
  async profileMembers () { return this._call('profileMembers') }
346
427
 
347
- /** Dónde estoy yo: { inProfile, profileId, seq, isMaster, caps, id }. */
428
+ /**
429
+ * Dónde estoy yo: { inProfile, profileId, seq, isMaster, caps, id }.
430
+ * @type {IdentityApi['myMembership']}
431
+ */
348
432
  async myMembership () { return this._call('myMembership') }
349
- /** La cadena de actas desde `sinceSeq` (ver la nota en `node.js`). */
433
+ /**
434
+ * La cadena de actas desde `sinceSeq` (ver la nota en `node.js`).
435
+ * @type {IdentityApi['actaHistory']}
436
+ */
350
437
  async actaHistory (opts) { return this._call('actaHistory', opts || {}) }
351
- /** Los que estuvieron en las actas de la ventana del historial y ya no están. */
438
+ /**
439
+ * Los que estuvieron en las actas de la ventana del historial y ya no están.
440
+ * @type {IdentityApi['pastMembers']}
441
+ */
352
442
  async pastMembers () { return this._call('pastMembers', {}) }
353
443
 
354
- /** ¿Es ESTE dispositivo el master (el único que puede cambiar el acta)? */
444
+ /**
445
+ * ¿Es ESTE dispositivo el master (el único que puede cambiar el acta)?
446
+ * @type {IdentityApi['isMaster']}
447
+ */
355
448
  async isMaster () { return this._call('isMaster') }
356
449
 
357
- /** Admite un miembro nuevo (solo el master). */
450
+ /**
451
+ * Admite un miembro nuevo (solo el master).
452
+ * @type {IdentityApi['admitMember']}
453
+ */
358
454
  async admitMember (member) { return this._call('admitMember', member) }
359
- /** Registra la llave de cifrado de un miembro ya admitido (evita re-enrolarlo). */
455
+ /**
456
+ * Registra la llave de cifrado de un miembro ya admitido (evita re-enrolarlo).
457
+ * @type {IdentityApi['setMemberEncPub']}
458
+ */
360
459
  async setMemberEncPub (args) { return this._call('setMemberEncPub', args) }
361
460
 
362
- /** Cambia las capacidades de un miembro (solo el master). */
461
+ /**
462
+ * Cambia las capacidades de un miembro (solo el master).
463
+ * @type {IdentityApi['setCaps']}
464
+ */
363
465
  async setCaps (pub, caps) { return this._call('setCaps', { pub, caps }) }
364
- /** Cambia las capacidades de VARIOS miembros en una sola acta: `[{ pub, caps }]`. */
466
+ /**
467
+ * Cambia las capacidades de VARIOS miembros en una sola acta: `[{ pub, caps }]`.
468
+ * @type {IdentityApi['setCapsMany']}
469
+ */
365
470
  async setCapsMany (changes) { return this._call('setCapsMany', { changes }) }
471
+ /** @type {IdentityApi['setLabel']} */
366
472
  async setLabel (pub, label) { return this._call('setLabel', { pub, label }) }
367
473
 
368
- /** Expulsa a un miembro (solo el master; al master no se le puede expulsar). */
474
+ /**
475
+ * Expulsa a un miembro (solo el master; al master no se le puede expulsar).
476
+ * @type {IdentityApi['removeMember']}
477
+ */
369
478
  async removeMember (pub) { return this._call('removeMember', { pub }) }
370
479
 
371
480
  /**
372
481
  * Traspasa el master a otro miembro — dispositivo → bóveda, o bóveda → bóveda al mudarse
373
482
  * de PC. Si `member` viene, se admite y se nombra en el MISMO seq (sin ventana intermedia).
483
+ * @type {IdentityApi['handoverMaster']}
374
484
  */
375
485
  async handoverMaster (to, member = null) { return this._call('handoverMaster', { to, member }) }
376
486
 
377
487
  /**
378
488
  * Este dispositivo se quita capacidades a sí mismo (p. ej. dejar de firmar). Es
379
489
  * unilateral y funciona con la bóveda apagada, que es justo cuando hace falta.
490
+ * @type {IdentityApi['renounceCaps']}
380
491
  */
381
492
  async renounceCaps (caps) { return this._call('renounceCaps', { caps }) }
382
493
 
383
- /** Absorbe en el acta una renuncia de otro miembro (solo el master). */
494
+ /**
495
+ * Absorbe en el acta una renuncia de otro miembro (solo el master).
496
+ * @type {IdentityApi['absorbRenounce']}
497
+ */
384
498
  async absorbRenounce (record) { return this._call('absorbRenounce', { record }) }
385
499
 
386
- /** Adopta un acta recibida de otro miembro (gana el seq mayor; a igual seq, el traspaso). */
500
+ /**
501
+ * Adopta un acta recibida de otro miembro (gana el seq mayor; a igual seq, el traspaso).
502
+ * @type {IdentityApi['adoptActa']}
503
+ */
387
504
  async adoptActa (acta) { return this._call('adoptActa', { acta }) }
388
505
  /**
389
506
  * Une ESTE perfil a la cuenta de otro (la de una bóveda). No es adoptar una versión nueva
390
507
  * de la tuya: esta llave pasa a ser de OTRA cuenta y deja de tener la suya, así que solo
391
508
  * procede sobre un perfil creado con `{ forVault: true }`. Si no, devuelve
392
509
  * `{ joined: false, reason: 'profile-has-data' }` y no escribe nada.
510
+ * @type {IdentityApi['joinProfile']}
393
511
  */
394
512
  async joinProfile (acta) { return this._call('joinProfile', { acta }) }
395
- /** Marca este perfil como nacido para ADOPTAR la cuenta de otro (camino A). */
513
+ /**
514
+ * Marca este perfil como nacido para ADOPTAR la cuenta de otro (camino A).
515
+ * @type {IdentityApi['prepareForAdoption']}
516
+ */
396
517
  async prepareForAdoption () { return this._call('prepareForAdoption') }
397
518
  /** MI tarjeta de perfil: lo mínimo que un contacto necesita para cifrarme a todos mis
398
519
  * dispositivos (perfil, versión y llaves). Sin etiquetas ni permisos. */
520
+ /** @type {IdentityApi['profileCard']} */
399
521
  async profileCard () { return this._call('profileCard') }
400
- /** Guarda la tarjeta de otra persona en su ficha de contacto (verificándola). */
522
+ /**
523
+ * Guarda la tarjeta de otra persona en su ficha de contacto (verificándola).
524
+ * @type {IdentityApi['adoptPeerCard']}
525
+ */
401
526
  async adoptPeerCard (card) { return this._call('adoptPeerCard', { card }) }
402
- /** La clave de contenido del perfil, abierta con la llave de cifrado de este dispositivo. */
527
+ /**
528
+ * La clave de contenido del perfil, abierta con la llave de cifrado de este dispositivo.
529
+ * @type {IdentityApi['contentKey']}
530
+ */
403
531
  async contentKey () { return this._call('contentKey') }
404
- /** Cifra con la clave de contenido del perfil (la privada de cifrado no sale del vault). */
532
+ /**
533
+ * Cifra con la clave de contenido del perfil (la privada de cifrado no sale del vault).
534
+ * @type {IdentityApi['sealContent']}
535
+ */
405
536
  async sealContent (plaintext) { return this._call('sealContent', { plaintext }) }
406
- /** Abre un sobre de contenido con el llavero del perfil. */
537
+ /**
538
+ * Abre un sobre de contenido con el llavero del perfil.
539
+ * @type {IdentityApi['openContent']}
540
+ */
407
541
  async openContent (envelope) { return this._call('openContent', { envelope }) }
408
- /** Rota la clave de contenido (corta el acceso al contenido FUTURO de quien ya no está). */
542
+ /**
543
+ * Rota la clave de contenido (corta el acceso al contenido FUTURO de quien ya no está).
544
+ * @type {IdentityApi['rotateContentKey']}
545
+ */
409
546
  async rotateContentKey () { return this._call('rotateContentKey') }
410
547
  /**
411
548
  * Abre un sobre de un CAJÓN DE SECRETOS con la envoltura dirigida a este aparato.
@@ -414,6 +551,7 @@ export class Identity {
414
551
  * y la privada de cifrado de este dispositivo —que nunca sale del iframe— la abre. Es lo
415
552
  * que le permite a quien administra LEER una variable pública sin teclear ninguna
416
553
  * contraseña, y solo las que la bóveda le haya envuelto.
554
+ * @type {IdentityApi['openSealedValue']}
417
555
  */
418
556
  async openSealedValue ({ wrap, envelope } = {}) { return this._call('openSealedValue', { wrap, envelope }) }
419
557
 
@@ -432,6 +570,7 @@ export class Identity {
432
570
  * · `'current'` → sigue con la cuenta abierta; solo vale si nació para adoptar o si ya
433
571
  * está emparejada con esa misma bóveda. Si no, falla antes de tocar la red.
434
572
  * @returns {Promise<{ ok:boolean, deviceId:string, master:string, exp:number, scope:string[] }>}
573
+ * @type {IdentityApi['enrollDevice']}
435
574
  */
436
575
  async enrollDevice (qr, { label = '', join = 'current', account = null } = {}) {
437
576
  // DÓNDE CORRE se mira AQUÍ, en la página, y no dentro del iframe: el iframe no ve si la
@@ -439,12 +578,18 @@ export class Identity {
439
578
  return this._call('vaultPair', { qr, label, join, account, machine: browserMachine() }, 200000)
440
579
  }
441
580
 
442
- /** Estado de emparejamiento: { paired, deviceId?, master?, scope?, exp?, pairedAt? }. */
581
+ /**
582
+ * Estado de emparejamiento: { paired, deviceId?, master?, scope?, exp?, pairedAt? }.
583
+ * @type {IdentityApi['vaultStatus']}
584
+ */
443
585
  async vaultStatus () {
444
586
  return this._call('vaultStatus')
445
587
  }
446
588
 
447
- /** Desvincula este dispositivo del vault (borra la sub-clave + el cert locales). */
589
+ /**
590
+ * Desvincula este dispositivo del vault (borra la sub-clave + el cert locales).
591
+ * @type {IdentityApi['unpairDevice']}
592
+ */
448
593
  async unpairDevice () {
449
594
  return this._call('vaultUnpair')
450
595
  }
@@ -454,6 +599,7 @@ export class Identity {
454
599
  * el cert de este dispositivo. Aditivo y explícito — NO cambia `signData` (local).
455
600
  * Requiere estar emparejado y el vault encendido. Devuelve { signature, publickey }
456
601
  * donde publickey es tu identidad MAESTRA.
602
+ * @type {IdentityApi['vaultSign']}
457
603
  */
458
604
  async vaultSign (payload) {
459
605
  return this._call('vaultSign', { payload }, 20000)
@@ -463,6 +609,7 @@ export class Identity {
463
609
  * Store DELEGADO: lee/escribe el store de hilos+aperturas (appendMessage,
464
610
  * listThread, recordOpen, getOpens, getStats, …) EN tu vault, usando el cert de
465
611
  * este dispositivo. Reusa el mismo emparejamiento. Requiere el vault encendido.
612
+ * @type {IdentityApi['vaultStore']}
466
613
  */
467
614
  async vaultStore (method, args, { wake = true } = {}) {
468
615
  return this._call('vaultStore', { method, args, wake }, 20000)
@@ -479,6 +626,7 @@ export class Identity {
479
626
  *
480
627
  * `args.to`: la llave de comunicación de UNA bóveda de la cuenta (`vault` en el acta), para
481
628
  * hablarle a esa y no a la que conteste primero. Espera más: una alojada dormida tarda.
629
+ * @type {IdentityApi['vaultAdmin']}
482
630
  */
483
631
  async vaultAdmin (op, args) {
484
632
  return this._call('vaultAdmin', { op, ...(args || {}) }, args?.to ? 50000 : 20000)
@@ -494,6 +642,7 @@ export class Identity {
494
642
  *
495
643
  * `args.profile` apunta a OTRA cuenta de este dispositivo (la que diga
496
644
  * `vaultApprovalsAll`); sin él es la activa.
645
+ * @type {IdentityApi['vaultApprovals']}
497
646
  */
498
647
  async vaultApprovals (op, args) {
499
648
  return this._call('vaultApprovals', { op, ...(args || {}) }, 20000)
@@ -509,27 +658,40 @@ export class Identity {
509
658
  * y el icono de la app cambiando a la vista.
510
659
  *
511
660
  * Aprobar uno de otra cuenta: `vaultApprovals('approve', { id, profile })`.
661
+ * @type {IdentityApi['vaultApprovalsAll']}
512
662
  */
513
663
  async vaultApprovalsAll (args) {
514
664
  return this._call('vaultApprovalsAll', args || {}, 30000)
515
665
  }
516
666
 
517
- /** Registra el token de push de la app nativa (FCM/APNs) bajo la llave de este aparato. */
667
+ /**
668
+ * Registra el token de push de la app nativa (FCM/APNs) bajo la llave de este aparato.
669
+ * @type {IdentityApi['registerPush']}
670
+ */
518
671
  async registerPush (args) {
519
672
  return this._call('registerPush', args || {}, 20000)
520
673
  }
521
674
 
522
- /** ¿El cert de este dispositivo le permite aprobar pedidos de la bóveda? */
675
+ /**
676
+ * ¿El cert de este dispositivo le permite aprobar pedidos de la bóveda?
677
+ * @type {IdentityApi['canApproveVault']}
678
+ */
523
679
  async canApproveVault () {
524
680
  return this._call('canApproveVault', {}, 20000)
525
681
  }
526
682
 
527
- /** ¿El cert de este dispositivo le permite administrar el perfil a distancia? */
683
+ /**
684
+ * ¿El cert de este dispositivo le permite administrar el perfil a distancia?
685
+ * @type {IdentityApi['canAdminVault']}
686
+ */
528
687
  async canAdminVault () {
529
688
  return this._call('canAdminVault', {}, 20000)
530
689
  }
531
690
 
532
- /** Lista (solo lectura) los dispositivos enrolados en tu vault: { devices, revoked }. */
691
+ /**
692
+ * Lista (solo lectura) los dispositivos enrolados en tu vault: { devices, revoked }.
693
+ * @type {IdentityApi['listVaultDevices']}
694
+ */
533
695
  async listVaultDevices () {
534
696
  return this._call('listVaultDevices', {}, 20000)
535
697
  }
@@ -538,12 +700,16 @@ export class Identity {
538
700
  * El cert de delegación de este dispositivo (o null si no está emparejado). El
539
701
  * transporte lo presenta al proxy en `identify` → "una identidad": el proxy enruta
540
702
  * los mensajes dirigidos a tu maestra M también a este dispositivo. No tiene secretos.
703
+ * @type {IdentityApi['getVaultCert']}
541
704
  */
542
705
  async getVaultCert () {
543
706
  return this._call('getVaultCert')
544
707
  }
545
708
 
546
- /** Suscribe a eventos de emparejamiento ('vault'): { phase:'challenge'|'paired'|'unpaired', ... }. */
709
+ /**
710
+ * Suscribe a eventos de emparejamiento ('vault'): { phase:'challenge'|'paired'|'unpaired', ... }.
711
+ * @type {IdentityApi['onVault']}
712
+ */
547
713
  onVault (handler) {
548
714
  return this.on('vault', handler)
549
715
  }
@@ -554,19 +720,40 @@ export class Identity {
554
720
  // generar códigos de emparejamiento, aprobar SAS y revocar máquinas — todo por RPC
555
721
  // al iframe. El daemon sólo corre en una pestaña visible a la vez (navigator.locks),
556
722
  // pero los getters (status/pending/machines) y revoke sirven desde cualquier pestaña.
557
- /** { enabled, running }: si el modo self está activado y si esta pestaña sostiene el daemon. */
723
+ /**
724
+ * { enabled, running }: si el modo self está activado y si esta pestaña sostiene el daemon.
725
+ * @type {IdentityApi['selfVaultStatus']}
726
+ */
558
727
  async selfVaultStatus () { return this._call('selfVaultStatus') }
559
- /** Activa/desactiva el modo self-vault en este dispositivo. */
728
+ /**
729
+ * Activa/desactiva el modo self-vault en este dispositivo.
730
+ * @type {IdentityApi['setSelfVault']}
731
+ */
560
732
  async setSelfVault (enabled) { return this._call('setSelfVault', { enabled }) }
561
- /** Genera un código de emparejamiento + QR para enlazar otra máquina. Sólo sirve desde la pestaña activa. */
733
+ /**
734
+ * Genera un código de emparejamiento + QR para enlazar otra máquina. Sólo sirve desde la pestaña activa.
735
+ * @type {IdentityApi['selfVaultPairing']}
736
+ */
562
737
  async selfVaultPairing (opts) { return this._call('selfVaultPairing', opts || {}, 60000) }
563
- /** Lista de solicitudes de emparejamiento pendientes de aprobar. */
738
+ /**
739
+ * Lista de solicitudes de emparejamiento pendientes de aprobar.
740
+ * @type {IdentityApi['selfVaultPending']}
741
+ */
564
742
  async selfVaultPending () { return this._call('selfVaultPending') }
565
- /** Máquinas/agentes enrolados (delegaciones vigentes con scope vault:sign). */
743
+ /**
744
+ * Máquinas/agentes enrolados (delegaciones vigentes con scope vault:sign).
745
+ * @type {IdentityApi['selfVaultMachines']}
746
+ */
566
747
  async selfVaultMachines () { return this._call('selfVaultMachines') }
567
- /** Aprueba una solicitud de emparejamiento comparando el código SAS. */
748
+ /**
749
+ * Aprueba una solicitud de emparejamiento comparando el código SAS.
750
+ * @type {IdentityApi['selfVaultApprove']}
751
+ */
568
752
  async selfVaultApprove (deviceId, code) { return this._call('selfVaultApprove', { deviceId, code }) }
569
- /** Rechaza una solicitud de emparejamiento pendiente. */
753
+ /**
754
+ * Rechaza una solicitud de emparejamiento pendiente.
755
+ * @type {IdentityApi['selfVaultReject']}
756
+ */
570
757
  async selfVaultReject (deviceId) { return this._call('selfVaultReject', { deviceId }) }
571
758
  /**
572
759
  * QUITA una máquina/agente enrolado en esta bóveda. Se le pasa **el aparato**
@@ -575,14 +762,21 @@ export class Identity {
575
762
  * Un `nonce` suelto (string, o `{ nonce }`) retira UN certificado y deja al aparato
576
763
  * dentro del acta: eso no es quitarlo, y quien queda así ya no recibe nunca el aviso
577
764
  * de expulsión. Se acepta por compatibilidad, no como la forma normal.
765
+ * @type {IdentityApi['selfVaultRevoke']}
578
766
  */
579
767
  async selfVaultRevoke (target) {
580
768
  const p = typeof target === 'string' ? { nonce: target } : { sub: target?.sub, nonce: target?.nonce }
581
769
  return this._call('selfVaultRevoke', p)
582
770
  }
583
- /** Presencia online (ping/pong) de las máquinas enroladas. Devuelve { online: [pubkeys] }. */
771
+ /**
772
+ * Presencia online (ping/pong) de las máquinas enroladas. Devuelve { online: [pubkeys] }.
773
+ * @type {IdentityApi['selfVaultProbe']}
774
+ */
584
775
  async selfVaultProbe (pubkeys) { return this._call('selfVaultProbe', { pubkeys }, 10000) }
585
- /** Suscribe a eventos del self-vault ('selfVault'): { running?, pending?, error? }. */
776
+ /**
777
+ * Suscribe a eventos del self-vault ('selfVault'): { running?, pending?, error? }.
778
+ * @type {IdentityApi['onSelfVault']}
779
+ */
586
780
  onSelfVault (handler) { return this.on('selfVault', handler) }
587
781
 
588
782
  // ----- entrar con usuario y contraseña, cuando la bóveda es ESTA pestaña -----
@@ -592,7 +786,10 @@ export class Identity {
592
786
  // tres versiones. Todo esto exige que esta pestaña sea la bóveda activa; si no lo es, se
593
787
  // dice con `code: 'not-the-vault'` en vez de contestar una lista vacía.
594
788
 
595
- /** Los aparatos que se abren con usuario y contraseña, con sus sesiones abiertas. */
789
+ /**
790
+ * Los aparatos que se abren con usuario y contraseña, con sus sesiones abiertas.
791
+ * @type {IdentityApi['selfVaultLogins']}
792
+ */
596
793
  async selfVaultLogins () { return this._call('selfVaultLogins') }
597
794
 
598
795
  /**
@@ -600,10 +797,14 @@ export class Identity {
600
797
  * deriva la llave que cierra el paquete con las privadas del aparato nuevo.
601
798
  *
602
799
  * Devuelve su dirección `nombre@AB12-CD34-EF56`, que es lo que hay que teclear al entrar.
800
+ * @type {IdentityApi['selfVaultLoginAdd']}
603
801
  */
604
802
  async selfVaultLoginAdd (opts) { return this._call('selfVaultLoginAdd', opts || {}, 60000) }
605
803
 
606
- /** Cambia la contraseña: hace falta la vieja, y lo que estuviera abierto se cierra. */
804
+ /**
805
+ * Cambia la contraseña: hace falta la vieja, y lo que estuviera abierto se cierra.
806
+ * @type {IdentityApi['selfVaultLoginPasswd']}
807
+ */
607
808
  async selfVaultLoginPasswd (opts) { return this._call('selfVaultLoginPasswd', opts || {}, 60000) }
608
809
 
609
810
  // ----- el RESPALDO, cuando la bóveda es ESTA pestaña (solo desde la consola) -----
@@ -611,22 +812,43 @@ export class Identity {
611
812
  // Bóveda abierta y origen de la consola (`vault.dotrino.com`): cualquier otro recibe
612
813
  // `code: 'not-the-console'`. El archivo vuelve YA CIFRADO con la contraseña dada.
613
814
 
614
- /** Los cajones que hay: `[{ owner, count, device? }]`. */
815
+ /**
816
+ * Los cajones que hay: `[{ owner, count, device? }]`.
817
+ * @type {IdentityApi['selfVaultBackupDrawers']}
818
+ */
615
819
  async selfVaultBackupDrawers () { return this._call('selfVaultBackupDrawers', {}, 30000) }
616
- /** Exporta todo (`drawers: null`) o esos cajones. Devuelve `{ file, summary }`. */
820
+ /**
821
+ * Exporta todo (`drawers: null`) o esos cajones. Devuelve `{ file, summary }`.
822
+ * @type {IdentityApi['selfVaultBackupExport']}
823
+ */
617
824
  async selfVaultBackupExport (opts) { return this._call('selfVaultBackupExport', opts || {}, 120000) }
618
- /** El plan de importar `file` (qué es nuevo, igual o choca). No escribe nada. */
825
+ /**
826
+ * El plan de importar `file` (qué es nuevo, igual o choca). No escribe nada.
827
+ * @type {IdentityApi['selfVaultBackupPlan']}
828
+ */
619
829
  async selfVaultBackupPlan (opts) { return this._call('selfVaultBackupPlan', opts || {}, 120000) }
620
- /** Importa. Con un choque sin decidir lanza `BACKUP_CONFLICTS` y no escribe nada. */
830
+ /**
831
+ * Importa. Con un choque sin decidir lanza `BACKUP_CONFLICTS` y no escribe nada.
832
+ * @type {IdentityApi['selfVaultBackupImport']}
833
+ */
621
834
  async selfVaultBackupImport (opts) { return this._call('selfVaultBackupImport', opts || {}, 120000) }
622
835
 
623
- /** Cierra un inicio de sesión abierto (sin `sid`, todos los de ese usuario). */
836
+ /**
837
+ * Cierra un inicio de sesión abierto (sin `sid`, todos los de ese usuario).
838
+ * @type {IdentityApi['selfVaultLoginClose']}
839
+ */
624
840
  async selfVaultLoginClose (opts) { return this._call('selfVaultLoginClose', opts || {}) }
625
841
 
626
- /** Quita la espera que dejan los intentos fallidos. */
842
+ /**
843
+ * Quita la espera que dejan los intentos fallidos.
844
+ * @type {IdentityApi['selfVaultLoginUnblock']}
845
+ */
627
846
  async selfVaultLoginUnblock (user) { return this._call('selfVaultLoginUnblock', { user }) }
628
847
 
629
- /** Lo quita, y saca su llave del acta: las dos cosas, o ninguna. */
848
+ /**
849
+ * Lo quita, y saca su llave del acta: las dos cosas, o ninguna.
850
+ * @type {IdentityApi['selfVaultLoginRemove']}
851
+ */
630
852
  async selfVaultLoginRemove (user) { return this._call('selfVaultLoginRemove', { user }, 30000) }
631
853
 
632
854
  // ----- multi-perfil por dispositivo -----
@@ -640,9 +862,13 @@ export class Identity {
640
862
  * le deja aprobar pedidos. Los dos salen de leer el cert guardado de cada perfil, sin
641
863
  * cambiar el activo ni firmar nada — es lo que necesita la pantalla de Pedidos para
642
864
  * saber a QUÉ perfil pertenece lo que timbró el teléfono.
865
+ * @type {IdentityApi['listProfiles']}
643
866
  */
644
867
  async listProfiles () { return this._call('listProfiles') }
645
- /** El perfil activo: { id, name, pubkey }. */
868
+ /**
869
+ * El perfil activo: { id, name, pubkey }.
870
+ * @type {IdentityApi['currentProfile']}
871
+ */
646
872
  async currentProfile () { return this._call('currentProfile') }
647
873
  /**
648
874
  * Crea un perfil nuevo (identidad fresca) y lo deja activo. La app debe recargar.
@@ -650,13 +876,23 @@ export class Identity {
650
876
  * `forVault: true` lo marca como **nacido para adoptar** la cuenta de una bóveda (camino B
651
877
  * de `vinculacion-de-cuentas.md`): es el único permiso que acepta `joinProfile`, y se
652
878
  * consume al unirse. Sin esa marca, la cuenta es de este dispositivo y nadie se la lleva.
879
+ * @type {IdentityApi['createProfile']}
653
880
  */
654
881
  async createProfile (name, { forVault = false } = {}) { return this._call('createProfile', { name, forVault }) }
655
- /** Cambia el perfil activo. La app debe recargar la página. */
882
+ /**
883
+ * Cambia el perfil activo. La app debe recargar la página.
884
+ * @type {IdentityApi['switchProfile']}
885
+ */
656
886
  async switchProfile (id) { return this._call('switchProfile', { id }) }
657
- /** Renombra un perfil (o el activo si no se pasa id). */
887
+ /**
888
+ * Renombra un perfil (o el activo si no se pasa id).
889
+ * @type {IdentityApi['renameProfile']}
890
+ */
658
891
  async renameProfile (id, name) { return this._call('renameProfile', { id, name }) }
659
- /** Borra un perfil y sus datos (no el único). */
892
+ /**
893
+ * Borra un perfil y sus datos (no el único).
894
+ * @type {IdentityApi['deleteProfile']}
895
+ */
660
896
  async deleteProfile (id) { return this._call('deleteProfile', { id }) }
661
897
 
662
898
  // ----- entrar con usuario y contraseña (`temporary-access.md`) -----
@@ -673,17 +909,22 @@ export class Identity {
673
909
  * La contraseña no sale de aquí: se comprueba con OPAQUE, que no la manda ni deja
674
910
  * adivinarla. Los errores llegan con su `code`: `login-failed` (dirección o contraseña),
675
911
  * `too-many-tries` (con `waitMs`), `no-vault` (ninguna bóveda encendida en esa dirección).
912
+ * @type {IdentityApi['loginWithPassword']}
676
913
  */
677
- async loginWithPassword ({ address, password, remember = false, label = '', proxyUrl = null } = {}) {
914
+ async loginWithPassword ({ address, password, remember = false, label = '', proxyUrl = null } = /** @type {any} */ ({})) {
678
915
  return this._call('loginWithPassword', { address, password, remember, label, proxyUrl }, 60000)
679
916
  }
680
917
 
681
- /** SALIR del inicio de sesión con contraseña (el activo, o el que digas). Recargar después. */
918
+ /**
919
+ * SALIR del inicio de sesión con contraseña (el activo, o el que digas). Recargar después.
920
+ * @type {IdentityApi['logoutLogin']}
921
+ */
682
922
  async logoutLogin (id = null) { return this._call('logoutLogin', { id }, 30000) }
683
923
 
684
924
  /**
685
925
  * Merge endorsements (signed ratings from third parties) about a subject
686
926
  * into the local peer book. Returns { merged, total }.
927
+ * @type {IdentityApi['mergeEndorsements']}
687
928
  */
688
929
  async mergeEndorsements (subject, endorsements, askerPubkey) {
689
930
  return this._call('mergeEndorsements', { subject, endorsements, askerPubkey })
@@ -692,6 +933,7 @@ export class Identity {
692
933
  /**
693
934
  * Return what this vault knows about a subject for the purpose of
694
935
  * answering a RATING_QUERY: { mine: signedEnvelopeOrNull, endorsements: [] }.
936
+ * @type {IdentityApi['getRatingsForSubject']}
695
937
  */
696
938
  async getRatingsForSubject (subject) {
697
939
  return this._call('getRatingsForSubject', { subject })
@@ -699,12 +941,16 @@ export class Identity {
699
941
 
700
942
  /**
701
943
  * Record that a peer asked us about a subject. Used for suspicion stats.
944
+ * @type {IdentityApi['recordQuery']}
702
945
  */
703
946
  async recordQuery (askerPubkey, subject) {
704
947
  return this._call('recordQuery', { askerPubkey, subject })
705
948
  }
706
949
 
707
- /** Update own nickname (broadcast to the vault, not to other apps automatically) */
950
+ /**
951
+ * Update own nickname (broadcast to the vault, not to other apps automatically)
952
+ * @type {IdentityApi['setMyNickname']}
953
+ */
708
954
  async setMyNickname (nickname) {
709
955
  const result = await this._call('setMyNickname', { nickname })
710
956
  if (result?.me) this._me = result.me
@@ -717,6 +963,7 @@ export class Identity {
717
963
  * `avatar` = data-URI 250×250 (o null para quitarla); `links`/`fields` = arrays con `visible`
718
964
  * por ítem (oculto = no se comparte). `telefono`/`direccion` son sensibles: ocultos por
719
965
  * defecto (solo se comparten si su flag === true). No pisa lo que no mandes.
966
+ * @type {IdentityApi['updateMe']}
720
967
  */
721
968
  async updateMe (patch) {
722
969
  const result = await this._call('updateMe', { patch })
@@ -724,9 +971,15 @@ export class Identity {
724
971
  return result
725
972
  }
726
973
 
727
- /** Tu `me` completo (incluye ocultos). */
974
+ /**
975
+ * Tu `me` completo (incluye ocultos).
976
+ * @type {IdentityApi['getMe']}
977
+ */
728
978
  async getMe () { return this._call('getMe') }
729
- /** Subconjunto PÚBLICO de tu perfil (solo lo visible) — para compartir/publicar. */
979
+ /**
980
+ * Subconjunto PÚBLICO de tu perfil (solo lo visible) — para compartir/publicar.
981
+ * @type {IdentityApi['publicMe']}
982
+ */
730
983
  async publicMe () { return this._call('publicMe') }
731
984
  /**
732
985
  * CÓMO FUE EL ÚLTIMO EMPUJÓN del perfil a la bóveda: `{ ok, at, error }`.
@@ -734,10 +987,14 @@ export class Identity {
734
987
  * El núcleo lo lleva desde la fase 3 y aquí no estaba, así que una app no podía
735
988
  * preguntarlo — que es justo para lo que se guardó: poder decir «esto no se guardó» en
736
989
  * vez de enseñar tan tranquila un perfil que solo vive en este aparato.
990
+ * @type {IdentityApi['profilePushState']}
737
991
  */
738
992
  async profilePushState () { return this._call('profilePushState') }
739
993
 
740
- /** Pubkey ECDH (JWK string) propio para encripción. */
994
+ /**
995
+ * Pubkey ECDH (JWK string) propio para encripción.
996
+ * @type {IdentityApi['getEncryptionPubkey']}
997
+ */
741
998
  async getEncryptionPubkey () {
742
999
  return this._call('getEncryptionPubkey')
743
1000
  }
@@ -747,6 +1004,7 @@ export class Identity {
747
1004
  * @param {Array<{token:string, encryptionPubkey:string}>} recipients
748
1005
  * @param {string} plaintext
749
1006
  * @returns {Promise<Object>} Envelope { v, iv, ct, wrap }
1007
+ * @type {IdentityApi['encrypt']}
750
1008
  */
751
1009
  async encrypt (recipients, plaintext) {
752
1010
  return this._call('encrypt', { recipients, plaintext })
@@ -757,6 +1015,7 @@ export class Identity {
757
1015
  * @param {string} senderEncryptionPubkey JWK string del emisor
758
1016
  * @param {string} myToken token efímero al que iba dirigido el wrap
759
1017
  * @param {Object} envelope
1018
+ * @type {IdentityApi['decrypt']}
760
1019
  */
761
1020
  async decrypt (senderEncryptionPubkey, myToken, envelope) {
762
1021
  return this._call('decrypt', { senderEncryptionPubkey, myToken, envelope })
@@ -766,6 +1025,7 @@ export class Identity {
766
1025
  * Export the full identity (private key + peer book) as a JSON-serializable object.
767
1026
  * The blob can be saved to a file by the host app and re-imported later.
768
1027
  * The private key is sensitive — handle accordingly.
1028
+ * @type {IdentityApi['exportIdentity']}
769
1029
  */
770
1030
  async exportIdentity () {
771
1031
  return this._call('exportIdentity')
@@ -774,6 +1034,7 @@ export class Identity {
774
1034
  /**
775
1035
  * Import a previously exported identity blob, replacing the current one.
776
1036
  * Throws if the blob is malformed or keys are invalid.
1037
+ * @type {IdentityApi['importIdentity']}
777
1038
  */
778
1039
  async importIdentity (blob) {
779
1040
  const result = await this._call('importIdentity', blob)
@@ -787,11 +1048,13 @@ export class Identity {
787
1048
  * Connect a Google account for encrypted backup to Drive's appDataFolder.
788
1049
  * Pops up a Google sign-in window. `clientId` is your Google OAuth Web client ID
789
1050
  * with Authorized JavaScript Origin = the vault origin (id.dotrino.com).
1051
+ * @type {IdentityApi['syncConnect']}
790
1052
  */
791
1053
  async syncConnect (clientId) {
792
1054
  return this._call('syncConnect', { clientId })
793
1055
  }
794
1056
 
1057
+ /** @type {IdentityApi['syncDisconnect']} */
795
1058
  async syncDisconnect () {
796
1059
  return this._call('syncDisconnect')
797
1060
  }
@@ -800,21 +1063,29 @@ export class Identity {
800
1063
  * Unlock auto-sync by providing the passphrase used to encrypt the backup.
801
1064
  * Must be ≥ 8 chars. After unlock the sync engine pulls remote, merges,
802
1065
  * and pushes on every local change (debounced).
1066
+ * @type {IdentityApi['syncUnlock']}
803
1067
  */
804
1068
  async syncUnlock (passphrase) {
805
1069
  return this._call('syncUnlock', { passphrase })
806
1070
  }
807
1071
 
1072
+ /** @type {IdentityApi['syncLock']} */
808
1073
  async syncLock () {
809
1074
  return this._call('syncLock')
810
1075
  }
811
1076
 
812
- /** { connected, unlocked, dirty, lastError } */
1077
+ /**
1078
+ * { connected, unlocked, dirty, lastError }
1079
+ * @type {IdentityApi['syncStatus']}
1080
+ */
813
1081
  async syncStatus () {
814
1082
  return this._call('syncStatus')
815
1083
  }
816
1084
 
817
- /** Force an immediate pull-then-push cycle. */
1085
+ /**
1086
+ * Force an immediate pull-then-push cycle.
1087
+ * @type {IdentityApi['syncNow']}
1088
+ */
818
1089
  async syncNow () {
819
1090
  return this._call('syncNow')
820
1091
  }
@@ -824,18 +1095,23 @@ export class Identity {
824
1095
  * `{ kind, status, error?, ts }` where status is one of
825
1096
  * 'connected' | 'disconnected' | 'unlocked' | 'locked' | 'syncing' |
826
1097
  * 'synced' | 'conflict' | 'offline' | 'error'.
1098
+ * @type {IdentityApi['onSync']}
827
1099
  */
828
1100
  onSync (handler) {
829
1101
  return this.on('sync', handler)
830
1102
  }
831
1103
 
1104
+ /** @type {IdentityApi['on']} */
832
1105
  on (event, handler) {
833
1106
  if (!this._listeners) this._listeners = new Map()
834
- if (!this._listeners.has(event)) this._listeners.set(event, new Set())
835
- this._listeners.get(event).add(handler)
836
- return () => this._listeners.get(event)?.delete(handler)
1107
+ const listeners = this._listeners
1108
+ let set = listeners.get(event)
1109
+ if (!set) { set = new Set(); listeners.set(event, set) }
1110
+ set.add(handler)
1111
+ return () => this._listeners?.get(event)?.delete(handler)
837
1112
  }
838
1113
 
1114
+ /** @param {string} event @param {any} payload */
839
1115
  _emit (event, payload) {
840
1116
  const set = this._listeners?.get(event)
841
1117
  if (!set) return
@@ -844,9 +1120,16 @@ export class Identity {
844
1120
  }
845
1121
  }
846
1122
 
1123
+ /**
1124
+ * @param {string} method
1125
+ * @param {Record<string, any>} [params]
1126
+ * @param {number} [timeoutMs]
1127
+ * @returns {Promise<any>}
1128
+ */
847
1129
  _call (method, params = {}, timeoutMs = this.timeoutMs) {
848
1130
  return new Promise((resolve, reject) => {
849
- if (!this._iframe?.contentWindow) {
1131
+ const win = this._iframe?.contentWindow
1132
+ if (!win) {
850
1133
  return reject(new Error('Vault not ready'))
851
1134
  }
852
1135
  const id = `req_${this._nextId++}`
@@ -864,7 +1147,7 @@ export class Identity {
864
1147
  // lo cual es la defensa real. El contenido de los mensajes salientes
865
1148
  // no contiene secretos (solo nombres de método y params); las claves
866
1149
  // privadas viven en el localStorage de la propia vault.
867
- this._iframe.contentWindow.postMessage(
1150
+ win.postMessage(
868
1151
  { _cci: true, type: 'request', id, method, params },
869
1152
  '*'
870
1153
  )