@dotrino/identity 0.139.0 → 0.140.0
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 +15 -0
- package/package.json +5 -1
- package/types/core.d.ts +4 -13
- package/types/e2e.d.ts +104 -0
- package/vault/core.js +9 -72
- package/vault/e2e.js +165 -0
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.0+).** 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.
|
|
3
|
+
"version": "0.140.0",
|
|
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,104 @@
|
|
|
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
|
+
/** @param {ArrayBuffer | ArrayLike<number>} buf @returns {string} */
|
|
18
|
+
export function bufToBase64(buf: ArrayBuffer | ArrayLike<number>): string;
|
|
19
|
+
/** @param {string} b64 @returns {ArrayBuffer} */
|
|
20
|
+
export function base64ToBuf(b64: string): ArrayBuffer;
|
|
21
|
+
/** @param {string | JsonWebKey} jwkStr @returns {Promise<CryptoKey>} */
|
|
22
|
+
export function importPeerEncPubkey(jwkStr: string | JsonWebKey): Promise<CryptoKey>;
|
|
23
|
+
/**
|
|
24
|
+
* La clave AES compartida entre mi privada y la pública del otro.
|
|
25
|
+
* @param {any} myPriv CryptoKey ECDH, o el asa de una llave del chip (`external`)
|
|
26
|
+
* @param {CryptoKey} peerPub
|
|
27
|
+
* @returns {Promise<CryptoKey>}
|
|
28
|
+
*/
|
|
29
|
+
export function deriveSharedAesKey(myPriv: any, peerPub: CryptoKey): Promise<CryptoKey>;
|
|
30
|
+
/**
|
|
31
|
+
* Id estable y corto de una llave de cifrado: con esto se indexan las envolturas. Es el
|
|
32
|
+
* `pubkeyId` de `capabilities.js` (SHA-256 del JWK canónico) cortado a 16.
|
|
33
|
+
* @param {string} encPub
|
|
34
|
+
* @returns {Promise<string>}
|
|
35
|
+
*/
|
|
36
|
+
export function encKeyId(encPub: string): Promise<string>;
|
|
37
|
+
/**
|
|
38
|
+
* @typedef {{ v: 2, iv: string, ct: string, wrap: Record<string, { iv: string, ct: string }> }} E2eEnvelope
|
|
39
|
+
*/
|
|
40
|
+
/**
|
|
41
|
+
* Cifra `plaintext` para cada llave de `encPubs`, con MI privada de cifrado.
|
|
42
|
+
*
|
|
43
|
+
* Un destinatario cuya llave no se puede importar se OMITE y no aparece en `wrap`: quien llama
|
|
44
|
+
* mira si quedó alguien (`identitySealing` lo hace), porque un sobre sin envolturas está cifrado
|
|
45
|
+
* de verdad y no lo abre nadie.
|
|
46
|
+
*
|
|
47
|
+
* @param {{ myEncPrivateKey: any, encPubs: Iterable<string>, plaintext: string }} args
|
|
48
|
+
* @returns {Promise<E2eEnvelope>}
|
|
49
|
+
*/
|
|
50
|
+
export function encryptFor({ myEncPrivateKey, encPubs, plaintext }: {
|
|
51
|
+
myEncPrivateKey: any;
|
|
52
|
+
encPubs: Iterable<string>;
|
|
53
|
+
plaintext: string;
|
|
54
|
+
}): Promise<E2eEnvelope>;
|
|
55
|
+
/**
|
|
56
|
+
* Abre un sobre que me mandó `senderEncPub`. Busca MI envoltura por el id de mi llave (v2);
|
|
57
|
+
* `myToken` solo por los sobres v1, que se indexaban por la conexión.
|
|
58
|
+
*
|
|
59
|
+
* Lanza si no soy destinatario o si no lo selló esa llave (AES-GCM no autentica con otra).
|
|
60
|
+
*
|
|
61
|
+
* @param {{ myEncPrivateKey: any, myEncPub: string, senderEncPub: string, envelope: any, myToken?: string | null }} args
|
|
62
|
+
* @returns {Promise<string>}
|
|
63
|
+
*/
|
|
64
|
+
export function decryptFrom({ myEncPrivateKey, myEncPub, senderEncPub, envelope, myToken }: {
|
|
65
|
+
myEncPrivateKey: any;
|
|
66
|
+
myEncPub: string;
|
|
67
|
+
senderEncPub: string;
|
|
68
|
+
envelope: any;
|
|
69
|
+
myToken?: string | null;
|
|
70
|
+
}): Promise<string>;
|
|
71
|
+
/**
|
|
72
|
+
* UNA IDENTIDAD DE CIFRADO desde un par de llaves suelto, con el dialecto del núcleo
|
|
73
|
+
* (`encryptionPubkey()`, `encrypt(destinatarios, texto)`, `decrypt(remitente, sobre)` →
|
|
74
|
+
* cadena). Es lo que `identitySealing` de `@dotrino/proxy-client` acepta, así que un aparato
|
|
75
|
+
* headless sella con el mismo sobre que una app del navegador:
|
|
76
|
+
*
|
|
77
|
+
* identitySealing(keyIdentity({ encPub, privateKey }), { app: 'messenger' })
|
|
78
|
+
*
|
|
79
|
+
* No expande destinatarios por su tarjeta de perfil (no tiene libreta): cifra a las llaves que
|
|
80
|
+
* se le dan.
|
|
81
|
+
*
|
|
82
|
+
* @param {{ encPub: string, privateKey: any }} keys
|
|
83
|
+
*/
|
|
84
|
+
export function keyIdentity({ encPub, privateKey }: {
|
|
85
|
+
encPub: string;
|
|
86
|
+
privateKey: any;
|
|
87
|
+
}): {
|
|
88
|
+
encryptionPubkey: () => string;
|
|
89
|
+
/** @param {Array<{ encryptionPubkey?: string }>} recipients @param {string} plaintext */
|
|
90
|
+
encrypt: (recipients: Array<{
|
|
91
|
+
encryptionPubkey?: string;
|
|
92
|
+
}>, plaintext: string) => Promise<E2eEnvelope>;
|
|
93
|
+
/** @param {string} senderEncPub @param {any} envelope */
|
|
94
|
+
decrypt: (senderEncPub: string, envelope: any) => Promise<string>;
|
|
95
|
+
};
|
|
96
|
+
export type E2eEnvelope = {
|
|
97
|
+
v: 2;
|
|
98
|
+
iv: string;
|
|
99
|
+
ct: string;
|
|
100
|
+
wrap: Record<string, {
|
|
101
|
+
iv: string;
|
|
102
|
+
ct: string;
|
|
103
|
+
}>;
|
|
104
|
+
};
|
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
|
-
|
|
153
|
-
export
|
|
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
|
-
|
|
4084
|
-
|
|
4085
|
-
|
|
4086
|
-
|
|
4087
|
-
|
|
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,165 @@
|
|
|
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
|
+
/** @param {ArrayBuffer | ArrayLike<number>} buf @returns {string} */
|
|
19
|
+
export function bufToBase64 (buf) {
|
|
20
|
+
const bytes = new Uint8Array(buf)
|
|
21
|
+
let s = ''
|
|
22
|
+
for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i])
|
|
23
|
+
return btoa(s)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param {string} b64 @returns {ArrayBuffer} */
|
|
27
|
+
export function base64ToBuf (b64) {
|
|
28
|
+
const s = atob(b64)
|
|
29
|
+
const bytes = new Uint8Array(s.length)
|
|
30
|
+
for (let i = 0; i < s.length; i++) bytes[i] = s.charCodeAt(i)
|
|
31
|
+
return bytes.buffer
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @param {string | JsonWebKey} jwkStr @returns {Promise<CryptoKey>} */
|
|
35
|
+
export async function importPeerEncPubkey (jwkStr) {
|
|
36
|
+
const jwk = typeof jwkStr === 'string' ? JSON.parse(jwkStr) : jwkStr
|
|
37
|
+
return crypto.subtle.importKey('jwk', jwk, { name: 'ECDH', namedCurve: 'P-256' }, true, [])
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* La clave AES compartida entre mi privada y la pública del otro.
|
|
42
|
+
* @param {any} myPriv CryptoKey ECDH, o el asa de una llave del chip (`external`)
|
|
43
|
+
* @param {CryptoKey} peerPub
|
|
44
|
+
* @returns {Promise<CryptoKey>}
|
|
45
|
+
*/
|
|
46
|
+
export async function deriveSharedAesKey (myPriv, peerPub) {
|
|
47
|
+
if (myPriv?.external) {
|
|
48
|
+
// Llave EXTERNA: el chip da los 32 bytes del secreto ECDH, que es exactamente lo que
|
|
49
|
+
// `deriveKey` ECDH→AES-256 usa por dentro. Mismo AES, sin que la privada salga.
|
|
50
|
+
const { kty, crv, x, y } = await crypto.subtle.exportKey('jwk', peerPub)
|
|
51
|
+
const bits = await myPriv.deriveBits(JSON.stringify({ kty, crv, x, y }))
|
|
52
|
+
return crypto.subtle.importKey('raw', bits, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
|
|
53
|
+
}
|
|
54
|
+
if (!myPriv?.usages?.includes('deriveKey')) {
|
|
55
|
+
// Una llave que solo admite `deriveBits` (la de un agente, `makeEncKeypair`): los mismos
|
|
56
|
+
// 32 bytes del secreto ECDH, y el mismo AES que daría `deriveKey`.
|
|
57
|
+
const bits = await crypto.subtle.deriveBits({ name: 'ECDH', public: peerPub }, myPriv, 256)
|
|
58
|
+
return crypto.subtle.importKey('raw', bits, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
|
|
59
|
+
}
|
|
60
|
+
return crypto.subtle.deriveKey(
|
|
61
|
+
{ name: 'ECDH', public: peerPub },
|
|
62
|
+
myPriv,
|
|
63
|
+
{ name: 'AES-GCM', length: 256 },
|
|
64
|
+
false,
|
|
65
|
+
['encrypt', 'decrypt']
|
|
66
|
+
)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Id estable y corto de una llave de cifrado: con esto se indexan las envolturas. Es el
|
|
71
|
+
* `pubkeyId` de `capabilities.js` (SHA-256 del JWK canónico) cortado a 16.
|
|
72
|
+
* @param {string} encPub
|
|
73
|
+
* @returns {Promise<string>}
|
|
74
|
+
*/
|
|
75
|
+
export async function encKeyId (encPub) {
|
|
76
|
+
const { pubkeyId } = await import('./capabilities.js')
|
|
77
|
+
return (await pubkeyId(encPub)).slice(0, 16)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* @typedef {{ v: 2, iv: string, ct: string, wrap: Record<string, { iv: string, ct: string }> }} E2eEnvelope
|
|
82
|
+
*/
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Cifra `plaintext` para cada llave de `encPubs`, con MI privada de cifrado.
|
|
86
|
+
*
|
|
87
|
+
* Un destinatario cuya llave no se puede importar se OMITE y no aparece en `wrap`: quien llama
|
|
88
|
+
* mira si quedó alguien (`identitySealing` lo hace), porque un sobre sin envolturas está cifrado
|
|
89
|
+
* de verdad y no lo abre nadie.
|
|
90
|
+
*
|
|
91
|
+
* @param {{ myEncPrivateKey: any, encPubs: Iterable<string>, plaintext: string }} args
|
|
92
|
+
* @returns {Promise<E2eEnvelope>}
|
|
93
|
+
*/
|
|
94
|
+
export async function encryptFor ({ myEncPrivateKey, encPubs, plaintext }) {
|
|
95
|
+
if (!myEncPrivateKey) throw new Error('encryptFor: myEncPrivateKey required')
|
|
96
|
+
if (typeof plaintext !== 'string') throw new Error('plaintext required')
|
|
97
|
+
const k = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt'])
|
|
98
|
+
const kRaw = await crypto.subtle.exportKey('raw', k)
|
|
99
|
+
const iv = crypto.getRandomValues(new Uint8Array(12))
|
|
100
|
+
const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, k, new TextEncoder().encode(plaintext))
|
|
101
|
+
/** @type {Record<string, { iv: string, ct: string }>} */
|
|
102
|
+
const wrap = {}
|
|
103
|
+
for (const encPub of new Set(encPubs)) {
|
|
104
|
+
try {
|
|
105
|
+
const peerPub = await importPeerEncPubkey(encPub)
|
|
106
|
+
const sharedKey = await deriveSharedAesKey(myEncPrivateKey, peerPub)
|
|
107
|
+
const wrapIv = crypto.getRandomValues(new Uint8Array(12))
|
|
108
|
+
const wrappedCt = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: wrapIv }, sharedKey, kRaw)
|
|
109
|
+
wrap[await encKeyId(encPub)] = { iv: bufToBase64(wrapIv), ct: bufToBase64(new Uint8Array(wrappedCt)) }
|
|
110
|
+
} catch (_) { /* destinatario omitido: lo mira quien llama */ }
|
|
111
|
+
}
|
|
112
|
+
return { v: 2, iv: bufToBase64(iv), ct: bufToBase64(new Uint8Array(ct)), wrap }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Abre un sobre que me mandó `senderEncPub`. Busca MI envoltura por el id de mi llave (v2);
|
|
117
|
+
* `myToken` solo por los sobres v1, que se indexaban por la conexión.
|
|
118
|
+
*
|
|
119
|
+
* Lanza si no soy destinatario o si no lo selló esa llave (AES-GCM no autentica con otra).
|
|
120
|
+
*
|
|
121
|
+
* @param {{ myEncPrivateKey: any, myEncPub: string, senderEncPub: string, envelope: any, myToken?: string | null }} args
|
|
122
|
+
* @returns {Promise<string>}
|
|
123
|
+
*/
|
|
124
|
+
export async function decryptFrom ({ myEncPrivateKey, myEncPub, senderEncPub, envelope, myToken = null }) {
|
|
125
|
+
if (!senderEncPub) throw new Error('senderEncryptionPubkey required')
|
|
126
|
+
if (!envelope || (envelope.v !== 1 && envelope.v !== 2)) throw new Error('Unsupported envelope')
|
|
127
|
+
const myId = await encKeyId(myEncPub)
|
|
128
|
+
const myEntry = envelope.wrap && (envelope.wrap[myId] || (myToken ? envelope.wrap[myToken] : null))
|
|
129
|
+
if (!myEntry) throw new Error('this device is not among the message recipients')
|
|
130
|
+
const senderPub = await importPeerEncPubkey(senderEncPub)
|
|
131
|
+
const sharedKey = await deriveSharedAesKey(myEncPrivateKey, senderPub)
|
|
132
|
+
const kRaw = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: new Uint8Array(base64ToBuf(myEntry.iv)) }, sharedKey, base64ToBuf(myEntry.ct))
|
|
133
|
+
const k = await crypto.subtle.importKey('raw', kRaw, { name: 'AES-GCM', length: 256 }, false, ['decrypt'])
|
|
134
|
+
const ptBytes = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: new Uint8Array(base64ToBuf(envelope.iv)) }, k, base64ToBuf(envelope.ct))
|
|
135
|
+
return new TextDecoder().decode(ptBytes)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* UNA IDENTIDAD DE CIFRADO desde un par de llaves suelto, con el dialecto del núcleo
|
|
140
|
+
* (`encryptionPubkey()`, `encrypt(destinatarios, texto)`, `decrypt(remitente, sobre)` →
|
|
141
|
+
* cadena). Es lo que `identitySealing` de `@dotrino/proxy-client` acepta, así que un aparato
|
|
142
|
+
* headless sella con el mismo sobre que una app del navegador:
|
|
143
|
+
*
|
|
144
|
+
* identitySealing(keyIdentity({ encPub, privateKey }), { app: 'messenger' })
|
|
145
|
+
*
|
|
146
|
+
* No expande destinatarios por su tarjeta de perfil (no tiene libreta): cifra a las llaves que
|
|
147
|
+
* se le dan.
|
|
148
|
+
*
|
|
149
|
+
* @param {{ encPub: string, privateKey: any }} keys
|
|
150
|
+
*/
|
|
151
|
+
export function keyIdentity ({ encPub, privateKey }) {
|
|
152
|
+
if (typeof encPub !== 'string' || !encPub) throw new Error('keyIdentity: encPub required')
|
|
153
|
+
if (!privateKey) throw new Error('keyIdentity: privateKey required')
|
|
154
|
+
return {
|
|
155
|
+
encryptionPubkey: () => encPub,
|
|
156
|
+
/** @param {Array<{ encryptionPubkey?: string }>} recipients @param {string} plaintext */
|
|
157
|
+
encrypt: (recipients, plaintext) => encryptFor({
|
|
158
|
+
myEncPrivateKey: privateKey,
|
|
159
|
+
encPubs: (recipients || []).flatMap((r) => (typeof r?.encryptionPubkey === 'string' && r.encryptionPubkey ? [r.encryptionPubkey] : [])),
|
|
160
|
+
plaintext
|
|
161
|
+
}),
|
|
162
|
+
/** @param {string} senderEncPub @param {any} envelope */
|
|
163
|
+
decrypt: (senderEncPub, envelope) => decryptFrom({ myEncPrivateKey: privateKey, myEncPub: encPub, senderEncPub, envelope })
|
|
164
|
+
}
|
|
165
|
+
}
|