@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.
- package/package.json +3 -2
- package/src/index.d.ts +60 -2
- package/src/index.js +364 -81
- package/src/node.js +29 -5
- package/types/acta.d.ts +397 -175
- package/types/assertion.d.ts +25 -18
- package/types/avatar.d.ts +14 -3
- package/types/capabilities.d.ts +110 -61
- package/types/content.d.ts +88 -45
- package/types/core.d.ts +578 -383
- package/types/keyid.d.ts +10 -3
- package/types/machine.d.ts +5 -1
- package/types/peerStore.d.ts +80 -0
- package/types/peerSync.d.ts +20 -6
- package/types/remote.d.ts +170 -42
- package/types/session.d.ts +74 -81
- package/types/sessionFlow.d.ts +108 -33
- package/types/vaultSeal.d.ts +21 -9
- package/vault/acta.js +245 -29
- package/vault/assertion.js +13 -4
- package/vault/avatar.js +12 -1
- package/vault/capabilities.js +56 -6
- package/vault/channel.js +18 -2
- package/vault/content.js +60 -6
- package/vault/core.js +419 -88
- package/vault/externalKeys.js +34 -2
- package/vault/facade.js +182 -24
- package/vault/globals.d.ts +60 -0
- package/vault/keyid.js +10 -1
- package/vault/machine.js +7 -1
- package/vault/nativeStore.js +21 -4
- package/vault/originPolicy.js +13 -2
- package/vault/peerStore.js +57 -10
- package/vault/peerSync.js +23 -4
- package/vault/remote.js +132 -32
- package/vault/session.js +24 -7
- package/vault/sessionFlow.js +43 -9
- package/vault/sync.js +59 -15
- package/vault/vault.js +78 -49
- package/vault/vaultSeal.js +18 -7
- package/vault/vendor/compat/VERSION.txt +1 -1
- package/vault/vendor/compat/advisory.js +58 -8
- package/vault/vendor/compat/index.js +57 -6
- package/vault/vendor/compat/ranges.js +12 -2
- package/vault/vendor/proxy-client/VERSION.txt +1 -1
- package/vault/vendor/proxy-client/client.js +41 -19
- package/vault/vendor/roadmap/manifests.js +23 -23
- package/vault/vendor/store/VERSION.txt +1 -1
- package/vault/vendor/vault/VERSION.txt +1 -1
- package/vault/vendor/vault/core/libVersion.js +1 -1
- package/vault/vendor/vault/core/transport.js +15 -3
- package/vault/vendor/vault/core/vault.js +71 -1
- package/vault/vendor/vault/protocol.js +25 -0
package/vault/assertion.js
CHANGED
|
@@ -75,16 +75,22 @@ export const newAssertionNonce = () => crypto.randomUUID()
|
|
|
75
75
|
* Pedir alcances desconocidos NO es un aviso que se pueda ignorar: se descartan, y si no
|
|
76
76
|
* queda ninguno se emite el mínimo (`id:whoami`), que es lo que significa «solo quiero
|
|
77
77
|
* saber quién eres».
|
|
78
|
+
* @param {unknown} scopes
|
|
79
|
+
* @returns {string[]}
|
|
78
80
|
*/
|
|
79
81
|
export function cleanScopes (scopes) {
|
|
80
82
|
const list = [...new Set((Array.isArray(scopes) ? scopes : []).filter((s) => SCOPES.includes(s)))].sort()
|
|
81
83
|
return list.length ? list : ['id:whoami']
|
|
82
84
|
}
|
|
83
85
|
|
|
84
|
-
/**
|
|
86
|
+
/**
|
|
87
|
+
* Las claves de datos que esos alcances permiten llevar.
|
|
88
|
+
* @param {unknown} scopes
|
|
89
|
+
* @returns {Set<string>}
|
|
90
|
+
*/
|
|
85
91
|
export function claimsAllowed (scopes) {
|
|
86
92
|
const out = new Set()
|
|
87
|
-
for (const s of cleanScopes(scopes)) for (const c of SCOPE_CLAIMS[s]) out.add(c)
|
|
93
|
+
for (const s of cleanScopes(scopes)) for (const c of SCOPE_CLAIMS[/** @type {keyof typeof SCOPE_CLAIMS} */ (s)]) out.add(c)
|
|
88
94
|
return out
|
|
89
95
|
}
|
|
90
96
|
|
|
@@ -96,6 +102,7 @@ export function claimsAllowed (scopes) {
|
|
|
96
102
|
*
|
|
97
103
|
* Lanza si le falta algo: es un error de programación de quien emite, no un dato del otro
|
|
98
104
|
* lado que pueda venir mal.
|
|
105
|
+
* @param {{ sub: string, aud: string, nonce: string, scopes?: unknown, claims?: Record<string, unknown> | null, iat: number, exp: number }} args
|
|
99
106
|
*/
|
|
100
107
|
export function assertionBody ({ sub, aud, nonce, scopes, claims, iat, exp }) {
|
|
101
108
|
if (typeof sub !== 'string' || !sub) throw new Error('assertion: sub required')
|
|
@@ -106,6 +113,7 @@ export function assertionBody ({ sub, aud, nonce, scopes, claims, iat, exp }) {
|
|
|
106
113
|
if (exp - iat > ASSERTION_MAX_TTL_MS) throw new Error('assertion: lifetime over the cap')
|
|
107
114
|
const granted = cleanScopes(scopes)
|
|
108
115
|
const permitido = claimsAllowed(granted)
|
|
116
|
+
/** @type {Record<string, unknown>} */
|
|
109
117
|
const out = {}
|
|
110
118
|
for (const [k, v] of Object.entries(claims || {})) {
|
|
111
119
|
// NO se recorta en silencio lo que sobra: llevar un dato sin su alcance es entregar
|
|
@@ -117,6 +125,7 @@ export function assertionBody ({ sub, aud, nonce, scopes, claims, iat, exp }) {
|
|
|
117
125
|
}
|
|
118
126
|
|
|
119
127
|
/** Los campos del cuerpo, sacados de una prueba completa (que además lleva firma y cadena). */
|
|
128
|
+
/** @param {any} a */
|
|
120
129
|
const bodyOf = (a) => ({ v: a.v, op: a.op, sub: a.sub, aud: a.aud, nonce: a.nonce, iat: a.iat, exp: a.exp, scopes: a.scopes, claims: a.claims })
|
|
121
130
|
|
|
122
131
|
/**
|
|
@@ -157,7 +166,7 @@ export async function verifyAssertion (assertion, opts = {}) {
|
|
|
157
166
|
if (a.exp <= now) return { ok: false, reason: 'expired' }
|
|
158
167
|
if (a.iat > now + maxSkewMs) return { ok: false, reason: 'from-future' }
|
|
159
168
|
|
|
160
|
-
if (a.scopes.some((s) => !SCOPES.includes(s))) return { ok: false, reason: 'unknown-scope' }
|
|
169
|
+
if (a.scopes.some((/** @type {string} */ s) => !SCOPES.includes(s))) return { ok: false, reason: 'unknown-scope' }
|
|
161
170
|
const permitido = claimsAllowed(a.scopes)
|
|
162
171
|
if (Object.keys(a.claims || {}).some((k) => !permitido.has(k))) return { ok: false, reason: 'claim-without-scope' }
|
|
163
172
|
|
|
@@ -231,7 +240,7 @@ export async function verifySignedFor (args = {}) {
|
|
|
231
240
|
* @param {{ signData: (d: object) => Promise<{ signature: string, publickey: string, chain?: any[] }> }} identity
|
|
232
241
|
* @param {{ aud: string, fields?: object, ttlMs?: number, now?: number }} opts
|
|
233
242
|
*/
|
|
234
|
-
export async function signedFor (identity, { aud, fields = {}, ttlMs = 24 * 60 * 60 * 1000, now = Date.now() } = {}) {
|
|
243
|
+
export async function signedFor (identity, { aud, fields = {}, ttlMs = 24 * 60 * 60 * 1000, now = Date.now() } = /** @type {any} */ ({})) {
|
|
235
244
|
if (typeof aud !== 'string' || !aud.trim()) throw Object.assign(new Error('signedFor: aud is required'), { code: 'no-audience' })
|
|
236
245
|
const body = { aud: aud.trim(), iat: now, exp: now + ttlMs, nonce: crypto.randomUUID(), ...fields }
|
|
237
246
|
const s = await identity.signData(body)
|
package/vault/avatar.js
CHANGED
|
@@ -19,9 +19,11 @@
|
|
|
19
19
|
*/
|
|
20
20
|
|
|
21
21
|
/** Hash FNV-1a + xorshift. Sin necesidades de seguridad: es decorativo. */
|
|
22
|
+
/** @param {string} s @returns {{ h: number, bytes: number[] }} */
|
|
22
23
|
function _hashSeed (s) {
|
|
23
24
|
let h = 2166136261 >>> 0
|
|
24
25
|
for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619) }
|
|
26
|
+
/** @type {number[]} */
|
|
25
27
|
const bytes = []
|
|
26
28
|
let x = (h ^ 0x9e3779b9) >>> 0
|
|
27
29
|
for (let i = 0; i < 16; i++) { x ^= x << 13; x ^= x >>> 17; x ^= x << 5; x >>>= 0; bytes.push(x & 0xff) }
|
|
@@ -33,6 +35,10 @@ function _hashSeed (s) {
|
|
|
33
35
|
* nace con imagen sin que el usuario tenga que subir nada. Síncrono → usable
|
|
34
36
|
* directo en plantillas. Rejilla 5×5 simétrica sobre una "moneda" redondeada,
|
|
35
37
|
* con color derivado del hash.
|
|
38
|
+
*
|
|
39
|
+
* @param {unknown} seed
|
|
40
|
+
* @param {{ size?: number }} [opts]
|
|
41
|
+
* @returns {string}
|
|
36
42
|
*/
|
|
37
43
|
export function avatarSvg (seed, { size = 80 } = {}) {
|
|
38
44
|
const { h, bytes } = _hashSeed(String(seed || 'dotrino'))
|
|
@@ -59,7 +65,12 @@ export function avatarSvg (seed, { size = 80 } = {}) {
|
|
|
59
65
|
`<g fill="${fg}" transform="translate(${(size * 0.12).toFixed(2)} ${(size * 0.12).toFixed(2)}) scale(0.76)">${rects}</g></svg>`
|
|
60
66
|
}
|
|
61
67
|
|
|
62
|
-
/**
|
|
68
|
+
/**
|
|
69
|
+
* El avatar como data-URI listo para `<img src>` o `background-image`.
|
|
70
|
+
* @param {unknown} seed
|
|
71
|
+
* @param {{ size?: number }} [opts]
|
|
72
|
+
* @returns {string}
|
|
73
|
+
*/
|
|
63
74
|
export function avatarDataUri (seed, opts) {
|
|
64
75
|
return 'data:image/svg+xml,' + encodeURIComponent(avatarSvg(seed, opts))
|
|
65
76
|
}
|
package/vault/capabilities.js
CHANGED
|
@@ -23,6 +23,22 @@
|
|
|
23
23
|
import { canonicalStringify, bufToBase64, base64ToBuf } from './core.js'
|
|
24
24
|
import { pubkeyId, keyLabel } from './keyid.js'
|
|
25
25
|
|
|
26
|
+
/**
|
|
27
|
+
* Una llave que firma: una CryptoKey, o una llave que vive fuera (el chip del teléfono) y
|
|
28
|
+
* firma por su cuenta.
|
|
29
|
+
* @typedef {CryptoKey | { external: true, sign: (bytes: Uint8Array) => Promise<string> }} SigningKey
|
|
30
|
+
*/
|
|
31
|
+
/**
|
|
32
|
+
* Un certificado de delegación: `iss` autoriza a `sub` para `scope`, válido mientras el acta
|
|
33
|
+
* no lo deje atrás (`seq`). Los viejos llevaban `exp` en vez de `seq`.
|
|
34
|
+
* @typedef {{ v: number, iss: string, sub: string, scope: string | string[], iat: number,
|
|
35
|
+
* seq?: number, exp?: number, nonce?: string, sig: string }} Delegation
|
|
36
|
+
*/
|
|
37
|
+
/**
|
|
38
|
+
* Qué nonces están revocados: una función, un Set o un objeto `{ nonce: true }`.
|
|
39
|
+
* @typedef {((nonce: string) => boolean) | Set<string> | Record<string, unknown>} RevokedSet
|
|
40
|
+
*/
|
|
41
|
+
|
|
26
42
|
const ECDSA = { name: 'ECDSA', namedCurve: 'P-256' }
|
|
27
43
|
const ECDH = { name: 'ECDH', namedCurve: 'P-256' }
|
|
28
44
|
const SIGN = { name: 'ECDSA', hash: { name: 'SHA-256' } }
|
|
@@ -34,14 +50,23 @@ const SIGN = { name: 'ECDSA', hash: { name: 'SHA-256' } }
|
|
|
34
50
|
* el mismo código que daba el repliegue al caducar, así que quien lo comprueba no cambia.
|
|
35
51
|
*/
|
|
36
52
|
|
|
53
|
+
/** @param {string} s */
|
|
37
54
|
const enc = (s) => new TextEncoder().encode(s)
|
|
38
55
|
|
|
56
|
+
/**
|
|
57
|
+
* @param {SigningKey | null | undefined} k
|
|
58
|
+
* @returns {k is { external: true, sign: (bytes: Uint8Array) => Promise<string> }}
|
|
59
|
+
*/
|
|
60
|
+
const isExternal = (k) => !!(/** @type {{ external?: unknown } | null | undefined} */ (k))?.external
|
|
61
|
+
|
|
62
|
+
/** @param {SigningKey} privateKey @param {Uint8Array<ArrayBuffer>} bytes @returns {Promise<string>} */
|
|
39
63
|
async function rawSign (privateKey, bytes) {
|
|
40
64
|
// Una llave EXTERNA (el chip del teléfono, `vault/vault.js`) firma ella misma: aquí no
|
|
41
65
|
// hay CryptoKey que pasarle a WebCrypto. Devuelve la misma firma P1363 en base64.
|
|
42
|
-
if (privateKey
|
|
43
|
-
return bufToBase64(await crypto.subtle.sign(SIGN, privateKey, bytes))
|
|
66
|
+
if (isExternal(privateKey)) return privateKey.sign(bytes)
|
|
67
|
+
return bufToBase64(await crypto.subtle.sign(SIGN, /** @type {CryptoKey} */ (privateKey), bytes))
|
|
44
68
|
}
|
|
69
|
+
/** @param {string} publicJwkStr @param {Uint8Array<ArrayBuffer>} bytes @param {string} sigB64 @returns {Promise<boolean>} */
|
|
45
70
|
async function rawVerify (publicJwkStr, bytes, sigB64) {
|
|
46
71
|
let pub
|
|
47
72
|
try { pub = await crypto.subtle.importKey('jwk', JSON.parse(publicJwkStr), ECDSA, true, ['verify']) }
|
|
@@ -50,7 +75,9 @@ async function rawVerify (publicJwkStr, bytes, sigB64) {
|
|
|
50
75
|
catch (_) { return false }
|
|
51
76
|
}
|
|
52
77
|
|
|
78
|
+
/** @param {JsonWebKey} privateJwk */
|
|
53
79
|
const publicOf = (privateJwk) => ({ kty: privateJwk.kty, crv: privateJwk.crv, x: privateJwk.x, y: privateJwk.y })
|
|
80
|
+
/** @param {string | string[]} scope @param {string} expected */
|
|
54
81
|
const scopeAllows = (scope, expected) => Array.isArray(scope) ? scope.includes(expected) : scope === expected
|
|
55
82
|
|
|
56
83
|
// El id de una llave y su huella legible viven en `./keyid.js`, que no tiene dependencias:
|
|
@@ -62,6 +89,8 @@ export { pubkeyId, keyLabel }
|
|
|
62
89
|
* `publickey` (JWK string). Prueba de POSESION de una sub-clave de dispositivo (no
|
|
63
90
|
* es cadena de delegacion): la usa el vault para confirmar que quien pide enrolar
|
|
64
91
|
* `dpub` realmente tiene su privada (un token robado ya no alcanza para enrolar).
|
|
92
|
+
* @param {{ publickey: unknown, data: unknown, signature: unknown }} args
|
|
93
|
+
* @returns {Promise<boolean>}
|
|
65
94
|
*/
|
|
66
95
|
export async function verifyDeviceSig ({ publickey, data, signature }) {
|
|
67
96
|
if (typeof publickey !== 'string' || typeof signature !== 'string') return false
|
|
@@ -74,6 +103,10 @@ export async function verifyDeviceSig ({ publickey, data, signature }) {
|
|
|
74
103
|
* visualmente entre las dos pantallas (PC del vault y dispositivo) al emparejar —
|
|
75
104
|
* eso mata el relay/phishing (un atacante remoto no puede mostrar el SAS correcto
|
|
76
105
|
* en el dispositivo fisico de la victima).
|
|
106
|
+
* @param {string} master
|
|
107
|
+
* @param {string} dpub
|
|
108
|
+
* @param {unknown} sn
|
|
109
|
+
* @returns {Promise<string>}
|
|
77
110
|
*/
|
|
78
111
|
export async function deriveSAS (master, dpub, sn) {
|
|
79
112
|
const h = new Uint8Array(await crypto.subtle.digest('SHA-256', enc(canonicalStringify({ iss: master, sub: dpub, sn }))))
|
|
@@ -86,6 +119,7 @@ export async function deriveSAS (master, dpub, sn) {
|
|
|
86
119
|
* el usuario lo tipea en el vault. El vault NO lo conoce: el dispositivo solo manda un
|
|
87
120
|
* COMPROMISO (`commitCode`), no el código → el vault lo aprende únicamente cuando vos se lo
|
|
88
121
|
* das, tipeándolo. Así, aprobar exige TENER el dispositivo (de ahí sale el código).
|
|
122
|
+
* @returns {string}
|
|
89
123
|
*/
|
|
90
124
|
export function makePairingCode () {
|
|
91
125
|
const b = crypto.getRandomValues(new Uint8Array(4))
|
|
@@ -97,6 +131,8 @@ export function makePairingCode () {
|
|
|
97
131
|
* Compromiso del código: `SHA-256(code ‖ dpub ‖ sn)` en hex. Va en el ENROLL (no el código).
|
|
98
132
|
* Liga el código a ESTE dispositivo y sesión (no reusable para otro). El vault lo guarda y,
|
|
99
133
|
* cuando tipeás el código, recomputa y compara → verifica posesión sin conocer el código antes.
|
|
134
|
+
* @param {{ code: unknown, dpub: string, sn: unknown }} args
|
|
135
|
+
* @returns {Promise<string>}
|
|
100
136
|
*/
|
|
101
137
|
export async function commitCode ({ code, dpub, sn }) {
|
|
102
138
|
const h = await crypto.subtle.digest('SHA-256', enc(canonicalStringify({ code: String(code), sub: dpub, sn })))
|
|
@@ -121,6 +157,7 @@ export { avatarSvg, avatarDataUri } from './avatar.js'
|
|
|
121
157
|
* Atarlo al `seq` hace las dos cosas de golpe: quitarle un permiso a un aparato surte
|
|
122
158
|
* efecto AL INSTANTE (el acta sube de `seq` y su papel deja de valer, sin esperar a
|
|
123
159
|
* ninguna renovación), y nadie tiene que abrir nada por calendario.
|
|
160
|
+
* @param {Delegation} cert
|
|
124
161
|
*/
|
|
125
162
|
export function delegationBody (cert) {
|
|
126
163
|
// LA FORMA DEL CUERPO ES LA DEL PAPEL, no la del código que lo lee. Un papel del modelo
|
|
@@ -136,6 +173,7 @@ export function delegationBody (cert) {
|
|
|
136
173
|
/**
|
|
137
174
|
* Genera una sub-clave de DISPOSITIVO `D`. Corre EN el dispositivo / bridge; la
|
|
138
175
|
* clave maestra nunca ve la privada. Solo `publickey` (JWK string) sale del device.
|
|
176
|
+
* @param {{ label?: string }} [opts]
|
|
139
177
|
*/
|
|
140
178
|
export async function makeDeviceKey ({ label = '' } = {}) {
|
|
141
179
|
const pair = await crypto.subtle.generateKey(ECDSA, true, ['sign', 'verify'])
|
|
@@ -177,6 +215,8 @@ export async function makeDeviceEncKey () {
|
|
|
177
215
|
* Existe para que nadie la importe a mano: `deriveBits` es el ÚNICO uso correcto, y
|
|
178
216
|
* pedir otro (`deriveKey`) hace fallar la importación en Node con un error que no
|
|
179
217
|
* dice nada útil.
|
|
218
|
+
* @param {JsonWebKey} encPrivateJwk
|
|
219
|
+
* @returns {Promise<CryptoKey>}
|
|
180
220
|
*/
|
|
181
221
|
export async function importDeviceEncKey (encPrivateJwk) {
|
|
182
222
|
if (!encPrivateJwk || typeof encPrivateJwk !== 'object') throw new Error('importDeviceEncKey: missing private JWK')
|
|
@@ -187,6 +227,10 @@ export async function importDeviceEncKey (encPrivateJwk) {
|
|
|
187
227
|
* Firma un certificado de delegación con una `privateKey` (CryptoKey) cuyo pubkey
|
|
188
228
|
* es `iss`. Lo usa el handler del vault (con la clave maestra). Devuelve el cert
|
|
189
229
|
* completo `{ v, iss, sub, scope, iat, seq, nonce, sig }`.
|
|
230
|
+
* @param {SigningKey} privateKey
|
|
231
|
+
* @param {string} iss
|
|
232
|
+
* @param {{ sub: string, scope: string | string[], iat: number, seq: number, nonce?: string }} body
|
|
233
|
+
* @returns {Promise<Delegation>}
|
|
190
234
|
*/
|
|
191
235
|
export async function signDelegationWith (privateKey, iss, { sub, scope, iat, seq, nonce }) {
|
|
192
236
|
const body = { v: 1, iss, sub, scope, iat, seq, nonce }
|
|
@@ -197,6 +241,8 @@ export async function signDelegationWith (privateKey, iss, { sub, scope, iat, se
|
|
|
197
241
|
/**
|
|
198
242
|
* Firma datos con la clave de DISPOSITIVO (formato byte-idéntico a `signData` del
|
|
199
243
|
* vault → lo que el dispositivo/bridge usa para firmar cada pin/acción).
|
|
244
|
+
* @param {{ privateJwk?: JsonWebKey, privateKey?: SigningKey | null, publickey?: string, data: unknown, sign?: ((text: string) => Promise<string>) | null }} args
|
|
245
|
+
* @returns {Promise<{ signature: string, publickey: string }>}
|
|
200
246
|
*/
|
|
201
247
|
export async function signWithDevice ({ privateJwk, privateKey, publickey, data, sign }) {
|
|
202
248
|
// UNA LLAVE QUE NO VIVE AQUÍ (la del chip del teléfono, en la app nativa): se le pasa el
|
|
@@ -217,9 +263,11 @@ export async function signWithDevice ({ privateJwk, privateKey, publickey, data,
|
|
|
217
263
|
const signature = await rawSign(privateKey, enc(canonicalStringify(data)))
|
|
218
264
|
return { signature, publickey }
|
|
219
265
|
}
|
|
220
|
-
|
|
266
|
+
// Sin llave ni firmador, el JWK es lo que queda; si tampoco está, `importKey` lanza.
|
|
267
|
+
const jwk = /** @type {JsonWebKey} */ (privateJwk)
|
|
268
|
+
const priv = await crypto.subtle.importKey('jwk', jwk, ECDSA, true, ['sign'])
|
|
221
269
|
const signature = await rawSign(priv, enc(canonicalStringify(data)))
|
|
222
|
-
return { signature, publickey: publickey || JSON.stringify(publicOf(
|
|
270
|
+
return { signature, publickey: publickey || JSON.stringify(publicOf(jwk)) }
|
|
223
271
|
}
|
|
224
272
|
|
|
225
273
|
/**
|
|
@@ -229,7 +277,8 @@ export async function signWithDevice ({ privateJwk, privateKey, publickey, data,
|
|
|
229
277
|
* 3) `scope` incluye `expectedScope` (si se pide),
|
|
230
278
|
* 4) `sub` === `expectedSub` (si se pide),
|
|
231
279
|
* 5) `nonce` no revocado (`revoked`: fn(nonce)→bool, Set o mapa).
|
|
232
|
-
* @
|
|
280
|
+
* @param {{ cert?: any, expectedScope?: string | null, expectedSub?: string | null, actaSeq?: number | null, sealers?: string[] | null, revoked?: RevokedSet | null }} [args]
|
|
281
|
+
* @returns {Promise<{ok:boolean, reason?:string, iss?: string, sub?: string, scope?: string | string[], iat?: number, seq?: number, nonce?: string}>}
|
|
233
282
|
*/
|
|
234
283
|
|
|
235
284
|
export async function verifyDelegation ({ cert, expectedScope, expectedSub, actaSeq = null, sealers = null, revoked } = {}) {
|
|
@@ -285,7 +334,8 @@ export async function verifyDelegation ({ cert, expectedScope, expectedSub, acta
|
|
|
285
334
|
* 2) el cert delega a ESTE dispositivo (`cert.sub === data.publickey`),
|
|
286
335
|
* 3) el cert es válido (firma de una selladora, scope, revocación),
|
|
287
336
|
* 4) opcional: `cert.iss === trustedIssuer` (fija la identidad maestra esperada).
|
|
288
|
-
* @
|
|
337
|
+
* @param {{ data?: any, signature?: unknown, cert?: any, expectedScope?: string | null, actaSeq?: number | null, sealers?: string[] | null, revoked?: RevokedSet | null }} [args]
|
|
338
|
+
* @returns {Promise<{ok:boolean, reason?:string, issuer?:string, device?:string, scope?: string | string[]}>}
|
|
289
339
|
*/
|
|
290
340
|
export async function verifyChain ({ data, signature, cert, expectedScope, actaSeq = null, sealers = null, revoked } = {}) {
|
|
291
341
|
if (!data || typeof data !== 'object' || typeof signature !== 'string') return { ok: false, reason: 'shape' }
|
package/vault/channel.js
CHANGED
|
@@ -20,12 +20,14 @@
|
|
|
20
20
|
const subtle = () => globalThis.crypto.subtle
|
|
21
21
|
|
|
22
22
|
const b64 = {
|
|
23
|
+
/** @param {ArrayBuffer | Uint8Array} buf @returns {string} */
|
|
23
24
|
enc (buf) {
|
|
24
25
|
const b = new Uint8Array(buf)
|
|
25
26
|
let s = ''
|
|
26
27
|
for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i])
|
|
27
28
|
return btoa(s)
|
|
28
29
|
},
|
|
30
|
+
/** @param {string} str @returns {Uint8Array<ArrayBuffer>} */
|
|
29
31
|
dec (str) {
|
|
30
32
|
const bin = atob(str)
|
|
31
33
|
const out = new Uint8Array(bin.length)
|
|
@@ -44,6 +46,10 @@ export async function makeEphemeral () {
|
|
|
44
46
|
/**
|
|
45
47
|
* Deriva la clave AES-256-GCM de la sesión a partir de la privada propia y la
|
|
46
48
|
* pub efímera (base64 raw) del otro extremo. `salt` liga la clave a la sesión.
|
|
49
|
+
* @param {CryptoKey} privateKey
|
|
50
|
+
* @param {string} otherPubB64
|
|
51
|
+
* @param {string} salt
|
|
52
|
+
* @returns {Promise<CryptoKey>}
|
|
47
53
|
*/
|
|
48
54
|
export async function deriveKey (privateKey, otherPubB64, salt) {
|
|
49
55
|
const otherPub = await subtle().importKey(
|
|
@@ -60,7 +66,12 @@ export async function deriveKey (privateKey, otherPubB64, salt) {
|
|
|
60
66
|
)
|
|
61
67
|
}
|
|
62
68
|
|
|
63
|
-
/**
|
|
69
|
+
/**
|
|
70
|
+
* Cifra un objeto JSON → sobre { iv, ct } (ambos base64).
|
|
71
|
+
* @param {CryptoKey} key
|
|
72
|
+
* @param {unknown} obj
|
|
73
|
+
* @returns {Promise<{ iv: string, ct: string }>}
|
|
74
|
+
*/
|
|
64
75
|
export async function seal (key, obj) {
|
|
65
76
|
const iv = globalThis.crypto.getRandomValues(new Uint8Array(12))
|
|
66
77
|
const pt = new TextEncoder().encode(JSON.stringify(obj))
|
|
@@ -68,7 +79,12 @@ export async function seal (key, obj) {
|
|
|
68
79
|
return { iv: b64.enc(iv), ct: b64.enc(ct) }
|
|
69
80
|
}
|
|
70
81
|
|
|
71
|
-
/**
|
|
82
|
+
/**
|
|
83
|
+
* Descifra un sobre { iv, ct } → objeto JSON. Lanza si el tag GCM no valida.
|
|
84
|
+
* @param {CryptoKey} key
|
|
85
|
+
* @param {{ iv: string, ct: string }} env
|
|
86
|
+
* @returns {Promise<any>}
|
|
87
|
+
*/
|
|
72
88
|
export async function open (key, env) {
|
|
73
89
|
const pt = await subtle().decrypt({ name: 'AES-GCM', iv: b64.dec(env.iv) }, key, b64.dec(env.ct))
|
|
74
90
|
return JSON.parse(new TextDecoder().decode(pt))
|
package/vault/content.js
CHANGED
|
@@ -23,12 +23,24 @@
|
|
|
23
23
|
const subtle = globalThis.crypto.subtle
|
|
24
24
|
const ECDH = { name: 'ECDH', namedCurve: 'P-256' }
|
|
25
25
|
|
|
26
|
+
/**
|
|
27
|
+
* La envoltura de la clave de contenido para un miembro: ECDH efímero + AES-GCM.
|
|
28
|
+
* @typedef {{ epk: string, iv: string, ct: string }} Wrap
|
|
29
|
+
*/
|
|
30
|
+
/**
|
|
31
|
+
* Un sobre cerrado con la clave de la cuenta (`gen` dice con cuál).
|
|
32
|
+
* @typedef {{ t?: string, gen: number, iv: string, ct: string }} CekEnvelope
|
|
33
|
+
*/
|
|
34
|
+
/** @typedef {import('./acta.js').KeyringGeneration} KeyringGeneration */
|
|
35
|
+
|
|
36
|
+
/** @param {ArrayBuffer | Uint8Array} buf @returns {string} */
|
|
26
37
|
const b64 = (buf) => {
|
|
27
38
|
const bytes = new Uint8Array(buf)
|
|
28
39
|
let s = ''
|
|
29
40
|
for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i])
|
|
30
41
|
return btoa(s)
|
|
31
42
|
}
|
|
43
|
+
/** @param {string} str @returns {Uint8Array<ArrayBuffer>} */
|
|
32
44
|
const fromB64 = (str) => {
|
|
33
45
|
const bin = atob(str)
|
|
34
46
|
const out = new Uint8Array(bin.length)
|
|
@@ -36,16 +48,25 @@ const fromB64 = (str) => {
|
|
|
36
48
|
return out
|
|
37
49
|
}
|
|
38
50
|
|
|
51
|
+
/**
|
|
52
|
+
* @param {any} privateKey una CryptoKey ECDH, o el asa de una llave del chip (`deriveBits`)
|
|
53
|
+
* @param {string} peerPubJwkStr
|
|
54
|
+
* @returns {Promise<CryptoKey>}
|
|
55
|
+
*/
|
|
39
56
|
async function sharedKey (privateKey, peerPubJwkStr) {
|
|
40
57
|
// Llave EXTERNA: el acuerdo ECDH lo hace el chip y devuelve los 32 bytes del secreto
|
|
41
58
|
// (lo mismo que `deriveBits(…, 256)`); la privada no sale de allí.
|
|
59
|
+
/** @type {ArrayBuffer} */
|
|
42
60
|
const bits = privateKey?.external
|
|
43
61
|
? await privateKey.deriveBits(peerPubJwkStr)
|
|
44
62
|
: await subtle.deriveBits({ name: 'ECDH', public: await subtle.importKey('jwk', JSON.parse(peerPubJwkStr), ECDH, false, []) }, privateKey, 256)
|
|
45
63
|
return subtle.importKey('raw', bits, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'])
|
|
46
64
|
}
|
|
47
65
|
|
|
48
|
-
/**
|
|
66
|
+
/**
|
|
67
|
+
* Genera una clave de contenido nueva (AES-256-GCM). Devuelve los bytes en base64.
|
|
68
|
+
* @returns {Promise<string>}
|
|
69
|
+
*/
|
|
49
70
|
export async function makeContentKey () {
|
|
50
71
|
const k = await subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt'])
|
|
51
72
|
return b64(await subtle.exportKey('raw', k))
|
|
@@ -54,6 +75,7 @@ export async function makeContentKey () {
|
|
|
54
75
|
/**
|
|
55
76
|
* Envuelve la CEK hacia la llave de cifrado de un miembro. La envoltura es pública: solo
|
|
56
77
|
* la abre quien tenga la privada de `memberEncPub`, así que puede viajar en el acta.
|
|
78
|
+
* @param {{ cek: string, memberEncPub: string }} args
|
|
57
79
|
* @returns {Promise<{epk:string, iv:string, ct:string}>}
|
|
58
80
|
*/
|
|
59
81
|
export async function wrapForMember ({ cek, memberEncPub }) {
|
|
@@ -71,7 +93,11 @@ export async function wrapForMember ({ cek, memberEncPub }) {
|
|
|
71
93
|
}
|
|
72
94
|
}
|
|
73
95
|
|
|
74
|
-
/**
|
|
96
|
+
/**
|
|
97
|
+
* Abre la envoltura con la llave de cifrado privada de ESTE miembro.
|
|
98
|
+
* @param {{ wrap: any, myEncPrivateKey: any }} args
|
|
99
|
+
* @returns {Promise<string>}
|
|
100
|
+
*/
|
|
75
101
|
export async function openWrap ({ wrap, myEncPrivateKey }) {
|
|
76
102
|
if (!wrap?.epk || !wrap?.iv || !wrap?.ct) throw new Error('invalid wrap')
|
|
77
103
|
const key = await sharedKey(myEncPrivateKey, wrap.epk)
|
|
@@ -83,10 +109,14 @@ export async function openWrap ({ wrap, myEncPrivateKey }) {
|
|
|
83
109
|
* Genera la CEK de una generación y la envuelve a TODOS los miembros que tengan llave de
|
|
84
110
|
* cifrado. Un miembro sin `encPub` simplemente no recibe envoltura (y por tanto no lee el
|
|
85
111
|
* contenido): se devuelve la lista para que la consola lo diga en vez de fallar en silencio.
|
|
112
|
+
* @param {{ members?: Array<{ pub: string, encPub?: string | null }> | null, gen?: number, cek?: string | null, now?: number }} args
|
|
113
|
+
* @returns {Promise<{ generation: KeyringGeneration, cek: string, sinLlave: Array<string | undefined> }>}
|
|
86
114
|
*/
|
|
87
115
|
export async function makeGeneration ({ members, gen = 1, cek = null, now = Date.now() }) {
|
|
88
116
|
const key = cek || await makeContentKey()
|
|
117
|
+
/** @type {Record<string, Wrap>} */
|
|
89
118
|
const wraps = {}
|
|
119
|
+
/** @type {Array<string | undefined>} */
|
|
90
120
|
const sinLlave = []
|
|
91
121
|
for (const m of members || []) {
|
|
92
122
|
if (!m?.encPub) { sinLlave.push(m?.pub); continue }
|
|
@@ -95,7 +125,11 @@ export async function makeGeneration ({ members, gen = 1, cek = null, now = Date
|
|
|
95
125
|
return { generation: { gen, createdAt: now, wraps }, cek: key, sinLlave }
|
|
96
126
|
}
|
|
97
127
|
|
|
98
|
-
/**
|
|
128
|
+
/**
|
|
129
|
+
* La CEK vigente para mí, sacada del llavero del acta. `null` si no tengo envoltura.
|
|
130
|
+
* @param {{ keyring?: KeyringGeneration[] | null, myPub: string, myEncPrivateKey: any }} args
|
|
131
|
+
* @returns {Promise<{ gen: number, cek: string } | null>}
|
|
132
|
+
*/
|
|
99
133
|
export async function myContentKey ({ keyring, myPub, myEncPrivateKey }) {
|
|
100
134
|
const gens = [...(keyring || [])].sort((a, b) => (b.gen || 0) - (a.gen || 0))
|
|
101
135
|
for (const g of gens) {
|
|
@@ -115,6 +149,7 @@ export async function myContentKey ({ keyring, myPub, myEncPrivateKey }) {
|
|
|
115
149
|
export const CEK_ENVELOPE = 'dotrino-cek'
|
|
116
150
|
|
|
117
151
|
/** ¿Es un sobre de la llave de la cuenta? */
|
|
152
|
+
/** @param {any} v @returns {v is CekEnvelope} */
|
|
118
153
|
export const isCekEnvelope = (v) => !!v && typeof v === 'object' && v.t === CEK_ENVELOPE &&
|
|
119
154
|
Number.isInteger(v.gen) && typeof v.iv === 'string' && typeof v.ct === 'string'
|
|
120
155
|
|
|
@@ -125,6 +160,8 @@ export const isCekEnvelope = (v) => !!v && typeof v === 'object' && v.t === CEK_
|
|
|
125
160
|
* cajones de secretos, cada entrada del gestor de contraseñas, el transporte). Por eso NO
|
|
126
161
|
* lleva la marca: la marca dice «esto es de la cuenta» y solo la pone `sealAccount`. En
|
|
127
162
|
* 0.107.0 la ponía aquí, y marcaba como de la cuenta sobres que la cuenta no abre.
|
|
163
|
+
* @param {{ cek: string, gen: number, plaintext: string }} args
|
|
164
|
+
* @returns {Promise<{ gen: number, iv: string, ct: string }>}
|
|
128
165
|
*/
|
|
129
166
|
export async function encryptWithCek ({ cek, gen, plaintext }) {
|
|
130
167
|
const k = await subtle.importKey('raw', fromB64(cek), { name: 'AES-GCM' }, false, ['encrypt'])
|
|
@@ -142,7 +179,7 @@ export async function encryptWithCek ({ cek, gen, plaintext }) {
|
|
|
142
179
|
* archivos: el archivo se cifra con una CEK nueva y solo la CEK pasa por el sellado de
|
|
143
180
|
* siempre (`wrapForMember`, o la bóveda).
|
|
144
181
|
*
|
|
145
|
-
* @param {{ cek: string, bytes: Uint8Array }} o
|
|
182
|
+
* @param {{ cek: string, bytes: Uint8Array<ArrayBuffer> }} o
|
|
146
183
|
* @returns {Promise<{ iv: Uint8Array, ct: Uint8Array }>}
|
|
147
184
|
*/
|
|
148
185
|
export async function encryptBytesWithCek ({ cek, bytes }) {
|
|
@@ -153,14 +190,22 @@ export async function encryptBytesWithCek ({ cek, bytes }) {
|
|
|
153
190
|
return { iv, ct }
|
|
154
191
|
}
|
|
155
192
|
|
|
156
|
-
/**
|
|
193
|
+
/**
|
|
194
|
+
* El inverso de `encryptBytesWithCek`. Lanza si los bytes no son de esa clave o se tocaron.
|
|
195
|
+
* @param {{ cek: string, iv: Uint8Array<ArrayBuffer>, ct: Uint8Array<ArrayBuffer> }} args
|
|
196
|
+
* @returns {Promise<Uint8Array>}
|
|
197
|
+
*/
|
|
157
198
|
export async function decryptBytesWithCek ({ cek, iv, ct }) {
|
|
158
199
|
if (!(iv instanceof Uint8Array) || !(ct instanceof Uint8Array)) throw new Error('decryptBytesWithCek: iv and ct must be Uint8Array')
|
|
159
200
|
const k = await subtle.importKey('raw', fromB64(cek), { name: 'AES-GCM' }, false, ['decrypt'])
|
|
160
201
|
return new Uint8Array(await subtle.decrypt({ name: 'AES-GCM', iv }, k, ct))
|
|
161
202
|
}
|
|
162
203
|
|
|
163
|
-
/**
|
|
204
|
+
/**
|
|
205
|
+
* Cierra con la LLAVE DE LA CUENTA (generación `gen`): el sobre lleva la marca.
|
|
206
|
+
* @param {{ cek: string, gen: number, plaintext: string }} args
|
|
207
|
+
* @returns {Promise<CekEnvelope>}
|
|
208
|
+
*/
|
|
164
209
|
export async function sealAccount ({ cek, gen, plaintext }) {
|
|
165
210
|
if (!Number.isInteger(gen) || gen < 1) throw new Error('sealAccount: the account key generation starts at 1')
|
|
166
211
|
return { t: CEK_ENVELOPE, ...(await encryptWithCek({ cek, gen, plaintext })) }
|
|
@@ -172,6 +217,8 @@ export async function sealAccount ({ cek, gen, plaintext }) {
|
|
|
172
217
|
* Existe para quien administra: tiene la clave a mano (la sacó de donde la guarde) y no
|
|
173
218
|
* necesita el llavero ni ser miembro. El camino normal —el del aparato que solo tiene su
|
|
174
219
|
* propia llave— es `decryptWithKeyring`.
|
|
220
|
+
* @param {{ cek: string, envelope: { iv: string, ct: string } }} args
|
|
221
|
+
* @returns {Promise<string>}
|
|
175
222
|
*/
|
|
176
223
|
export async function decryptWithCek ({ cek, envelope }) {
|
|
177
224
|
const k = await subtle.importKey('raw', fromB64(cek), { name: 'AES-GCM' }, false, ['decrypt'])
|
|
@@ -183,6 +230,8 @@ export async function decryptWithCek ({ cek, envelope }) {
|
|
|
183
230
|
* Descifra un sobre. Hay que darle el llavero porque el contenido viejo está cifrado con
|
|
184
231
|
* generaciones anteriores: por eso las CEK antiguas se conservan (32 bytes cada una) en vez
|
|
185
232
|
* de re-cifrarlo todo de golpe al rotar.
|
|
233
|
+
* @param {{ envelope: any, keyring?: KeyringGeneration[] | null, myPub: string, myEncPrivateKey: any }} args
|
|
234
|
+
* @returns {Promise<string>}
|
|
186
235
|
*/
|
|
187
236
|
export async function decryptWithKeyring ({ envelope, keyring, myPub, myEncPrivateKey }) {
|
|
188
237
|
const g = (keyring || []).find((x) => x.gen === envelope?.gen)
|
|
@@ -204,6 +253,7 @@ export async function decryptWithKeyring ({ envelope, keyring, myPub, myEncPriva
|
|
|
204
253
|
export const LEGACY_UNMARKED_UNTIL = Date.parse('2027-06-30T00:00:00Z')
|
|
205
254
|
|
|
206
255
|
/** ¿Tiene la forma EXACTA de un sobre de la cuenta anterior a la marca? */
|
|
256
|
+
/** @param {any} v @returns {v is CekEnvelope} */
|
|
207
257
|
export const isLegacyCekEnvelope = (v) => !!v && typeof v === 'object' && !Array.isArray(v) &&
|
|
208
258
|
Object.keys(v).length === 3 && Number.isInteger(v.gen) && v.gen >= 1 &&
|
|
209
259
|
typeof v.iv === 'string' && typeof v.ct === 'string'
|
|
@@ -235,10 +285,12 @@ export async function resealStale (value, { gen, reseal, now = Date.now() }) {
|
|
|
235
285
|
if (!Number.isInteger(gen)) throw new Error('resealStale: the current generation is required')
|
|
236
286
|
const migrar = now < LEGACY_UNMARKED_UNTIL
|
|
237
287
|
let changed = 0; let skipped = 0
|
|
288
|
+
/** @param {any} nuevo @returns {CekEnvelope} */
|
|
238
289
|
const comprobar = (nuevo) => {
|
|
239
290
|
if (!isCekEnvelope(nuevo) || nuevo.gen !== gen) throw new Error(`resealStale: reseal did not return a marked envelope of generation ${gen}`)
|
|
240
291
|
return nuevo
|
|
241
292
|
}
|
|
293
|
+
/** @param {any} v @returns {Promise<any>} */
|
|
242
294
|
const walk = async (v) => {
|
|
243
295
|
if (isCekEnvelope(v)) {
|
|
244
296
|
if (v.gen === gen) return v
|
|
@@ -253,11 +305,13 @@ export async function resealStale (value, { gen, reseal, now = Date.now() }) {
|
|
|
253
305
|
return comprobar(nuevo)
|
|
254
306
|
}
|
|
255
307
|
if (Array.isArray(v)) {
|
|
308
|
+
/** @type {any[]} */
|
|
256
309
|
const out = []
|
|
257
310
|
for (const x of v) out.push(await walk(x))
|
|
258
311
|
return out
|
|
259
312
|
}
|
|
260
313
|
if (v && typeof v === 'object') {
|
|
314
|
+
/** @type {Record<string, any>} */
|
|
261
315
|
const out = {}
|
|
262
316
|
for (const [k, x] of Object.entries(v)) out[k] = await walk(x)
|
|
263
317
|
return out
|