@dotrino/identity 0.139.0 → 0.140.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -124,6 +124,21 @@ Mismo registro de `peers` que arriba, pero filtrado por flag `isContact: true`.
124
124
  - `id.encrypt(recipients, plaintext)` → `{v:1, iv, ct, wrap}` envelope. `recipients` = `[{token, encryptionPubkey}]`. AES-256-GCM con clave efímera por mensaje, envuelta para cada destinatario vía ECDH(P-256). El campo `token` puede ser cualquier identificador estable (en messenger se usa la pubkey del destinatario para sobrevivir cambios de token del proxy).
125
125
  - `id.decrypt(senderEncryptionPubkey, myToken, envelope)` → `{ plaintext }`. Forward-secrecy por mensaje (clave simétrica nueva cada vez).
126
126
 
127
+ **El mismo sobre sin el iframe: `@dotrino/identity/e2e` (0.140.1+; la 0.140.0 sellaba sobres vacíos dentro de un service worker).** Para un aparato headless
128
+ que tiene su propia llave de cifrado (un agente de `@dotrino/remote-agent`). Son las funciones
129
+ que usa el núcleo por dentro, así que el sobre es byte a byte el mismo y prueba igual quién lo
130
+ selló:
131
+
132
+ ```js
133
+ import { keyIdentity, encryptFor, decryptFrom } from '@dotrino/identity/e2e'
134
+ import { identitySealing } from '@dotrino/proxy-client'
135
+
136
+ // encPub (JWK en texto) + privateKey (CryptoKey ECDH, con deriveKey o solo deriveBits)
137
+ client.updateConfig({ myEncPub: encPub, sealing: identitySealing(keyIdentity({ encPub, privateKey }), { app: 'messenger' }) })
138
+ ```
139
+
140
+ `keyIdentity` no expande destinatarios por su tarjeta: cifra a las llaves que se le dan.
141
+
127
142
  ### Firma genérica (0.7.0+)
128
143
 
129
144
  - `id.signData(data)` → `{ signature, publickey }` con encoding canonical-JSON. Lo usa el messenger para construir sobres `identify` que el proxy verifica con su `verifySignatureWithJWK`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/identity",
3
- "version": "0.139.0",
3
+ "version": "0.140.1",
4
4
  "description": "Identidad y rating de usuarios compartidos entre apps de Dotrino (vault iframe + postMessage)",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -38,6 +38,10 @@
38
38
  "types": "./types/acta.d.ts",
39
39
  "import": "./vault/acta.js"
40
40
  },
41
+ "./e2e": {
42
+ "types": "./types/e2e.d.ts",
43
+ "import": "./vault/e2e.js"
44
+ },
41
45
  "./content": {
42
46
  "types": "./types/content.d.ts",
43
47
  "import": "./vault/content.js"
package/types/core.d.ts CHANGED
@@ -1,9 +1,5 @@
1
1
  /** @param {any} v @returns {string} */
2
2
  export function canonicalStringify(v: any): string;
3
- /** @param {ArrayBuffer | ArrayLike<number>} buf @returns {string} */
4
- export function bufToBase64(buf: ArrayBuffer | ArrayLike<number>): string;
5
- /** @param {string} b64 @returns {ArrayBuffer} */
6
- export function base64ToBuf(b64: string): ArrayBuffer;
7
3
  /**
8
4
  * QUÉ CLASE ES CADA DATO DEL PERFIL: `public` o `private`
9
5
  * (`dotrino-vault/docs/datos-del-perfil.md` §2).
@@ -1011,15 +1007,7 @@ export function createIdentityCore({ kv: hostKv, peers, makeSync, keyStore: host
1011
1007
  * perfil (§tarjeta). Le escribes a la persona, no al aparato desde el que te habló.
1012
1008
  * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
1013
1009
  */
1014
- encrypt({ recipients, plaintext }: HandlerParams): Promise<{
1015
- v: number;
1016
- iv: string;
1017
- ct: string;
1018
- wrap: Record<string, {
1019
- iv: string;
1020
- ct: string;
1021
- }>;
1022
- }>;
1010
+ encrypt({ recipients, plaintext }: HandlerParams): Promise<import("./e2e.js").E2eEnvelope>;
1023
1011
  /**
1024
1012
  * Descifra. Busca MI envoltura por el id de mi llave de cifrado (v2); `myToken` ya no
1025
1013
  * hace falta y se acepta solo por compatibilidad de llamada.
@@ -1362,3 +1350,6 @@ export type Acta = import("./acta.js").Acta;
1362
1350
  export type HandlerParams = Record<string, any>;
1363
1351
  import * as Acta from './acta.js';
1364
1352
  import * as Content from './content.js';
1353
+ import { bufToBase64 } from './e2e.js';
1354
+ import { base64ToBuf } from './e2e.js';
1355
+ export { bufToBase64, base64ToBuf };
package/types/e2e.d.ts ADDED
@@ -0,0 +1,93 @@
1
+ /** @param {ArrayBuffer | ArrayLike<number>} buf @returns {string} */
2
+ export function bufToBase64(buf: ArrayBuffer | ArrayLike<number>): string;
3
+ /** @param {string} b64 @returns {ArrayBuffer} */
4
+ export function base64ToBuf(b64: string): ArrayBuffer;
5
+ /** @param {string | JsonWebKey} jwkStr @returns {Promise<CryptoKey>} */
6
+ export function importPeerEncPubkey(jwkStr: string | JsonWebKey): Promise<CryptoKey>;
7
+ /**
8
+ * La clave AES compartida entre mi privada y la pública del otro.
9
+ * @param {any} myPriv CryptoKey ECDH, o el asa de una llave del chip (`external`)
10
+ * @param {CryptoKey} peerPub
11
+ * @returns {Promise<CryptoKey>}
12
+ */
13
+ export function deriveSharedAesKey(myPriv: any, peerPub: CryptoKey): Promise<CryptoKey>;
14
+ /**
15
+ * Id estable y corto de una llave de cifrado: con esto se indexan las envolturas. Es el
16
+ * `pubkeyId` de `keyid.js` (SHA-256 del JWK canónico) cortado a 16.
17
+ *
18
+ * IMPORT ESTÁTICO, y no es estética: un service worker (la extensión de contraseñas) no
19
+ * admite `import()` dinámico. Con `await import('./capabilities.js')` aquí, cada envoltura
20
+ * fallaba dentro del `catch` de `encryptFor` y el sobre salía SIN destinatarios: la bóveda
21
+ * lo recibía, «no es para mí», y la extensión veía silencio (0.140.0, arreglado en 0.140.1).
22
+ * @param {string} encPub
23
+ * @returns {Promise<string>}
24
+ */
25
+ export function encKeyId(encPub: string): Promise<string>;
26
+ /**
27
+ * @typedef {{ v: 2, iv: string, ct: string, wrap: Record<string, { iv: string, ct: string }> }} E2eEnvelope
28
+ */
29
+ /**
30
+ * Cifra `plaintext` para cada llave de `encPubs`, con MI privada de cifrado.
31
+ *
32
+ * Un destinatario cuya llave no se puede importar se OMITE y no aparece en `wrap`: quien llama
33
+ * mira si quedó alguien (`identitySealing` lo hace), porque un sobre sin envolturas está cifrado
34
+ * de verdad y no lo abre nadie.
35
+ *
36
+ * @param {{ myEncPrivateKey: any, encPubs: Iterable<string>, plaintext: string }} args
37
+ * @returns {Promise<E2eEnvelope>}
38
+ */
39
+ export function encryptFor({ myEncPrivateKey, encPubs, plaintext }: {
40
+ myEncPrivateKey: any;
41
+ encPubs: Iterable<string>;
42
+ plaintext: string;
43
+ }): Promise<E2eEnvelope>;
44
+ /**
45
+ * Abre un sobre que me mandó `senderEncPub`. Busca MI envoltura por el id de mi llave (v2);
46
+ * `myToken` solo por los sobres v1, que se indexaban por la conexión.
47
+ *
48
+ * Lanza si no soy destinatario o si no lo selló esa llave (AES-GCM no autentica con otra).
49
+ *
50
+ * @param {{ myEncPrivateKey: any, myEncPub: string, senderEncPub: string, envelope: any, myToken?: string | null }} args
51
+ * @returns {Promise<string>}
52
+ */
53
+ export function decryptFrom({ myEncPrivateKey, myEncPub, senderEncPub, envelope, myToken }: {
54
+ myEncPrivateKey: any;
55
+ myEncPub: string;
56
+ senderEncPub: string;
57
+ envelope: any;
58
+ myToken?: string | null;
59
+ }): Promise<string>;
60
+ /**
61
+ * UNA IDENTIDAD DE CIFRADO desde un par de llaves suelto, con el dialecto del núcleo
62
+ * (`encryptionPubkey()`, `encrypt(destinatarios, texto)`, `decrypt(remitente, sobre)` →
63
+ * cadena). Es lo que `identitySealing` de `@dotrino/proxy-client` acepta, así que un aparato
64
+ * headless sella con el mismo sobre que una app del navegador:
65
+ *
66
+ * identitySealing(keyIdentity({ encPub, privateKey }), { app: 'messenger' })
67
+ *
68
+ * No expande destinatarios por su tarjeta de perfil (no tiene libreta): cifra a las llaves que
69
+ * se le dan.
70
+ *
71
+ * @param {{ encPub: string, privateKey: any }} keys
72
+ */
73
+ export function keyIdentity({ encPub, privateKey }: {
74
+ encPub: string;
75
+ privateKey: any;
76
+ }): {
77
+ encryptionPubkey: () => string;
78
+ /** @param {Array<{ encryptionPubkey?: string }>} recipients @param {string} plaintext */
79
+ encrypt: (recipients: Array<{
80
+ encryptionPubkey?: string;
81
+ }>, plaintext: string) => Promise<E2eEnvelope>;
82
+ /** @param {string} senderEncPub @param {any} envelope */
83
+ decrypt: (senderEncPub: string, envelope: any) => Promise<string>;
84
+ };
85
+ export type E2eEnvelope = {
86
+ v: 2;
87
+ iv: string;
88
+ ct: string;
89
+ wrap: Record<string, {
90
+ iv: string;
91
+ ct: string;
92
+ }>;
93
+ };
package/vault/core.js CHANGED
@@ -24,6 +24,7 @@ import * as Content from './content.js'
24
24
  import { syncPeers, stampOf } from './peerSync.js'
25
25
  import { assertionBody, cleanScopes, claimsAllowed, ASSERTION_DEFAULT_TTL_MS, ASSERTION_MAX_TTL_MS } from './assertion.js'
26
26
  import { pubkeyId as pubkeyIdOf, signWithDevice, keyLabel } from './capabilities.js'
27
+ import { bufToBase64, base64ToBuf, encryptFor, decryptFrom } from './e2e.js'
27
28
  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
29
 
29
30
  /**
@@ -149,45 +150,8 @@ export function canonicalStringify (v) {
149
150
  return '{' + ks.map(k => JSON.stringify(k) + ':' + canonicalStringify(v[k])).join(',') + '}'
150
151
  }
151
152
 
152
- /** @param {ArrayBuffer | ArrayLike<number>} buf @returns {string} */
153
- export function bufToBase64 (buf) {
154
- const bytes = new Uint8Array(buf)
155
- let s = ''
156
- for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i])
157
- return btoa(s)
158
- }
159
-
160
- /** @param {string} b64 @returns {ArrayBuffer} */
161
- export function base64ToBuf (b64) {
162
- const s = atob(b64)
163
- const bytes = new Uint8Array(s.length)
164
- for (let i = 0; i < s.length; i++) bytes[i] = s.charCodeAt(i)
165
- return bytes.buffer
166
- }
167
-
168
- /** @param {string | JsonWebKey} jwkStr @returns {Promise<CryptoKey>} */
169
- async function importPeerEncPubkey (jwkStr) {
170
- const jwk = typeof jwkStr === 'string' ? JSON.parse(jwkStr) : jwkStr
171
- return crypto.subtle.importKey('jwk', jwk, { name: 'ECDH', namedCurve: 'P-256' }, true, [])
172
- }
173
-
174
- /** @param {any} myPriv CryptoKey ECDH, o el asa de una llave del chip @param {CryptoKey} peerPub @returns {Promise<CryptoKey>} */
175
- async function deriveSharedAesKey (myPriv, peerPub) {
176
- if (myPriv?.external) {
177
- // Llave EXTERNA: el chip da los 32 bytes del secreto ECDH, que es exactamente lo que
178
- // `deriveKey` ECDH→AES-256 usa por dentro. Mismo AES, sin que la privada salga.
179
- const { kty, crv, x, y } = await crypto.subtle.exportKey('jwk', peerPub)
180
- const bits = await myPriv.deriveBits(JSON.stringify({ kty, crv, x, y }))
181
- return crypto.subtle.importKey('raw', bits, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
182
- }
183
- return crypto.subtle.deriveKey(
184
- { name: 'ECDH', public: peerPub },
185
- myPriv,
186
- { name: 'AES-GCM', length: 256 },
187
- false,
188
- ['encrypt', 'decrypt']
189
- )
190
- }
153
+ // El sobre de persona a persona y sus piezas viven en e2e.js (puras, sin el par de este núcleo).
154
+ export { bufToBase64, base64ToBuf }
191
155
 
192
156
  /** @param {any} privateKey CryptoKey ECDSA, o el asa de una llave del chip @param {Uint8Array<ArrayBuffer>} bytes @returns {Promise<string>} */
193
157
  async function signBytes (privateKey, bytes) {
@@ -947,10 +911,6 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
947
911
  return r
948
912
  }
949
913
 
950
- /** Id estable y corto de una llave de cifrado: con esto se indexan las envolturas. */
951
- /** @param {string} encPub */
952
- const encKeyId = async (encPub) => (await pubkeyIdOf(encPub)).slice(0, 16)
953
-
954
914
  /** @returns {VaultLink | null} */
955
915
  const loadVaultCert = () => { try { return JSON.parse(kv.getItem(VAULT_CERT_STORAGE) || 'null') } catch (_) { return null } }
956
916
 
@@ -4045,11 +4005,6 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
4045
4005
  async encrypt ({ recipients, plaintext }) {
4046
4006
  if (!Array.isArray(recipients) || recipients.length === 0) throw new Error('recipients required')
4047
4007
  if (typeof plaintext !== 'string') throw new Error('plaintext required')
4048
- const k = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt'])
4049
- const kRaw = await crypto.subtle.exportKey('raw', k)
4050
- const iv = crypto.getRandomValues(new Uint8Array(12))
4051
- const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, k, new TextEncoder().encode(plaintext))
4052
-
4053
4008
  // Expandir cada destinatario a TODOS los dispositivos de su perfil que conozcamos.
4054
4009
  const encPubs = new Set()
4055
4010
  const peers = loadPeers()
@@ -4059,19 +4014,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
4059
4014
  const card = (r.publickey && peers[r.publickey]?.card) || null
4060
4015
  for (const kk of (card?.keys || [])) if (kk.encPub) encPubs.add(kk.encPub)
4061
4016
  }
4062
-
4063
- /** @type {Record<string, { iv: string, ct: string }>} */
4064
- const wrap = {}
4065
- for (const encPub of encPubs) {
4066
- try {
4067
- const peerPub = await importPeerEncPubkey(encPub)
4068
- const sharedKey = await deriveSharedAesKey(encKeypair.privateKey, peerPub)
4069
- const wrapIv = crypto.getRandomValues(new Uint8Array(12))
4070
- const wrappedCt = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: wrapIv }, sharedKey, kRaw)
4071
- wrap[await encKeyId(encPub)] = { iv: bufToBase64(wrapIv), ct: bufToBase64(new Uint8Array(wrappedCt)) }
4072
- } catch (e) { /* destinatario omitido */ }
4073
- }
4074
- return { v: 2, iv: bufToBase64(iv), ct: bufToBase64(new Uint8Array(ct)), wrap }
4017
+ return encryptFor({ myEncPrivateKey: encKeypair.privateKey, encPubs, plaintext })
4075
4018
  },
4076
4019
 
4077
4020
  /**
@@ -4080,17 +4023,11 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
4080
4023
  * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
4081
4024
  */
4082
4025
  async decrypt ({ senderEncryptionPubkey, myToken, envelope }) {
4083
- if (!senderEncryptionPubkey) throw new Error('senderEncryptionPubkey required')
4084
- if (!envelope || (envelope.v !== 1 && envelope.v !== 2)) throw new Error('Unsupported envelope')
4085
- const myId = await encKeyId(encPublickeyJwkStr)
4086
- const myEntry = envelope.wrap && (envelope.wrap[myId] || (myToken ? envelope.wrap[myToken] : null))
4087
- if (!myEntry) throw new Error('this device is not among the message recipients')
4088
- const senderPub = await importPeerEncPubkey(senderEncryptionPubkey)
4089
- const sharedKey = await deriveSharedAesKey(encKeypair.privateKey, senderPub)
4090
- const kRaw = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: base64ToBuf(myEntry.iv) }, sharedKey, base64ToBuf(myEntry.ct))
4091
- const k = await crypto.subtle.importKey('raw', kRaw, { name: 'AES-GCM', length: 256 }, false, ['decrypt'])
4092
- const ptBytes = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: base64ToBuf(envelope.iv) }, k, base64ToBuf(envelope.ct))
4093
- return { plaintext: new TextDecoder().decode(ptBytes) }
4026
+ const plaintext = await decryptFrom({
4027
+ myEncPrivateKey: encKeypair.privateKey, myEncPub: encPublickeyJwkStr,
4028
+ senderEncPub: senderEncryptionPubkey, envelope, myToken
4029
+ })
4030
+ return { plaintext }
4094
4031
  },
4095
4032
 
4096
4033
  async exportIdentity () {
package/vault/e2e.js ADDED
@@ -0,0 +1,179 @@
1
+ /**
2
+ * e2e.js — EL SOBRE DE PERSONA A PERSONA (v2), como funciones puras.
3
+ *
4
+ * Es el sobre que arma `identity.encrypt` y abre `identity.decrypt`: una clave AES nueva por
5
+ * mensaje, envuelta para cada destinatario con ECDH entre la llave de cifrado de QUIEN MANDA y
6
+ * la del destinatario. Por eso prueba de quién viene: solo lo pudo armar quien tiene la privada
7
+ * de esa llave (el puente `identitySealing` de `@dotrino/proxy-client` la entrega como
8
+ * `senderEncPub`).
9
+ *
10
+ * Vivía solo dentro del núcleo, atado a SU par de llaves. Sale aquí para que un aparato
11
+ * headless que tiene su propia llave de cifrado (un agente de `@dotrino/remote-agent`) arme y
12
+ * abra el MISMO sobre que una app del navegador, sin una segunda copia de la cripto. El núcleo
13
+ * usa estas mismas funciones.
14
+ *
15
+ * No hay cripto nueva: ECDH P-256 + AES-GCM, como siempre.
16
+ */
17
+
18
+ import { pubkeyId } from './keyid.js'
19
+
20
+ /** @param {ArrayBuffer | ArrayLike<number>} buf @returns {string} */
21
+ export function bufToBase64 (buf) {
22
+ const bytes = new Uint8Array(buf)
23
+ let s = ''
24
+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i])
25
+ return btoa(s)
26
+ }
27
+
28
+ /** @param {string} b64 @returns {ArrayBuffer} */
29
+ export function base64ToBuf (b64) {
30
+ const s = atob(b64)
31
+ const bytes = new Uint8Array(s.length)
32
+ for (let i = 0; i < s.length; i++) bytes[i] = s.charCodeAt(i)
33
+ return bytes.buffer
34
+ }
35
+
36
+ /** @param {string | JsonWebKey} jwkStr @returns {Promise<CryptoKey>} */
37
+ export async function importPeerEncPubkey (jwkStr) {
38
+ const jwk = typeof jwkStr === 'string' ? JSON.parse(jwkStr) : jwkStr
39
+ return crypto.subtle.importKey('jwk', jwk, { name: 'ECDH', namedCurve: 'P-256' }, true, [])
40
+ }
41
+
42
+ /**
43
+ * La clave AES compartida entre mi privada y la pública del otro.
44
+ * @param {any} myPriv CryptoKey ECDH, o el asa de una llave del chip (`external`)
45
+ * @param {CryptoKey} peerPub
46
+ * @returns {Promise<CryptoKey>}
47
+ */
48
+ export async function deriveSharedAesKey (myPriv, peerPub) {
49
+ if (myPriv?.external) {
50
+ // Llave EXTERNA: el chip da los 32 bytes del secreto ECDH, que es exactamente lo que
51
+ // `deriveKey` ECDH→AES-256 usa por dentro. Mismo AES, sin que la privada salga.
52
+ const { kty, crv, x, y } = await crypto.subtle.exportKey('jwk', peerPub)
53
+ const bits = await myPriv.deriveBits(JSON.stringify({ kty, crv, x, y }))
54
+ return crypto.subtle.importKey('raw', bits, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
55
+ }
56
+ if (!myPriv?.usages?.includes('deriveKey')) {
57
+ // Una llave que solo admite `deriveBits` (la de un agente, `makeEncKeypair`): los mismos
58
+ // 32 bytes del secreto ECDH, y el mismo AES que daría `deriveKey`.
59
+ const bits = await crypto.subtle.deriveBits({ name: 'ECDH', public: peerPub }, myPriv, 256)
60
+ return crypto.subtle.importKey('raw', bits, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
61
+ }
62
+ return crypto.subtle.deriveKey(
63
+ { name: 'ECDH', public: peerPub },
64
+ myPriv,
65
+ { name: 'AES-GCM', length: 256 },
66
+ false,
67
+ ['encrypt', 'decrypt']
68
+ )
69
+ }
70
+
71
+ /**
72
+ * Id estable y corto de una llave de cifrado: con esto se indexan las envolturas. Es el
73
+ * `pubkeyId` de `keyid.js` (SHA-256 del JWK canónico) cortado a 16.
74
+ *
75
+ * IMPORT ESTÁTICO, y no es estética: un service worker (la extensión de contraseñas) no
76
+ * admite `import()` dinámico. Con `await import('./capabilities.js')` aquí, cada envoltura
77
+ * fallaba dentro del `catch` de `encryptFor` y el sobre salía SIN destinatarios: la bóveda
78
+ * lo recibía, «no es para mí», y la extensión veía silencio (0.140.0, arreglado en 0.140.1).
79
+ * @param {string} encPub
80
+ * @returns {Promise<string>}
81
+ */
82
+ export async function encKeyId (encPub) {
83
+ return (await pubkeyId(encPub)).slice(0, 16)
84
+ }
85
+
86
+ /**
87
+ * @typedef {{ v: 2, iv: string, ct: string, wrap: Record<string, { iv: string, ct: string }> }} E2eEnvelope
88
+ */
89
+
90
+ /**
91
+ * Cifra `plaintext` para cada llave de `encPubs`, con MI privada de cifrado.
92
+ *
93
+ * Un destinatario cuya llave no se puede importar se OMITE y no aparece en `wrap`: quien llama
94
+ * mira si quedó alguien (`identitySealing` lo hace), porque un sobre sin envolturas está cifrado
95
+ * de verdad y no lo abre nadie.
96
+ *
97
+ * @param {{ myEncPrivateKey: any, encPubs: Iterable<string>, plaintext: string }} args
98
+ * @returns {Promise<E2eEnvelope>}
99
+ */
100
+ export async function encryptFor ({ myEncPrivateKey, encPubs, plaintext }) {
101
+ if (!myEncPrivateKey) throw new Error('encryptFor: myEncPrivateKey required')
102
+ if (typeof plaintext !== 'string') throw new Error('plaintext required')
103
+ const k = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt'])
104
+ const kRaw = await crypto.subtle.exportKey('raw', k)
105
+ const iv = crypto.getRandomValues(new Uint8Array(12))
106
+ const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, k, new TextEncoder().encode(plaintext))
107
+ /** @type {Record<string, { iv: string, ct: string }>} */
108
+ const wrap = {}
109
+ /** @type {any} */
110
+ let lastError = null
111
+ for (const encPub of new Set(encPubs)) {
112
+ try {
113
+ const peerPub = await importPeerEncPubkey(encPub)
114
+ const sharedKey = await deriveSharedAesKey(myEncPrivateKey, peerPub)
115
+ const wrapIv = crypto.getRandomValues(new Uint8Array(12))
116
+ const wrappedCt = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: wrapIv }, sharedKey, kRaw)
117
+ wrap[await encKeyId(encPub)] = { iv: bufToBase64(wrapIv), ct: bufToBase64(new Uint8Array(wrappedCt)) }
118
+ } catch (e) { lastError = e /* destinatario omitido; si no queda NINGUNO, se para abajo */ }
119
+ }
120
+ // UN SOBRE SIN ENVOLTURAS NO LO ABRE NADIE, y salir así es fallar en silencio: el otro lado
121
+ // lo descarta («no es para mí») y quien pidió solo ve que nadie contesta. Se para aquí, con
122
+ // la causa.
123
+ if (Object.keys(wrap).length === 0) {
124
+ throw Object.assign(new Error('encryptFor: no recipient could be sealed' + (lastError ? ` (${lastError.message})` : '')), { code: 'no-recipients' })
125
+ }
126
+ return { v: 2, iv: bufToBase64(iv), ct: bufToBase64(new Uint8Array(ct)), wrap }
127
+ }
128
+
129
+ /**
130
+ * Abre un sobre que me mandó `senderEncPub`. Busca MI envoltura por el id de mi llave (v2);
131
+ * `myToken` solo por los sobres v1, que se indexaban por la conexión.
132
+ *
133
+ * Lanza si no soy destinatario o si no lo selló esa llave (AES-GCM no autentica con otra).
134
+ *
135
+ * @param {{ myEncPrivateKey: any, myEncPub: string, senderEncPub: string, envelope: any, myToken?: string | null }} args
136
+ * @returns {Promise<string>}
137
+ */
138
+ export async function decryptFrom ({ myEncPrivateKey, myEncPub, senderEncPub, envelope, myToken = null }) {
139
+ if (!senderEncPub) throw new Error('senderEncryptionPubkey required')
140
+ if (!envelope || (envelope.v !== 1 && envelope.v !== 2)) throw new Error('Unsupported envelope')
141
+ const myId = await encKeyId(myEncPub)
142
+ const myEntry = envelope.wrap && (envelope.wrap[myId] || (myToken ? envelope.wrap[myToken] : null))
143
+ if (!myEntry) throw new Error('this device is not among the message recipients')
144
+ const senderPub = await importPeerEncPubkey(senderEncPub)
145
+ const sharedKey = await deriveSharedAesKey(myEncPrivateKey, senderPub)
146
+ const kRaw = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: new Uint8Array(base64ToBuf(myEntry.iv)) }, sharedKey, base64ToBuf(myEntry.ct))
147
+ const k = await crypto.subtle.importKey('raw', kRaw, { name: 'AES-GCM', length: 256 }, false, ['decrypt'])
148
+ const ptBytes = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: new Uint8Array(base64ToBuf(envelope.iv)) }, k, base64ToBuf(envelope.ct))
149
+ return new TextDecoder().decode(ptBytes)
150
+ }
151
+
152
+ /**
153
+ * UNA IDENTIDAD DE CIFRADO desde un par de llaves suelto, con el dialecto del núcleo
154
+ * (`encryptionPubkey()`, `encrypt(destinatarios, texto)`, `decrypt(remitente, sobre)` →
155
+ * cadena). Es lo que `identitySealing` de `@dotrino/proxy-client` acepta, así que un aparato
156
+ * headless sella con el mismo sobre que una app del navegador:
157
+ *
158
+ * identitySealing(keyIdentity({ encPub, privateKey }), { app: 'messenger' })
159
+ *
160
+ * No expande destinatarios por su tarjeta de perfil (no tiene libreta): cifra a las llaves que
161
+ * se le dan.
162
+ *
163
+ * @param {{ encPub: string, privateKey: any }} keys
164
+ */
165
+ export function keyIdentity ({ encPub, privateKey }) {
166
+ if (typeof encPub !== 'string' || !encPub) throw new Error('keyIdentity: encPub required')
167
+ if (!privateKey) throw new Error('keyIdentity: privateKey required')
168
+ return {
169
+ encryptionPubkey: () => encPub,
170
+ /** @param {Array<{ encryptionPubkey?: string }>} recipients @param {string} plaintext */
171
+ encrypt: (recipients, plaintext) => encryptFor({
172
+ myEncPrivateKey: privateKey,
173
+ encPubs: (recipients || []).flatMap((r) => (typeof r?.encryptionPubkey === 'string' && r.encryptionPubkey ? [r.encryptionPubkey] : [])),
174
+ plaintext
175
+ }),
176
+ /** @param {string} senderEncPub @param {any} envelope */
177
+ decrypt: (senderEncPub, envelope) => decryptFrom({ myEncPrivateKey: privateKey, myEncPub: encPub, senderEncPub, envelope })
178
+ }
179
+ }