@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
@@ -18,12 +18,14 @@
18
18
  * `save`, `remove`. La app solo le enseña el puente a `https://id.dotrino.com`.
19
19
  */
20
20
 
21
+ /** @param {ArrayBuffer | Uint8Array} buf @returns {string} */
21
22
  const b64 = (buf) => {
22
23
  const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf)
23
24
  let s = ''
24
25
  for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i])
25
26
  return btoa(s)
26
27
  }
28
+ /** @param {string} str @returns {Uint8Array<ArrayBuffer>} */
27
29
  const fromB64 = (str) => {
28
30
  const bin = atob(str)
29
31
  const out = new Uint8Array(bin.length)
@@ -35,6 +37,7 @@ const SIGN_SUFFIX = '.keypair'
35
37
  const ENC_SUFFIX = '.enc-keypair'
36
38
 
37
39
  /** El nombre de la OTRA mitad del mismo perfil: firma y cifrado comparten llave en el chip. */
40
+ /** @param {string} name @returns {string | null} */
38
41
  function siblingName (name) {
39
42
  if (name.endsWith(ENC_SUFFIX)) return name.slice(0, -ENC_SUFFIX.length) + SIGN_SUFFIX
40
43
  if (name.endsWith(SIGN_SUFFIX)) return name.slice(0, -SIGN_SUFFIX.length) + ENC_SUFFIX
@@ -42,19 +45,30 @@ function siblingName (name) {
42
45
  }
43
46
 
44
47
  /** El asa de una llave del chip. Lo que la app no pueda hacer sale con su `code`, sin plan B. */
48
+ /**
49
+ * @typedef {{ call (method: string, params?: any): Promise<any> }} AppBridge
50
+ */
51
+
52
+ /**
53
+ * @param {AppBridge} bridge
54
+ * @param {string} kid
55
+ */
45
56
  export function externalHandle (bridge, kid) {
46
57
  return {
47
- external: true,
58
+ external: /** @type {true} */ (true),
48
59
  kid,
60
+ /** @param {Uint8Array} bytes @returns {Promise<string>} */
49
61
  async sign (bytes) {
50
62
  const { signature } = await bridge.call('sign', { kid, data: b64(bytes) })
51
63
  return signature
52
64
  },
65
+ /** @param {string} peerPubJwkStr @returns {Promise<ArrayBuffer>} */
53
66
  async deriveBits (peerPubJwkStr) {
54
67
  const { bits } = await bridge.call('deriveBits', { kid, peer: peerPubJwkStr })
55
68
  return fromB64(bits).buffer
56
69
  },
57
70
  /** Tras emparejar: la app guarda la cuenta para su pantalla de Pedidos. */
71
+ /** @param {Record<string, any>} account */
58
72
  async paired (account) { return bridge.call('save', { kid, ...account }) }
59
73
  }
60
74
  }
@@ -63,13 +77,21 @@ export function externalHandle (bridge, kid) {
63
77
  * Envuelve `keyStore` para que las llaves NUEVAS nazcan en el chip. Las que ya existían
64
78
  * (CryptoKey de IndexedDB) siguen igual: una llave no extraíble no se puede mover.
65
79
  */
80
+ /**
81
+ * @param {import('./core.js').KeyStore} keyStore
82
+ * @param {AppBridge} bridge
83
+ * @returns {import('./core.js').KeyStore}
84
+ */
66
85
  export function withExternalKeys (keyStore, bridge) {
86
+ /** @param {any} rec */
67
87
  const toHandle = (rec) => (rec && rec.external
68
88
  ? { privateKey: externalHandle(bridge, rec.external), publicJwk: rec.publicJwk }
69
89
  : rec)
70
90
  return {
91
+ /** @param {string} name */
71
92
  async get (name) { return toHandle(await keyStore.get(name)) },
72
- set: (name, pair) => keyStore.set(name, pair),
93
+ set: (/** @type {string} */ name, /** @type {any} */ pair) => keyStore.set(name, pair),
94
+ /** @param {string} name */
73
95
  async remove (name) {
74
96
  const rec = await keyStore.get(name)
75
97
  await keyStore.remove(name)
@@ -86,7 +108,9 @@ export function withExternalKeys (keyStore, bridge) {
86
108
  * acta (es la cadena con la que esa llave es miembro). Si la bóveda no entrega la de
87
109
  * cifrado (`enc.privateJwk` nulo), la app estrena una y devuelve su pública.
88
110
  */
111
+ /** @param {{ sign: { name: string, privateJwk: JsonWebKey, publickey: string }, enc: { name: string, privateJwk: JsonWebKey | null, publickey: string | null } }} pair */
89
112
  async importPair ({ sign, enc }) {
113
+ /** @type {{ sign: JsonWebKey, publickey: string, enc?: JsonWebKey, encPub?: string | null }} */
90
114
  const params = { sign: sign.privateJwk, publickey: sign.publickey }
91
115
  if (enc.privateJwk) { params.enc = enc.privateJwk; params.encPub = enc.publickey }
92
116
  const k = await bridge.call('import', params)
@@ -94,6 +118,7 @@ export function withExternalKeys (keyStore, bridge) {
94
118
  await keyStore.set(sign.name, { external: k.kid, kind: 'sign', publicJwk: JSON.parse(sign.publickey) })
95
119
  await keyStore.set(enc.name, { external: k.kid, kind: 'enc', publicJwk: JSON.parse(enc.publickey || k.encPub) })
96
120
  },
121
+ /** @param {'sign' | 'enc'} kind @param {string} name */
97
122
  async create (kind, name) {
98
123
  // Las dos mitades del perfil van bajo la MISMA llave del chip: si la otra ya nació
99
124
  // allí, se reutiliza; si no, se crea una nueva.
@@ -116,8 +141,14 @@ export function withExternalKeys (keyStore, bridge) {
116
141
  * `addWebMessageListener` de Android). Mensajes `{ id, method, params }` → `{ id, result }`
117
142
  * o `{ id, error, code }`.
118
143
  */
144
+ /**
145
+ * @param {{ onmessage: ((ev: { data: string }) => void) | null, postMessage (data: string): void }} port
146
+ * @param {{ timeoutMs?: number }} [opts]
147
+ * @returns {AppBridge}
148
+ */
119
149
  export function appBridge (port, { timeoutMs = 20000 } = {}) {
120
150
  let seq = 0
151
+ /** @type {Map<string, { resolve: (v: any) => void, reject: (e: Error) => void, t: ReturnType<typeof setTimeout> }>} */
121
152
  const waiting = new Map()
122
153
  port.onmessage = (ev) => {
123
154
  let m
@@ -130,6 +161,7 @@ export function appBridge (port, { timeoutMs = 20000 } = {}) {
130
161
  else w.resolve(m.result)
131
162
  }
132
163
  return {
164
+ /** @param {string} method @param {any} [params] @returns {Promise<any>} */
133
165
  call (method, params = {}) {
134
166
  const id = 'k' + (++seq)
135
167
  return new Promise((resolve, reject) => {
package/vault/facade.js CHANGED
@@ -6,18 +6,23 @@
6
6
  * iframe o la extensión, y la bóveda lo envuelve con esto. Una sola envoltura, para que la
7
7
  * bóveda llame a lo mismo en las tres versiones.
8
8
  */
9
+ /** @typedef {Awaited<ReturnType<typeof import('./core.js').createIdentityCore>>} IdentityCore */
10
+
9
11
  export class IdentityFacade {
10
- /** @param {object} [core] el resultado de `createIdentityCore` */
12
+ /** @param {IdentityCore | null} [core] el resultado de `createIdentityCore` */
11
13
  constructor (core = null) {
14
+ /** @type {IdentityCore | null} */
12
15
  this._core = core
16
+ /** @type {Map<string, Set<(payload: any) => void>>} */
13
17
  this._listeners = new Map()
14
18
  if (core) this._wire()
15
19
  }
16
20
 
17
21
  /** Engancha los eventos del core a `on()`. Lo llama quien pone el core. */
18
22
  _wire () {
19
- this._core.onSyncStatus?.((payload) => this._emit('sync', payload))
20
- this._core.onVaultEvent?.((payload) => this._emit('vault', payload))
23
+ const core = /** @type {any} */ (this._core)
24
+ core.onSyncStatus?.((/** @type {any} */ payload) => this._emit('sync', payload))
25
+ core.onVaultEvent?.((/** @type {any} */ payload) => this._emit('vault', payload))
21
26
  }
22
27
 
23
28
  destroy () { this._core = null }
@@ -31,48 +36,83 @@ export class IdentityFacade {
31
36
  sealMasterKey () { return this._core?.sealMasterKey?.() }
32
37
  /** Vuelve a cargar el par tras abrir el candado, sin reabrir la identidad. */
33
38
  reloadMasterKey () { return this._core?.reloadMasterKey?.() }
34
- /** Ver `core.js`: al abrir, los aparatos muertos salen del acta en una sola. */
39
+ /**
40
+ * Ver `core.js`: al abrir, los aparatos muertos salen del acta en una sola.
41
+ * @param {number} now
42
+ */
35
43
  pruneExpiredDevices (now) { return this._core?.pruneExpiredDevices?.(now) }
36
44
  /** Ver `core.js`: al abrir, la clave de contenido llega a todos los miembros. */
37
45
  completeKeyring () { return this._core?.completeKeyring?.() }
38
46
 
47
+ /** @param {string} method @param {any} [params] @returns {any} */
39
48
  _h (method, params = {}) {
40
49
  if (!this._core) throw new Error('Identity not ready — call ready()/connect() first')
41
- return this._core.handlers[method](params)
50
+ return /** @type {Record<string, (params: any) => any>} */ (this._core.handlers)[method](params)
42
51
  }
43
52
 
44
53
  // ----- API pública (espeja src/index.js) -----
45
54
 
46
55
  makeChallenge () { return this._h('makeChallenge') }
56
+ /** @param {string} nonce */
47
57
  signChallenge (nonce) { return this._h('signChallenge', { nonce }) }
58
+ /** @param {{ nonce: string, publickey: string, signature: string, encryptionPubkey?: string }} args */
48
59
  verifyResponse ({ nonce, publickey, signature, encryptionPubkey }) {
49
60
  return this._h('verifyResponse', { nonce, publickey, signature, encryptionPubkey })
50
61
  }
62
+ /** @param {string} publickey */
51
63
  getPeer (publickey) { return this._h('getPeer', { publickey }) }
64
+ /**
65
+ * @param {string} publickey
66
+ * @param {string} nickname
67
+ */
52
68
  setNickname (publickey, nickname) { return this._h('setNickname', { publickey, nickname }) }
69
+ /**
70
+ * @param {string} publickey
71
+ * @param {boolean} blocked
72
+ */
53
73
  setBlocked (publickey, blocked) { return this._h('setBlocked', { publickey, blocked }) }
74
+ /**
75
+ * @param {string} publickey
76
+ * @param {number} rating
77
+ * @param {string} notes
78
+ */
54
79
  setRating (publickey, rating, notes) { return this._h('setRating', { publickey, rating, notes }) }
55
80
  listPeers () { return this._h('listPeers') }
81
+ /** @param {string} publickey */
56
82
  forgetPeer (publickey) { return this._h('forgetPeer', { publickey }) }
57
- addContact ({ publickey, nickname, encryptionPubkey, lastToken, notes } = {}) {
83
+ /** @param {{ publickey: string, nickname?: string, encryptionPubkey?: string, lastToken?: string, notes?: string }} args */
84
+ addContact ({ publickey, nickname, encryptionPubkey, lastToken, notes } = /** @type {any} */ ({})) {
58
85
  return this._h('addContact', { publickey, nickname, encryptionPubkey, lastToken, notes })
59
86
  }
87
+ /**
88
+ * @param {string} publickey
89
+ * @param {Record<string, any>} patch
90
+ */
60
91
  updateContact (publickey, patch) { return this._h('updateContact', { publickey, patch }) }
92
+ /** @param {string} publickey */
61
93
  removeContact (publickey) { return this._h('removeContact', { publickey }) }
62
94
  listContacts () { return this._h('listContacts') }
95
+ /** @param {any} data */
63
96
  signData (data) { return this._h('signData', { data }) }
64
97
  /**
65
98
  * Prueba firmada con destinatario y vigencia (ver `vault/assertion.js`). Un servicio en
66
99
  * Node la pide igual que una app: `{ audience, nonce, scopes?, ttlMs? }`.
100
+ *
101
+ * @param {{ audience: string, nonce: string, scopes?: string[], ttlMs?: number }} args
67
102
  */
68
- async requestAssertion ({ audience, nonce, scopes, ttlMs } = {}) {
103
+ async requestAssertion ({ audience, nonce, scopes, ttlMs } = /** @type {any} */ ({})) {
69
104
  const { assertion } = await this._h('requestAssertion', { audience, nonce, scopes, ttlMs })
70
105
  return assertion
71
106
  }
72
107
  // Delegación de capacidad (sub-clave de dispositivo con scope/exp/revocación)
108
+ /** @param {string} sub @param {string | string[]} scope @param {Record<string, any>} [opts] */
73
109
  signDelegation (sub, scope, opts = {}) { return this._h('signDelegation', { sub, scope, ...opts }) }
110
+ /** @param {string} nonce */
74
111
  revokeDelegation (nonce) { return this._h('revokeDelegation', { nonce }) }
75
- /** Quitar el DISPOSITIVO: retira todos sus certificados vigentes, no solo uno. */
112
+ /**
113
+ * Quitar el DISPOSITIVO: retira todos sus certificados vigentes, no solo uno.
114
+ * @param {string} sub
115
+ */
76
116
  revokeDevice (sub) { return this._h('revokeDevice', { sub }) }
77
117
  listDelegations () { return this._h('listDelegations') }
78
118
  // Acta de perfil (qué llaves son del perfil y qué puede cada una; ver acta-de-perfil.md)
@@ -87,14 +127,27 @@ export class IdentityFacade {
87
127
  * este puente es en-proceso: al navegador no se le puede pasar una función, y tampoco
88
128
  * la necesita — no sella secretos de nadie.
89
129
  */
90
- /** Abre un sobre sellado A ESTE aparato (envoltura + sobre). Ver `core.js`. */
130
+ /**
131
+ * Abre un sobre sellado A ESTE aparato (envoltura + sobre). Ver `core.js`.
132
+ * @param {any} wrap
133
+ * @param {any} envelope
134
+ */
91
135
  openSealedValue (wrap, envelope) { return this._h('openSealedValue', { wrap, envelope }) }
92
- /** Re-envuelve para otro miembro una llave que este aparato ya puede abrir. */
136
+ /**
137
+ * Re-envuelve para otro miembro una llave que este aparato ya puede abrir.
138
+ * @param {any} wrap
139
+ * @param {string} encPub
140
+ */
93
141
  rewrapFor (wrap, encPub) { return this._h('rewrapFor', { wrap, encPub }) }
142
+ /** @param {any} provider */
94
143
  setSealKeyProvider (provider) { return this._h('setSealKeyProvider', { provider }) }
95
144
  /** Estrena la llave de sellado en un acta nueva, sin tocar a ningún miembro. */
96
145
  rotateSealKey () { return this._h('rotateSealKey') }
97
- /** Con qué llave se comprueban los sobres que se firmaron con el acta `seq`. */
146
+ /**
147
+ * Con qué llave se comprueban los sobres que se firmaron con el acta `seq`.
148
+ * @param {number} seq
149
+ * @param {string | null} [vault]
150
+ */
98
151
  sealKeyAt (seq, vault = null) { return this._h('sealKeyAt', { seq, vault }) }
99
152
  myMembership () { return this._h('myMembership') }
100
153
  /**
@@ -106,104 +159,209 @@ export class IdentityFacade {
106
159
  * —que es lo que manda SIEMPRE un navegador ya emparejado— reventaba con
107
160
  * «is not a function», la bóveda respondía error, y el aparato NUNCA volvía a
108
161
  * sincronizar su acta. Se quedaba con la copia del día que emparejó.
162
+ * @param {any} opts
109
163
  */
110
164
  actaHistory (opts) { return this._h('actaHistory', opts || {}) }
111
165
  /** Los que estuvieron en las actas de la ventana y el acta actual ya no nombra. */
112
166
  pastMembers () { return this._h('pastMembers') }
113
167
  isMaster () { return this._h('isMaster') }
168
+ /** @param {any} member */
114
169
  admitMember (member) { return this._h('admitMember', member) }
115
- /** Registra la llave de cifrado de un miembro ya admitido (evita re-enrolarlo). */
170
+ /**
171
+ * Registra la llave de cifrado de un miembro ya admitido (evita re-enrolarlo).
172
+ * @param {any} args
173
+ */
116
174
  setMemberEncPub (args) { return this._h('setMemberEncPub', args) }
117
- /** Dice de qué bóveda es una llave de comunicación ya admitida. */
175
+ /**
176
+ * Dice de qué bóveda es una llave de comunicación ya admitida.
177
+ * @param {any} args
178
+ */
118
179
  setMemberVault (args) { return this._h('setMemberVault', args) }
180
+ /**
181
+ * @param {string} pub
182
+ * @param {string[]} caps
183
+ */
119
184
  setCaps (pub, caps) { return this._h('setCaps', { pub, caps }) }
185
+ /** @param {any} changes */
120
186
  setCapsMany (changes) { return this._h('setCapsMany', { changes }) }
187
+ /**
188
+ * @param {string} pub
189
+ * @param {string} label
190
+ */
121
191
  setLabel (pub, label) { return this._h('setLabel', { pub, label }) }
192
+ /** @param {string} pub */
122
193
  removeMember (pub) { return this._h('removeMember', { pub }) }
194
+ /**
195
+ * @param {string} to
196
+ * @param {any} [member]
197
+ */
123
198
  handoverMaster (to, member = null) { return this._h('handoverMaster', { to, member }) }
199
+ /** @param {string[]} caps */
124
200
  renounceCaps (caps) { return this._h('renounceCaps', { caps }) }
201
+ /** @param {any} record */
125
202
  absorbRenounce (record) { return this._h('absorbRenounce', { record }) }
203
+ /** @param {any} acta */
126
204
  adoptActa (acta) { return this._h('adoptActa', { acta }) }
127
- /** Adopta una cadena de actas, eslabón a eslabón (para ponerse al día tras estar apagado). */
205
+ /**
206
+ * Adopta una cadena de actas, eslabón a eslabón (para ponerse al día tras estar apagado).
207
+ * @param {any[]} chain
208
+ */
128
209
  adoptActaChain (chain) { return this._h('adoptActaChain', { chain }) }
129
- /** Se pone al día por la cadena de selladoras: sin las actas de en medio, desde la que se tiene. */
210
+ /**
211
+ * Se pone al día por la cadena de selladoras: sin las actas de en medio, desde la que se tiene.
212
+ * @param {any[]} sealerChain
213
+ */
130
214
  adoptActaBySealerChain (sealerChain) { return this._h('adoptActaBySealerChain', { sealerChain }) }
131
- /** Completa el historial con las actas que falten detrás de la vigente, comprobadas por hash. */
215
+ /**
216
+ * Completa el historial con las actas que falten detrás de la vigente, comprobadas por hash.
217
+ * @param {any[]} actas
218
+ */
132
219
  fillActaHistory (actas) { return this._h('fillActaHistory', { actas }) }
133
- /** Las últimas actas guardadas, con la vigente. */
220
+ /**
221
+ * Las últimas actas guardadas, con la vigente.
222
+ * @param {number} count
223
+ */
134
224
  recentActas (count) { return this._h('recentActas', { count }) }
135
- /** Une ESTE perfil a la cuenta de otro (solo si nació para eso: `createProfile(n, { forVault: true })`). */
225
+ /**
226
+ * Une ESTE perfil a la cuenta de otro (solo si nació para eso: `createProfile(n, { forVault: true })`).
227
+ * @param {any} acta
228
+ */
136
229
  joinProfile (acta) { return this._h('joinProfile', { acta }) }
137
230
  /** Marca este perfil como nacido para ADOPTAR la cuenta de otro (camino A: lo usa la bóveda). */
138
231
  prepareForAdoption () { return this._h('prepareForAdoption') }
139
232
  /** MI tarjeta de perfil: lo mínimo que un contacto necesita para cifrarme a todos mis
140
233
  * dispositivos (perfil, versión y llaves). Sin etiquetas ni permisos. */
141
234
  profileCard () { return this._h('profileCard') }
142
- /** Guarda la tarjeta de otra persona en su ficha de contacto (verificándola). */
235
+ /**
236
+ * Guarda la tarjeta de otra persona en su ficha de contacto (verificándola).
237
+ * @param {any} card
238
+ */
143
239
  adoptPeerCard (card) { return this._h('adoptPeerCard', { card }) }
144
240
  /** La clave de contenido del perfil, abierta con la llave de cifrado de este dispositivo. */
145
241
  contentKey () { return this._h('contentKey') }
146
- /** Cifra con la clave de contenido del perfil (la privada de cifrado no sale del vault). */
242
+ /**
243
+ * Cifra con la clave de contenido del perfil (la privada de cifrado no sale del vault).
244
+ * @param {string} plaintext
245
+ */
147
246
  sealContent (plaintext) { return this._h('sealContent', { plaintext }) }
148
- /** Abre un sobre de contenido con el llavero del perfil. */
247
+ /**
248
+ * Abre un sobre de contenido con el llavero del perfil.
249
+ * @param {any} envelope
250
+ */
149
251
  openContent (envelope) { return this._h('openContent', { envelope }) }
150
252
  /** Rota la clave de contenido (corta el acceso al contenido FUTURO de quien ya no está). */
151
253
  rotateContentKey () { return this._h('rotateContentKey') }
152
254
  // Emparejar ESTE dispositivo con el vault del usuario (Fase 1)
255
+ /**
256
+ * @param {any} qr
257
+ * @param {{ label?: string, join?: string, account?: string | null, requireCaps?: string[] | null }} [opts]
258
+ */
153
259
  enrollDevice (qr, { label = '', join = 'current', account = null, requireCaps = null } = {}) { return this._h('vaultPair', { qr, label, join, account, requireCaps }) }
154
260
  vaultStatus () { return this._h('vaultStatus') }
155
261
  unpairDevice () { return this._h('vaultUnpair') }
262
+ /** @param {any} payload */
156
263
  vaultSign (payload) { return this._h('vaultSign', { payload }) }
264
+ /** @param {string} method @param {any} args @param {{ wake?: boolean }} [opts] */
157
265
  vaultStore (method, args, { wake = true } = {}) { return this._h('vaultStore', { method, args, wake }) }
266
+ /** @param {any} opts */
158
267
  listVaultDevices (opts) { return this._h('listVaultDevices', opts || {}) }
159
268
  getVaultCert () { return this._h('getVaultCert') }
269
+ /**
270
+ * @param {string} op
271
+ * @param {any} args
272
+ */
160
273
  vaultApprovals (op, args) { return this._h('vaultApprovals', { op, ...(args || {}) }) }
161
- /** Los pedidos de TODAS las cuentas que aprueban, sin cambiar la activa. */
274
+ /**
275
+ * Los pedidos de TODAS las cuentas que aprueban, sin cambiar la activa.
276
+ * @param {any} args
277
+ */
162
278
  vaultApprovalsAll (args) { return this._h('vaultApprovalsAll', args || {}) }
279
+ /** @param {(payload: any) => void} handler */
163
280
  onVault (handler) { return this.on('vault', handler) }
164
281
  // Multi-perfil por dispositivo (crear/cambiar reinicializa con el nuevo perfil activo).
165
282
  listProfiles () { return this._h('listProfiles') }
166
283
  currentProfile () { return this._h('currentProfile') }
284
+ /** @param {string} name @param {{ forVault?: boolean }} [opts] */
167
285
  createProfile (name, { forVault = false } = {}) { return this._h('createProfile', { name, forVault }) }
286
+ /** @param {string} id */
168
287
  switchProfile (id) { return this._h('switchProfile', { id }) }
288
+ /**
289
+ * @param {string} id
290
+ * @param {string} name
291
+ */
169
292
  renameProfile (id, name) { return this._h('renameProfile', { id, name }) }
293
+ /** @param {string} id */
170
294
  deleteProfile (id) { return this._h('deleteProfile', { id }) }
295
+ /**
296
+ * @param {string} subject
297
+ * @param {any[]} endorsements
298
+ * @param {string} askerPubkey
299
+ */
171
300
  mergeEndorsements (subject, endorsements, askerPubkey) {
172
301
  return this._h('mergeEndorsements', { subject, endorsements, askerPubkey })
173
302
  }
303
+ /** @param {string} subject */
174
304
  getRatingsForSubject (subject) { return this._h('getRatingsForSubject', { subject }) }
305
+ /**
306
+ * @param {string} askerPubkey
307
+ * @param {string} subject
308
+ */
175
309
  recordQuery (askerPubkey, subject) { return this._h('recordQuery', { askerPubkey, subject }) }
310
+ /** @param {string} nickname */
176
311
  async setMyNickname (nickname) {
177
312
  const result = await this._h('setMyNickname', { nickname })
178
313
  return result
179
314
  }
315
+ /** @param {Record<string, any>} patch */
180
316
  async updateMe (patch) { return this._h('updateMe', { patch }) }
181
317
  getMe () { return this._h('getMe') }
182
318
  publicMe () { return this._h('publicMe') }
183
319
  /** Cómo fue el último empujón del perfil a la bóveda: `{ ok, at, error }`. */
184
320
  profilePushState () { return this._h('profilePushState') }
185
321
  getEncryptionPubkey () { return this._h('getEncryptionPubkey') }
322
+ /**
323
+ * @param {any[]} recipients
324
+ * @param {string} plaintext
325
+ */
186
326
  encrypt (recipients, plaintext) { return this._h('encrypt', { recipients, plaintext }) }
327
+ /**
328
+ * @param {string} senderEncryptionPubkey
329
+ * @param {string | null} myToken
330
+ * @param {any} envelope
331
+ */
187
332
  decrypt (senderEncryptionPubkey, myToken, envelope) {
188
333
  return this._h('decrypt', { senderEncryptionPubkey, myToken, envelope })
189
334
  }
190
335
  exportIdentity () { return this._h('exportIdentity') }
336
+ /** @param {any} blob */
191
337
  async importIdentity (blob) { return this._h('importIdentity', blob || {}) }
192
338
 
193
339
  // Sync (Google Drive) no disponible headless — los handlers responden acorde.
340
+ /** @param {string} clientId */
194
341
  syncConnect (clientId) { return this._h('syncConnect', { clientId }) }
195
342
  syncDisconnect () { return this._h('syncDisconnect') }
343
+ /** @param {string} passphrase */
196
344
  syncUnlock (passphrase) { return this._h('syncUnlock', { passphrase }) }
197
345
  syncLock () { return this._h('syncLock') }
198
346
  syncStatus () { return this._h('syncStatus') }
199
347
  syncNow () { return this._h('syncNow') }
200
348
 
349
+ /** @param {(payload: any) => void} handler */
201
350
  onSync (handler) { return this.on('sync', handler) }
351
+ /**
352
+ * @param {string} event
353
+ * @param {(payload: any) => void} handler
354
+ */
202
355
  on (event, handler) {
203
- if (!this._listeners.has(event)) this._listeners.set(event, new Set())
204
- this._listeners.get(event).add(handler)
356
+ let set = this._listeners.get(event)
357
+ if (!set) { set = new Set(); this._listeners.set(event, set) }
358
+ set.add(handler)
205
359
  return () => this._listeners.get(event)?.delete(handler)
206
360
  }
361
+ /**
362
+ * @param {string} event
363
+ * @param {any} payload
364
+ */
207
365
  _emit (event, payload) {
208
366
  const set = this._listeners.get(event)
209
367
  if (!set) return
@@ -0,0 +1,60 @@
1
+ // Globales del navegador que usa la identidad y que TypeScript no trae: solo para el chequeo
2
+ // de tipos (`npm run type-check`), no se publican como tipos del paquete.
3
+
4
+ /** Google Identity Services (lo justo de `oauth2` que usa `sync.js`). */
5
+ interface GoogleTokenResponse {
6
+ access_token?: string
7
+ expires_in?: number | string
8
+ error?: string
9
+ }
10
+ interface GoogleTokenClient {
11
+ callback: (resp: GoogleTokenResponse) => void
12
+ requestAccessToken (opts?: { prompt?: string }): void
13
+ /** Lo apunta `sync.js` para saber para qué cliente se creó. */
14
+ _clientId?: string
15
+ }
16
+
17
+ interface Window {
18
+ google?: {
19
+ accounts?: {
20
+ oauth2?: {
21
+ initTokenClient (cfg: { client_id: string, scope: string, prompt: string, callback: (resp: GoogleTokenResponse) => void }): GoogleTokenClient
22
+ }
23
+ }
24
+ }
25
+ }
26
+
27
+ interface Window {
28
+ /**
29
+ * El puente con el chip del teléfono, dentro de la app nativa (`addWebMessageListener`).
30
+ * `storage: true`: la app guarda también la identidad (la de iOS).
31
+ */
32
+ DotrinoIdentityKeys?: { onmessage: ((ev: { data: string }) => void) | null, postMessage (data: string): void, storage?: boolean }
33
+ }
34
+
35
+ // Módulos que el iframe resuelve con su import map (`@dotrino/vault`, vendorizado en
36
+ // `vault/vendor/`) y que este paquete no instala: lo justo de lo que se usa.
37
+ declare module '@dotrino/vault/browser' {
38
+ /** La bóveda entera sobre IndexedDB; devuelve su mostrador (`listPending`, `approve`…). */
39
+ export function startBrowserVault (opts: Record<string, any>): Promise<any>
40
+ }
41
+ declare module '@dotrino/vault/password-logins' {
42
+ export function sealDeviceKeys (exportKey: any, keys: { sign: JsonWebKey, enc: JsonWebKey }): Promise<any>
43
+ export function openDeviceKeys (exportKey: any, blob: any): Promise<{ sign: JsonWebKey, enc: JsonWebKey }>
44
+ export function loginAddress (user: string, fingerprint: string): string
45
+ export function accountFingerprint (identity: { profileActa (): Promise<any> }): Promise<string>
46
+ export function vaultChannel (code: string): string
47
+ }
48
+ declare module '@dotrino/vault/backup' {
49
+ export function sealBackup (payload: any, password: string): Promise<any>
50
+ export function openBackup (file: any, password: string): Promise<any>
51
+ }
52
+ // `@dotrino/opaque` se instala, pero no publica tipos.
53
+ declare module '@dotrino/opaque' {
54
+ export const client: {
55
+ registrationStart (args: { password: string }): { request: any, state: any }
56
+ registrationFinish (args: { state: any, response: any, password: string }): { upload: any, exportKey: any }
57
+ loginStart (args: { password: string }): { request: any, state: any }
58
+ loginFinish (args: { state: any, response: any, password: string }): { finalization: any, exportKey: any }
59
+ }
60
+ }
package/vault/keyid.js CHANGED
@@ -11,15 +11,21 @@
11
11
  * `pubkeyId` desde aquí para que haya UNA sola implementación.
12
12
  */
13
13
 
14
+ /** @param {string} s */
14
15
  const enc = (s) => new TextEncoder().encode(s)
15
16
 
16
17
  /** Serialización canónica de los campos que identifican la llave (mismo orden siempre). */
18
+ /** @param {JsonWebKey} jwk @returns {string} */
17
19
  function canonicalJwk (jwk) {
18
20
  return JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y })
19
21
  .replace(/^{/, '{').replace(/}$/, '}')
20
22
  }
21
23
 
22
- /** id corto y estable de un pubkey (sha-256 hex de los campos canónicos del JWK). */
24
+ /**
25
+ * id corto y estable de un pubkey (sha-256 hex de los campos canónicos del JWK).
26
+ * @param {string | JsonWebKey} publicJwkStr
27
+ * @returns {Promise<string>}
28
+ */
23
29
  export async function pubkeyId (publicJwkStr) {
24
30
  const jwk = typeof publicJwkStr === 'string' ? JSON.parse(publicJwkStr) : publicJwkStr
25
31
  const h = await crypto.subtle.digest('SHA-256', enc(canonicalJwk(jwk)))
@@ -29,6 +35,9 @@ export async function pubkeyId (publicJwkStr) {
29
35
  /**
30
36
  * La huella que SÍ se le enseña a una persona: `AB12-CD34`. Corta, comparable de un vistazo
31
37
  * y la misma en todo el ecosistema (emparejamiento, acta, lista de dispositivos).
38
+ *
39
+ * @param {string | JsonWebKey | null | undefined} publicJwkStr
40
+ * @returns {Promise<string>}
32
41
  */
33
42
  export async function keyLabel (publicJwkStr) {
34
43
  if (!publicJwkStr) return ''
package/vault/machine.js CHANGED
@@ -21,6 +21,7 @@
21
21
 
22
22
  export const MACHINE_KINDS = ['node', 'browser', 'extension', 'ios', 'android']
23
23
 
24
+ /** @param {unknown} s @param {number} n @returns {string} */
24
25
  const clip = (s, n) => (typeof s === 'string' ? s.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, n) : '')
25
26
 
26
27
  /**
@@ -38,13 +39,18 @@ export function cleanMachine (raw) {
38
39
  return { kind, os, name }
39
40
  }
40
41
 
41
- /** Una línea para enseñarlo: `node · Linux 7.0.0 · mi-pc`. Vacía si no hay nada. */
42
+ /**
43
+ * Una línea para enseñarlo: `node · Linux 7.0.0 · mi-pc`. Vacía si no hay nada.
44
+ * @param {any} m
45
+ * @returns {string}
46
+ */
42
47
  export function machineLine (m) {
43
48
  const c = cleanMachine(m)
44
49
  return c ? [c.kind, c.os, c.name].filter(Boolean).join(' · ') : ''
45
50
  }
46
51
 
47
52
  /** ¿Dicen lo mismo? Para no reescribir un archivo cada vez que un aparato repite lo de siempre. */
53
+ /** @param {any} a @param {any} b @returns {boolean} */
48
54
  export const sameMachine = (a, b) => machineLine(a) === machineLine(b)
49
55
 
50
56
  /** @type {Array<[RegExp, (v: string) => string]>} */