@dotrino/identity 0.141.0 → 0.142.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/identity",
3
- "version": "0.141.0",
3
+ "version": "0.142.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",
@@ -94,9 +94,10 @@
94
94
  },
95
95
  "devDependencies": {
96
96
  "@dotrino/opaque": "0.1.0",
97
+ "@dotrino/proxy-client": "0.52.0",
98
+ "@types/node": "^22.0.0",
97
99
  "fake-indexeddb": "^6.2.5",
98
- "typescript": "5.9.3",
99
- "@types/node": "^22.0.0"
100
+ "typescript": "5.9.3"
100
101
  },
101
102
  "peerDependencies": {
102
103
  "@dotrino/proxy-client": ">=0.20.0"
package/src/index.d.ts CHANGED
@@ -197,6 +197,10 @@ export class Identity {
197
197
  * sin emparejar, `not-paired`; si la bóveda no contesta, `vault-no-reply`.
198
198
  */
199
199
  vaultStore (method: string, args?: any): Promise<any>
200
+ /** El TURN y el buzón del cajón `transport` de la bóveda; el cajón no sale del iframe. */
201
+ vaultTransport (op?: 'status'): Promise<{ turn: boolean, mailbox: boolean }>
202
+ vaultTransport (op: 'ice'): Promise<{ iceServers: Array<{ urls: string | string[], username?: string, credential?: string }>, expires: number }>
203
+ vaultTransport (op: 'mailbox'): Promise<{ put: string, get: string, key: string, expires: number }>
200
204
  listVaultDevices (): Promise<{ devices: any[]; revoked: any[] }>
201
205
  /**
202
206
  * Pedidos de aprobación de la cuenta activa (o de otra, con `profile`).
package/src/index.js CHANGED
@@ -615,6 +615,21 @@ export class Identity {
615
615
  return this._call('vaultStore', { method, args, wake }, 20000)
616
616
  }
617
617
 
618
+ /**
619
+ * EL TRANSPORTE DEL PERFIL: el TURN y el buzón del cajón `transport` de tu bóveda
620
+ * (`dotrino-proxy-client/docs/transporte-del-perfil.md`). El cajón se abre dentro del
621
+ * iframe y aquí solo sale lo corto:
622
+ * · `'status'` → `{ turn, mailbox }`, qué hay configurado;
623
+ * · `'ice'` → `{ iceServers, expires }`, credenciales TURN de 10 min;
624
+ * · `'mailbox'` → `{ put, get, key, expires }`, dos URLs firmadas para un objeto nuevo.
625
+ * Errores con `code`: `not-paired`, `no-transport-permission`, `no-turn`, `no-mailbox`,
626
+ * `transport-incomplete`.
627
+ * @type {IdentityApi['vaultTransport']}
628
+ */
629
+ async vaultTransport (op = 'status') {
630
+ return this._call('vaultTransport', { op }, 30000)
631
+ }
632
+
618
633
  /**
619
634
  * CONSOLA REMOTA: administra el perfil desde este dispositivo, contra la bóveda
620
635
  * (`dotrino-vault/docs/consola-remota.md`). `op`: `pending` · `pair` · `approve` ·
package/types/core.d.ts CHANGED
@@ -877,6 +877,29 @@ export function createIdentityCore({ kv: hostKv, peers, makeSync, keyStore: host
877
877
  * @param {HandlerParams} params lo que llega por `postMessage` o la API: sin comprobar todavía
878
878
  */
879
879
  vaultStore({ method, args, wake }: HandlerParams): Promise<any>;
880
+ /**
881
+ * EL TRANSPORTE DEL PERFIL (`dotrino-proxy-client/docs/transporte-del-perfil.md`): el TURN
882
+ * y el buzón que la cuenta tiene en su cajón `transport`.
883
+ *
884
+ * El cajón se abre AQUÍ, con la llave de cifrado de este aparato, y a la app solo le sale
885
+ * lo corto: credenciales TURN de 10 min (`ice`), dos URLs firmadas para un objeto nuevo del
886
+ * buzón (`mailbox`) o qué hay configurado (`status`). Las llaves del cajón no salen del iframe.
887
+ *
888
+ * Sin el permiso `transport` en el acta la bóveda no sirve el cajón (`no-transport-permission`).
889
+ * @param {HandlerParams} params
890
+ */
891
+ vaultTransport({ op }?: HandlerParams): Promise<{
892
+ turn: boolean;
893
+ mailbox: boolean;
894
+ } | {
895
+ iceServers: import("@dotrino/proxy-client").ProfileIceServer[];
896
+ expires: number;
897
+ } | {
898
+ put: string;
899
+ get: string;
900
+ key: string;
901
+ expires: number;
902
+ }>;
880
903
  /**
881
904
  * CONSOLA REMOTA: administrar el perfil desde este dispositivo (ver
882
905
  * `dotrino-vault/docs/consola-remota.md`). Requiere que el cert de este aparato
package/types/remote.d.ts CHANGED
@@ -153,6 +153,24 @@ export function requestStore({ master, proxy, device, cert, acta, method, args,
153
153
  enc?: any;
154
154
  wake?: boolean;
155
155
  }): Promise<any>;
156
+ /**
157
+ * UN CAJÓN QUE ESTE APARATO PUEDE LEER, tal como lo sirve la bóveda: hoy el de `transport`,
158
+ * que se reparte por el permiso del mismo nombre (`dotrino-proxy-client/docs/transporte-del-perfil.md`).
159
+ *
160
+ * Va por `vault.secrets`, el mismo mostrador que usan los servicios, con `publicOnly`: las
161
+ * variables del transporte se guardan públicas para que pedirlas no haga sonar el teléfono.
162
+ * La respuesta se comprueba con el mismo código que en un servicio (`verifyResponder` de
163
+ * `@dotrino/vault/drawer`). Devuelve el bundle SIN abrir: lo abre quien tiene la llave.
164
+ * @param {PairingContext & { ns: string, timeoutMs?: number }} args
165
+ * @returns {Promise<{ sealed: any, acta: any }>}
166
+ */
167
+ export function requestDrawer({ master, proxy, device, cert, acta, ns, onRevoked, timeoutMs }?: PairingContext & {
168
+ ns: string;
169
+ timeoutMs?: number;
170
+ }): Promise<{
171
+ sealed: any;
172
+ acta: any;
173
+ }>;
156
174
  /**
157
175
  * Lista (solo lectura) los dispositivos enrolados en tu vault.
158
176
  * @param {PairingContext & { sinceSeq?: number }} args
package/vault/core.js CHANGED
@@ -25,7 +25,7 @@ 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
27
  import { bufToBase64, base64ToBuf, encryptFor, decryptFrom } from './e2e.js'
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
+ 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, requestDrawer as remoteDrawer, registerLocalVault } from './remote.js'
29
29
 
30
30
  /**
31
31
  * Almacén clave → texto, síncrono (localStorage, o lo que lo imite en Node y en la app).
@@ -881,6 +881,50 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
881
881
  * DEGRADAR: avisar a la app de que la bóveda nos está rechazando, y que sea el usuario
882
882
  * quien decida. El borrado real llega por `vault.revoked` firmado (ver `wipeVaultLink`).
883
883
  */
884
+ /**
885
+ * Los valores del cajón `transport`, abiertos. Se guardan en memoria unos minutos (nunca en
886
+ * disco): cada credencial TURN no puede costar un viaje a la bóveda.
887
+ */
888
+ let transportCache = /** @type {{ vars: Record<string, string>, at: number, master: string } | null} */ (null)
889
+ const TRANSPORT_CACHE_MS = 5 * 60 * 1000
890
+ async function transportVars () {
891
+ const v = loadVaultCert(); const device = loadVaultDevice()
892
+ if (!v?.cert || !device) throw Object.assign(new Error('this device is not paired with a vault'), { code: 'not-paired' })
893
+ // Por cuenta: cambiar de cuenta no puede devolver el cajón de la anterior.
894
+ if (transportCache && transportCache.master === v.master && Date.now() - transportCache.at < TRANSPORT_CACHE_MS) return transportCache.vars
895
+ maybeRenewVaultCert()
896
+ const ask = () => {
897
+ const now = loadVaultCert()
898
+ return remoteDrawer({ acta: loadActa(), master: v.master, proxy: v.proxy, device, cert: now?.cert || v.cert, ns: 'transport', onRevoked: wipeVaultLink })
899
+ }
900
+ let got
901
+ try {
902
+ try { got = await ask() } catch (e) {
903
+ // EL PAPEL SE QUEDÓ ATRÁS DEL ACTA: el permiso se dio después de emparejar y el papel no
904
+ // lleva el scope del cajón. Se pone al día el acta (la lista la trae), se pide papel
905
+ // nuevo UNA vez y se vuelve a preguntar. Lo mismo que hace un servicio (`fetchSecrets`).
906
+ if (!/unauthorized: scope/.test(String(/** @type {any} */ (e)?.message || ''))) throw e
907
+ await handlers.listVaultDevices().catch(() => null)
908
+ if (!(await renovarCert().catch(() => null))) throw e
909
+ got = await ask()
910
+ }
911
+ } catch (e) {
912
+ const err = /** @type {any} */ (e)
913
+ if (/unauthorized/.test(String(err?.message || ''))) {
914
+ throw Object.assign(new Error(`this device does not have the transport permission: give it in the vault (${String(err.message)})`), { code: 'no-transport-permission' })
915
+ }
916
+ return handleVaultError(e)
917
+ }
918
+ const { openDrawer } = await import('@dotrino/vault/drawer')
919
+ const acta = loadActa()
920
+ const vars = await openDrawer(got.sealed, {
921
+ openWrap: (/** @type {any} */ wrap) => Content.openWrap({ wrap, myEncPrivateKey: encKeypair.privateKey }),
922
+ acta: got.acta, masterPubkey: v.master, sealers: acta ? Acta.sealersOf(acta) : null, ns: 'transport'
923
+ })
924
+ transportCache = { vars, at: Date.now(), master: v.master }
925
+ return vars
926
+ }
927
+
884
928
  /** @param {any} e @returns {never} */
885
929
  const handleVaultError = (e) => {
886
930
  if (e && /\brevoked\b/.test(e.message || '')) emitVault({ phase: 'rejected', reason: e.message })
@@ -3685,6 +3729,30 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3685
3729
  } catch (e) { return handleVaultError(e) }
3686
3730
  },
3687
3731
 
3732
+ /**
3733
+ * EL TRANSPORTE DEL PERFIL (`dotrino-proxy-client/docs/transporte-del-perfil.md`): el TURN
3734
+ * y el buzón que la cuenta tiene en su cajón `transport`.
3735
+ *
3736
+ * El cajón se abre AQUÍ, con la llave de cifrado de este aparato, y a la app solo le sale
3737
+ * lo corto: credenciales TURN de 10 min (`ice`), dos URLs firmadas para un objeto nuevo del
3738
+ * buzón (`mailbox`) o qué hay configurado (`status`). Las llaves del cajón no salen del iframe.
3739
+ *
3740
+ * Sin el permiso `transport` en el acta la bóveda no sirve el cajón (`no-transport-permission`).
3741
+ * @param {HandlerParams} params
3742
+ */
3743
+ async vaultTransport ({ op = 'status' } = {}) {
3744
+ if (!['status', 'ice', 'mailbox'].includes(op)) throw Object.assign(new Error(`vaultTransport: unknown op "${op}" (status, ice or mailbox)`), { code: 'bad-op' })
3745
+ const PT = await import('@dotrino/proxy-client')
3746
+ const vars = await transportVars()
3747
+ if (op === 'status') return PT.transportStatus(vars)
3748
+ if (op === 'ice') {
3749
+ const device = loadVaultDevice()
3750
+ const who = device ? await pubkeyIdOf(device.publickey).catch(() => 'device') : 'device'
3751
+ return PT.iceServersFrom(vars, { who })
3752
+ }
3753
+ return PT.mailboxUrlsFrom(vars)
3754
+ },
3755
+
3688
3756
  /**
3689
3757
  * CONSOLA REMOTA: administrar el perfil desde este dispositivo (ver
3690
3758
  * `dotrino-vault/docs/consola-remota.md`). Requiere que el cert de este aparato
package/vault/facade.js CHANGED
@@ -263,6 +263,7 @@ export class IdentityFacade {
263
263
  vaultSign (payload) { return this._h('vaultSign', { payload }) }
264
264
  /** @param {string} method @param {any} args @param {{ wake?: boolean }} [opts] */
265
265
  vaultStore (method, args, { wake = true } = {}) { return this._h('vaultStore', { method, args, wake }) }
266
+ vaultTransport (op = 'status') { return this._h('vaultTransport', { op }) }
266
267
  /** @param {any} opts */
267
268
  listVaultDevices (opts) { return this._h('listVaultDevices', opts || {}) }
268
269
  getVaultCert () { return this._h('getVaultCert') }
@@ -45,6 +45,16 @@ declare module '@dotrino/vault/password-logins' {
45
45
  export function accountFingerprint (identity: { profileActa (): Promise<any> }): Promise<string>
46
46
  export function vaultChannel (code: string): string
47
47
  }
48
+ declare module '@dotrino/vault/sealed' {
49
+ export function makeEphemeralKey (): Promise<{ ek: string, privateKey: CryptoKey }>
50
+ export function openSealed (args: { privateKey: CryptoKey, enc: any }): Promise<any>
51
+ }
52
+ declare module '@dotrino/vault/drawer' {
53
+ /** Comprueba la respuesta de la bóveda contra el acta (la misma que en un servicio). */
54
+ export function verifyResponder (args: { body: any, seal: any, acta: any, masterPubkey: string, knownSeq?: number | null, knownSealers?: string[] | null, askSealerChain?: (() => Promise<any>) | null }): Promise<void>
55
+ /** Abre un cajón servido por la bóveda con la llave de cifrado de quien llama. */
56
+ export function openDrawer (sealed: any, opts: { openWrap: (wrap: any) => Promise<any>, acta?: any, masterPubkey?: string | null, sealers?: string[] | null, ns?: string | null }): Promise<Record<string, string>>
57
+ }
48
58
  declare module '@dotrino/vault/backup' {
49
59
  export function sealBackup (payload: any, password: string): Promise<any>
50
60
  export function openBackup (file: any, password: string): Promise<any>
package/vault/index.html CHANGED
@@ -158,6 +158,8 @@
158
158
  "@dotrino/proxy-client/sealing": "./vendor/proxy-client/sealing.js",
159
159
  "@dotrino/vault": "./vendor/vault/index.js",
160
160
  "@dotrino/vault/browser": "./vendor/vault/browser.js",
161
+ "@dotrino/vault/sealed": "./vendor/vault/sealed.js",
162
+ "@dotrino/vault/drawer": "./vendor/vault/drawer.js",
161
163
  "@dotrino/compat": "./vendor/compat/index.js",
162
164
  "@dotrino/compat/ranges": "./vendor/compat/ranges.js",
163
165
  "@dotrino/roadmap": "./vendor/roadmap/index.js",
package/vault/remote.js CHANGED
@@ -14,7 +14,7 @@
14
14
  * `@dotrino/proxy-client` (importado perezosamente; solo se carga al emparejar).
15
15
  */
16
16
  import { makeDeviceKey, signWithDevice, verifyDeviceSig, makePairingCode, commitCode, keyLabel } from './capabilities.js'
17
- import { checkVaultReply, accountMismatch } from './acta.js'
17
+ import { checkVaultReply, accountMismatch, sealersOf } from './acta.js'
18
18
  import { cleanMachine, browserMachine } from './machine.js'
19
19
  import { sendToVault, acceptReply } from './vaultSeal.js'
20
20
 
@@ -570,6 +570,40 @@ export async function requestStore ({ master, proxy, device, cert, acta = null,
570
570
  return res.result
571
571
  }
572
572
 
573
+ /** Lo que tarda en dejar de valer una respuesta de cajón (la misma ventana que los servicios). */
574
+ const DRAWER_FRESH_MS = 5 * 60 * 1000
575
+
576
+ /**
577
+ * UN CAJÓN QUE ESTE APARATO PUEDE LEER, tal como lo sirve la bóveda: hoy el de `transport`,
578
+ * que se reparte por el permiso del mismo nombre (`dotrino-proxy-client/docs/transporte-del-perfil.md`).
579
+ *
580
+ * Va por `vault.secrets`, el mismo mostrador que usan los servicios, con `publicOnly`: las
581
+ * variables del transporte se guardan públicas para que pedirlas no haga sonar el teléfono.
582
+ * La respuesta se comprueba con el mismo código que en un servicio (`verifyResponder` de
583
+ * `@dotrino/vault/drawer`). Devuelve el bundle SIN abrir: lo abre quien tiene la llave.
584
+ * @param {PairingContext & { ns: string, timeoutMs?: number }} args
585
+ * @returns {Promise<{ sealed: any, acta: any }>}
586
+ */
587
+ export async function requestDrawer ({ master, proxy, device, cert, acta = null, ns, onRevoked, timeoutMs = 20000 } = /** @type {any} */ ({})) {
588
+ const { makeEphemeralKey, openSealed } = await import('@dotrino/vault/sealed')
589
+ const { verifyResponder } = await import('@dotrino/vault/drawer')
590
+ const eph = await makeEphemeralKey()
591
+ const res = await vaultRpc({ master, proxy, device, cert, acta, onRevoked, timeoutMs, sendType: 'vault.secrets', okType: 'vault.secrets.result', data: { op: 'secrets', ns, ek: eph.ek, publicOnly: true } })
592
+ const body = res?.body
593
+ if (!body || body.op !== 'secrets.result' || body.ns !== ns) throw Object.assign(new Error('malformed drawer reply'), { code: 'drawer-malformed' })
594
+ if (typeof body.ts !== 'number' || Math.abs(Date.now() - body.ts) > DRAWER_FRESH_MS) throw Object.assign(new Error('stale drawer reply'), { code: 'drawer-stale' })
595
+ // Se abre ANTES de comprobar la firma: el sobre de fuera va a la efímera recién hecha, y
596
+ // dentro viaja el acta con la que SÍ se comprueba. Nada se usa antes de verificar.
597
+ const payload = await openSealed({ privateKey: eph.privateKey, enc: body.enc })
598
+ await verifyResponder({
599
+ body, seal: res.seal, acta: payload?.acta, masterPubkey: master,
600
+ knownSeq: typeof acta?.seq === 'number' ? acta.seq : null,
601
+ knownSealers: acta ? sealersOf(acta) : null
602
+ })
603
+ if (!payload?.sealed) throw Object.assign(new Error('the vault served the drawer without envelopes (it is too old)'), { code: 'drawer-unsealed' })
604
+ return { sealed: payload.sealed, acta: payload.acta }
605
+ }
606
+
573
607
  /**
574
608
  * Lista (solo lectura) los dispositivos enrolados en tu vault.
575
609
  * @param {PairingContext & { sinceSeq?: number }} args
@@ -1,4 +1,4 @@
1
- Copia vendorizada de @dotrino/proxy-client@0.51.0 (dotrino-proxy-client/src/{binpack,ble/manager,ble/wire,canonical,client,encpub,errors,index,parts,sealing,signature,stats-log,stats,webrtc}.js).
1
+ Copia vendorizada de @dotrino/proxy-client@0.52.0 (dotrino-proxy-client/src/{binpack,ble/manager,ble/wire,canonical,client,encpub,errors,index,parts,profileTransport,sealing,signature,stats-log,stats,webrtc}.js).
2
2
  NO se edita a mano: la escribe `node vendor.mjs` y la vigila test/vendor-up-to-date.test.mjs.
3
3
  sealing.js resuelve @dotrino/identity/content de forma PEREZOSA (= ../../content.js
4
4
  por el import map): solo se carga si de verdad se sella algo.
@@ -15,6 +15,7 @@ export { PART_TAG, DIRECT_PART_CHARS, PROXY_PART_CHARS, QUEUE_MAX_CHARS, RELAY_M
15
15
  export { pack, unpack, hasBinary, encodeFrame, decodeFrame } from './binpack.js'
16
16
  export { logStats, formatStats, netReport, splitPeers } from './stats-log.js'
17
17
  export { encodeContact, decodeContact, KIND_PAIR, KIND_CONTACT } from './ble/wire.js'
18
+ export { TRANSPORT_DRAWER, TURN_TTL_S, transportStatus, turnProvider, iceServersFrom, mailboxConfig, mailboxUrlsFrom } from './profileTransport.js'
18
19
 
19
20
  import { WebSocketProxyClient } from './client.js'
20
21
 
@@ -0,0 +1,191 @@
1
+ /**
2
+ * EL TRANSPORTE DEL PERFIL: lo que sale del cajón `transport` de la bóveda
3
+ * (`docs/transporte-del-perfil.md`).
4
+ *
5
+ * Funciones puras sobre los valores del cajón. No piden nada a la bóveda ni guardan nada:
6
+ * quien tiene el cajón abierto (el iframe de identidad, un agente) las llama y entrega a la
7
+ * app solo lo corto y caducable — credenciales TURN o URLs firmadas —, nunca las llaves.
8
+ *
9
+ * Mismo contrato en Kotlin y Swift (`dotrino-native`).
10
+ */
11
+
12
+ /** Nombre del cajón y del permiso del acta. */
13
+ export const TRANSPORT_DRAWER = 'transport'
14
+
15
+ /** Vida de una credencial TURN, en segundos. */
16
+ export const TURN_TTL_S = 600
17
+
18
+ /** Vida de una URL del buzón, si el cajón no dice otra cosa. */
19
+ export const MAILBOX_DEFAULT_TTL_H = 24
20
+
21
+ const CF_API = 'https://rtc.live.cloudflare.com/v1/turn/keys'
22
+
23
+ /**
24
+ * Error con `code`: el código es el contrato, el mensaje no.
25
+ * @param {string} message
26
+ * @param {string} code
27
+ */
28
+ function fail (message, code) {
29
+ return Object.assign(new Error(message), { code })
30
+ }
31
+
32
+ /** @param {Record<string, string> | null | undefined} vars @param {string} k */
33
+ const val = (vars, k) => (vars && typeof vars[k] === 'string' ? vars[k].trim() : '')
34
+
35
+ /**
36
+ * Qué hay configurado, sin valores.
37
+ * @param {Record<string, string> | null | undefined} vars
38
+ * @returns {{ turn: boolean, mailbox: boolean }}
39
+ */
40
+ export function transportStatus (vars) {
41
+ return { turn: !!turnProvider(vars), mailbox: !!mailboxConfig(vars) }
42
+ }
43
+
44
+ /**
45
+ * El proveedor TURN del cajón, o `null` si no hay TURN. Un `TURN_PROVIDER` desconocido o
46
+ * con variables a medias es un error: no se adivina.
47
+ * @param {Record<string, string> | null | undefined} vars
48
+ * @returns {'cloudflare' | 'coturn' | null}
49
+ */
50
+ export function turnProvider (vars) {
51
+ const p = val(vars, 'TURN_PROVIDER')
52
+ if (!p) return null
53
+ if (p === 'cloudflare') {
54
+ if (!val(vars, 'TURN_KEY_ID') || !val(vars, 'TURN_KEY_API_TOKEN')) throw fail('transport: TURN_PROVIDER=cloudflare needs TURN_KEY_ID and TURN_KEY_API_TOKEN', 'transport-incomplete')
55
+ return 'cloudflare'
56
+ }
57
+ if (p === 'coturn') {
58
+ if (!val(vars, 'TURN_URLS') || !val(vars, 'TURN_SECRET')) throw fail('transport: TURN_PROVIDER=coturn needs TURN_URLS and TURN_SECRET', 'transport-incomplete')
59
+ return 'coturn'
60
+ }
61
+ throw fail(`transport: unknown TURN_PROVIDER "${p}" (cloudflare or coturn)`, 'transport-unknown-provider')
62
+ }
63
+
64
+ /** @param {ArrayBuffer} buf */
65
+ const b64 = (buf) => {
66
+ const bytes = new Uint8Array(buf)
67
+ let s = ''
68
+ for (const b of bytes) s += String.fromCharCode(b)
69
+ return btoa(s)
70
+ }
71
+ /** @param {ArrayBuffer} buf */
72
+ const hex = (buf) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('')
73
+ const enc = new TextEncoder()
74
+
75
+ /**
76
+ * @param {'SHA-1' | 'SHA-256'} hash
77
+ * @param {BufferSource} key
78
+ * @param {string} data
79
+ */
80
+ async function hmac (hash, key, data) {
81
+ const k = await crypto.subtle.importKey('raw', key, { name: 'HMAC', hash }, false, ['sign'])
82
+ return crypto.subtle.sign('HMAC', k, enc.encode(data))
83
+ }
84
+
85
+ /**
86
+ * Credenciales TURN cortas sacadas del cajón.
87
+ *
88
+ * - `cloudflare`: la API `generate-ice-servers` (admite CORS, así que vale desde el navegador).
89
+ * - `coturn` con `use-auth-secret`: `username = <caduca>:<quien>`,
90
+ * `credential = base64(HMAC-SHA1(TURN_SECRET, username))`.
91
+ *
92
+ * @param {Record<string, string>} vars los valores del cajón, ya abiertos
93
+ * @param {{ who?: string, ttl?: number, now?: number, fetchImpl?: typeof fetch }} [opts]
94
+ * @returns {Promise<{ iceServers: Array<{ urls: string | string[], username?: string, credential?: string }>, expires: number }>}
95
+ */
96
+ export async function iceServersFrom (vars, { who = 'device', ttl = TURN_TTL_S, now = Date.now(), fetchImpl = globalThis.fetch } = {}) {
97
+ const provider = turnProvider(vars)
98
+ if (!provider) throw fail('transport: there is no TURN server in this profile', 'no-turn')
99
+ const expires = now + ttl * 1000
100
+ if (provider === 'coturn') {
101
+ const urls = val(vars, 'TURN_URLS').split(/[\s,]+/).filter(Boolean)
102
+ const username = `${Math.floor(expires / 1000)}:${String(who).replace(/[^A-Za-z0-9_-]/g, '').slice(0, 32) || 'device'}`
103
+ const credential = b64(await hmac('SHA-1', enc.encode(val(vars, 'TURN_SECRET')), username))
104
+ return { iceServers: [{ urls, username, credential }], expires }
105
+ }
106
+ if (typeof fetchImpl !== 'function') throw fail('transport: no fetch to ask Cloudflare for TURN credentials', 'no-fetch')
107
+ const res = await fetchImpl(`${CF_API}/${encodeURIComponent(val(vars, 'TURN_KEY_ID'))}/credentials/generate-ice-servers`, {
108
+ method: 'POST',
109
+ headers: { Authorization: `Bearer ${val(vars, 'TURN_KEY_API_TOKEN')}`, 'Content-Type': 'application/json' },
110
+ body: JSON.stringify({ ttl })
111
+ })
112
+ if (!res.ok) throw fail(`transport: Cloudflare answered ${res.status} when asked for TURN credentials`, 'turn-provider-error')
113
+ const body = await res.json()
114
+ const list = Array.isArray(body?.iceServers) ? body.iceServers : body?.iceServers ? [body.iceServers] : []
115
+ const iceServers = list
116
+ .filter((/** @type {any} */ s) => s && s.urls)
117
+ .map((/** @type {any} */ s) => ({ urls: s.urls, ...(s.username ? { username: s.username } : {}), ...(s.credential ? { credential: s.credential } : {}) }))
118
+ if (!iceServers.length) throw fail('transport: Cloudflare answered without ICE servers', 'turn-provider-error')
119
+ return { iceServers, expires }
120
+ }
121
+
122
+ /**
123
+ * La configuración del buzón, o `null` si no hay buzón. A medias es un error.
124
+ * @param {Record<string, string> | null | undefined} vars
125
+ */
126
+ export function mailboxConfig (vars) {
127
+ const bucket = val(vars, 'MAILBOX_BUCKET')
128
+ const keyId = val(vars, 'MAILBOX_ACCESS_KEY_ID')
129
+ const secret = val(vars, 'MAILBOX_SECRET_ACCESS_KEY')
130
+ if (!bucket && !keyId && !secret) return null
131
+ if (!bucket || !keyId || !secret) throw fail('transport: the mailbox needs MAILBOX_BUCKET, MAILBOX_ACCESS_KEY_ID and MAILBOX_SECRET_ACCESS_KEY', 'transport-incomplete')
132
+ const region = val(vars, 'MAILBOX_REGION') || 'us-east-1'
133
+ const endpoint = (val(vars, 'MAILBOX_ENDPOINT') || `https://s3.${region}.amazonaws.com`).replace(/\/+$/, '')
134
+ if (!/^https:\/\//.test(endpoint)) throw fail('transport: MAILBOX_ENDPOINT must be https', 'transport-incomplete')
135
+ const ttlRaw = val(vars, 'MAILBOX_TTL_HOURS')
136
+ const ttlH = ttlRaw ? Number(ttlRaw) : MAILBOX_DEFAULT_TTL_H
137
+ // SigV4 no firma más de 7 días.
138
+ if (!Number.isFinite(ttlH) || ttlH <= 0 || ttlH > 168) throw fail('transport: MAILBOX_TTL_HOURS must be between 1 and 168', 'transport-incomplete')
139
+ return { bucket, keyId, secret, region, endpoint, ttlH }
140
+ }
141
+
142
+ /** RFC 3986, como lo pide SigV4. @param {string} s */
143
+ const uriEncode = (s) => encodeURIComponent(s).replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase())
144
+
145
+ /**
146
+ * Una URL firmada (SigV4, `UNSIGNED-PAYLOAD`) en estilo de ruta: `<endpoint>/<bucket>/<key>`.
147
+ * @param {ReturnType<typeof mailboxConfig> & {}} cfg
148
+ * @param {'PUT' | 'GET'} method
149
+ * @param {string} key
150
+ * @param {number} now
151
+ */
152
+ async function presign (cfg, method, key, now) {
153
+ const d = new Date(now).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '')
154
+ const date = d.slice(0, 8)
155
+ const host = new URL(cfg.endpoint).host
156
+ const basePath = new URL(cfg.endpoint).pathname.replace(/\/+$/, '')
157
+ const path = `${basePath}/${uriEncode(cfg.bucket)}/${key.split('/').map(uriEncode).join('/')}`
158
+ const scope = `${date}/${cfg.region}/s3/aws4_request`
159
+ const q = {
160
+ 'X-Amz-Algorithm': 'AWS4-HMAC-SHA256',
161
+ 'X-Amz-Credential': `${cfg.keyId}/${scope}`,
162
+ 'X-Amz-Date': d,
163
+ 'X-Amz-Expires': String(Math.floor(cfg.ttlH * 3600)),
164
+ 'X-Amz-SignedHeaders': 'host'
165
+ }
166
+ const query = Object.keys(q).sort().map((k) => `${uriEncode(k)}=${uriEncode(q[/** @type {keyof typeof q} */ (k)])}`).join('&')
167
+ const canonical = [method, path, query, `host:${host}\n`, 'host', 'UNSIGNED-PAYLOAD'].join('\n')
168
+ const toSign = ['AWS4-HMAC-SHA256', d, scope, hex(await crypto.subtle.digest('SHA-256', enc.encode(canonical)))].join('\n')
169
+ let k = await hmac('SHA-256', enc.encode('AWS4' + cfg.secret), date)
170
+ k = await hmac('SHA-256', k, cfg.region)
171
+ k = await hmac('SHA-256', k, 's3')
172
+ k = await hmac('SHA-256', k, 'aws4_request')
173
+ const sig = hex(await hmac('SHA-256', k, toSign))
174
+ return `${new URL(cfg.endpoint).origin}${path}?${query}&X-Amz-Signature=${sig}`
175
+ }
176
+
177
+ /**
178
+ * Dos URLs firmadas para UN objeto nuevo del buzón: `put` para subirlo y `get` para que el
179
+ * destinatario lo baje. El nombre es aleatorio: no dice nada de quién ni de qué.
180
+ *
181
+ * @param {Record<string, string>} vars
182
+ * @param {{ now?: number, key?: string }} [opts]
183
+ * @returns {Promise<{ put: string, get: string, key: string, expires: number }>}
184
+ */
185
+ export async function mailboxUrlsFrom (vars, { now = Date.now(), key } = {}) {
186
+ const cfg = mailboxConfig(vars)
187
+ if (!cfg) throw fail('transport: there is no mailbox in this profile', 'no-mailbox')
188
+ const name = key || `dotrino/${hex(crypto.getRandomValues(new Uint8Array(16)).buffer)}`
189
+ const [put, get] = await Promise.all([presign(cfg, 'PUT', name, now), presign(cfg, 'GET', name, now)])
190
+ return { put, get, key: name, expires: now + cfg.ttlH * 3600 * 1000 }
191
+ }
@@ -22,16 +22,16 @@ export const MANIFESTS = Object.freeze({
22
22
  "env": {
23
23
  "repo": "imdotrino/dotrino-vault",
24
24
  "npm": "@dotrino/env",
25
- "current": "0.123.4",
25
+ "current": "0.123.8",
26
26
  "protocol": 1,
27
27
  "requires": {
28
- "vault": ">=0.118.0"
28
+ "vault": ">=0.123.8"
29
29
  }
30
30
  },
31
31
  "identity": {
32
32
  "repo": "imdotrino/dotrino-identity",
33
33
  "npm": "@dotrino/identity",
34
- "current": "0.140.2",
34
+ "current": "0.140.4",
35
35
  "protocol": 1,
36
36
  "requires": {
37
37
  "proxy-client": ">=0.20.0"
@@ -341,12 +341,12 @@ export const MANIFESTS = Object.freeze({
341
341
  "vault": {
342
342
  "repo": "imdotrino/dotrino-vault",
343
343
  "npm": "@dotrino/vault",
344
- "current": "0.123.4",
344
+ "current": "0.123.8",
345
345
  "protocol": 1,
346
346
  "requires": {
347
347
  "vaultd": ">=0.105.0",
348
348
  "proxy-client": ">=0.47.0",
349
- "identity": ">=0.136.0",
349
+ "identity": ">=0.139.0",
350
350
  "opaque": ">=0.1.0",
351
351
  "compat": ">=0.5.0",
352
352
  "roadmap": ">=0.4.26",
@@ -357,7 +357,7 @@ export const MANIFESTS = Object.freeze({
357
357
  "vaultd": {
358
358
  "repo": "imdotrino/dotrino-vault",
359
359
  "npm": "@dotrino/vaultd",
360
- "current": "0.199.6",
360
+ "current": "0.199.9",
361
361
  "protocol": 1,
362
362
  "requires": {
363
363
  "identity": ">=0.139.0",
@@ -410,12 +410,12 @@ export const MANIFESTS = Object.freeze({
410
410
  },
411
411
  "passmanager-extension": {
412
412
  "repo": "imdotrino/dotrino-passmanager",
413
- "current": "0.64.2",
413
+ "current": "0.64.4",
414
414
  "protocol": 1,
415
415
  "requires": {
416
- "identity": ">=0.138.0",
416
+ "identity": ">=0.140.4",
417
417
  "proxy-client": ">=0.47.0",
418
- "vault": ">=0.120.1",
418
+ "vault": ">=0.123.7",
419
419
  "proxy": "1.1.0+",
420
420
  "vaultd": ">=0.160.2"
421
421
  }
@@ -1,4 +1,4 @@
1
- Copia vendorizada de @dotrino/vault@0.123.7 (dotrino-vault/lib/src/{admin,b64,browser,core/approvals,core/backup,core/blocked,core/browserDisk,core/commKey,core/disk,core/exNotices,core/gate,core/libVersion,core/logAnchor,core/machines,core/memberGroups,core/notices,core/notifiable,core/passwords,core/sealKey,core/sealer,core/sealers,core/secretsStore,core/sha256,core/siblingBackup,core/store,core/subacta,core/threadStore,core/transport,core/vault,enroll,index,invite,loginClient,passwordLogins,procContext,protocol,revocation,sealed}.js).
1
+ Copia vendorizada de @dotrino/vault@0.124.0 (dotrino-vault/lib/src/{admin,b64,browser,core/approvals,core/backup,core/blocked,core/browserDisk,core/commKey,core/disk,core/exNotices,core/gate,core/libVersion,core/logAnchor,core/machines,core/memberGroups,core/notices,core/notifiable,core/passwords,core/sealKey,core/sealer,core/sealers,core/secretsStore,core/sha256,core/siblingBackup,core/store,core/subacta,core/threadStore,core/transport,core/vault,drawer,enroll,index,invite,loginClient,passwordLogins,procContext,protocol,revocation,sealed}.js).
2
2
  NO se edita a mano: la escribe `node vendor.mjs` y la vigila test/vendor-up-to-date.test.mjs.
3
3
  browser.js es la bóveda de esta pestaña: el MISMO núcleo que el binario (core/), con
4
4
  el disco en IndexedDB. Importa @dotrino/{compat,roadmap,passmanager,store/core} y
@@ -5,4 +5,4 @@
5
5
  * si no coincide con la del paquete: una versión anunciada que no es la que corre es peor
6
6
  * que no anunciar ninguna.
7
7
  */
8
- export const LIB_VERSION = '0.123.7'
8
+ export const LIB_VERSION = '0.124.0'
@@ -3883,7 +3883,12 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
3883
3883
  // pero la salvaguarda era un accidente: bastaba que alguien le apuntara una `encPub`
3884
3884
  // para envolverle la llave a la llave que firma con la bóveda CERRADA. Se comprueba el
3885
3885
  // permiso, que es lo que de verdad se quería preguntar.
3886
- return (record.members || []).filter((m) => m.cn === ns && Acta.memberCanReadSecrets(record, m.pub, ns))
3886
+ //
3887
+ // Y QUIÉN LEE LO DICE SOLO EL ACTA (`memberCanReadSecrets`): ahí está el `cn` de cada
3888
+ // cajón y también el cajón `transport`, que se reparte a los aparatos con el permiso
3889
+ // `transport` y no a un servicio (dueño, 2026-12-06: «a los que tienen el permiso de
3890
+ // transporte se les hace sus sobres y listo»).
3891
+ return (record.members || []).filter((m) => Acta.memberCanReadSecrets(record, m.pub, ns))
3887
3892
  }
3888
3893
 
3889
3894
  /**
@@ -0,0 +1,280 @@
1
+ /**
2
+ * ABRIR UN CAJÓN que entregó la bóveda, en cualquier sitio: un servicio en Node
3
+ * (`service.js`) o el iframe de identidad (el cajón `transport` de un aparato con ese
4
+ * permiso). Sin Node: lo vendoriza `dotrino-identity/vendor.mjs`.
5
+ *
6
+ * Quien llama pone `openWrap(wrap) → cek` con SU llave de cifrado, que no sale de donde vive.
7
+ */
8
+
9
+ import { decryptWithCek } from '@dotrino/identity/content'
10
+ import { verifyActa, sealKeyAt, memberCan, actaHash, verifySealerChain } from '@dotrino/identity/acta'
11
+ import { verifyDeviceSig } from '@dotrino/identity/capabilities'
12
+
13
+ /**
14
+ * ¿SALIÓ ESTE SOBRE DE MI BÓVEDA? (§8.8 de `dotrino-vault/docs/secretos-sellados.md`)
15
+ *
16
+ * Envolver una llave solo necesita públicas, así que **cualquiera puede fabricar un sobre
17
+ * válido** para este servicio: abrirlo prueba que es para mí, no que lo escribió quien
18
+ * debía. Lo que lo prueba es la firma, hecha con la llave de sellado que el acta nombra
19
+ * para el `seq` con el que se firmó — y el acta la firma la maestra, que es la que este
20
+ * agente lleva pineada desde que se enroló.
21
+ *
22
+ * Una firma que NO cuadra es un error duro: es exactamente el caso que esto viene a
23
+ * cazar. Un sobre SIN firma se acepta y se avisa: los hay de antes de que esto existiera
24
+ * y negarse a arrancar por eso apagaría servicios que llevan meses bien.
25
+ */
26
+ export async function makeSealCheck (acta, masterPubkey, log = console.log, knownSealers = null) {
27
+ if (!acta) return () => {}
28
+ // El acta tiene que venir firmada por la maestra que este agente ya conoce. Si la
29
+ // selló otro (un traspaso que este agente no ha visto), no se puede establecer
30
+ // procedencia: se dice y se sigue, en vez de fingir que se comprobó.
31
+ // O una bóveda que el acta ya aceptada dejaba sellar (`docs/replicas.md` §11.5).
32
+ const known = acta.sealedBy === masterPubkey || (Array.isArray(knownSealers) && knownSealers.includes(acta.sealedBy))
33
+ const ok = known && (await verifyActa({ acta })).ok
34
+ if (!ok) {
35
+ log('[vault] ⚠ the record does not come from the master this agent knows: envelope provenance NOT checked')
36
+ return () => {}
37
+ }
38
+ let warned = false
39
+ return async (owner, key, gen, e, seal) => {
40
+ if (!seal?.sig) {
41
+ if (!warned) { warned = true; log('[vault] ⚠ some envelopes carry no signature (sealed before this vault could sign)') }
42
+ return
43
+ }
44
+ const pub = sealKeyAt(acta, seal.seq, seal.vault ?? null)
45
+ if (!pub) throw new Error(`${key}: the record has no sealing key for #${seal.seq} (the envelope claims a record that does not exist)`)
46
+ const good = await verifyDeviceSig({ publickey: pub, data: { owner, key, gen, iv: e.iv, ct: e.ct }, signature: seal.sig })
47
+ if (!good) throw new Error(`${key}: the envelope signature does not check out — it did not come from this vault`)
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Abre un bundle sellado (un cajón tal como lo entrega `vault.secrets`): saca la CEK de la envoltura dirigida a este aparato y
53
+ * descifra con ella las variables privadas. Las públicas vienen en claro.
54
+ *
55
+ * Un fallo al abrir es un ERROR DURO, nunca un salto a lo del scope ni un valor
56
+ * omitido: silenciarlo convertiría una rotación mal sellada en «el servicio sigue
57
+ * con el valor viejo y nadie se entera», que es el peor modo de fallo de todo esto.
58
+ */
59
+ /**
60
+ * @param {any} sealed el bundle (`{ entries, ns, dev, wraps }`)
61
+ * @param {{ openWrap: (wrap: any) => Promise<any>, acta?: any, masterPubkey?: string | null, sealers?: string[] | null, ns?: string | null }} opts
62
+ * @returns {Promise<Record<string, string>>}
63
+ */
64
+ export async function openDrawer (sealed, { openWrap: openWrapFn, acta = null, masterPubkey = null, sealers = null, ns = null }) {
65
+ if (typeof openWrapFn !== 'function') throw new Error('openDrawer: needs openWrap(wrap) → cek')
66
+
67
+ // UNA LLAVE POR GENERACIÓN, no una por cajón. Desde v5 cada escritura estrena
68
+ // generación —la bóveda no puede reutilizar una llave que no puede abrir—, así que dos
69
+ // variables del mismo cajón pueden venir de generaciones distintas. El bundle trae
70
+ // TODAS las envolturas de este aparato; se abren perezosamente, solo las que hagan
71
+ // falta. `sealed.ns`/`sealed.dev` (una sola, la vigente) siguen entrando: es el bundle
72
+ // de v4 y sirve para lo que ese vault selló.
73
+ const byGen = { ns: new Map(), dev: new Map() }
74
+ const añade = (which, info) => { if (info?.wrap) byGen[which].set(info.gen ?? 0, info.wrap) }
75
+ añade('ns', sealed.ns); añade('dev', sealed.dev)
76
+ for (const which of ['ns', 'dev']) for (const info of sealed.wraps?.[which] || []) añade(which, info)
77
+
78
+ const opened = { ns: new Map(), dev: new Map() }
79
+ const cekFrom = async (which, gen) => {
80
+ if (opened[which].has(gen)) return opened[which].get(gen)
81
+ // Un bundle de v4 no traía `gen` en la envoltura: si solo hay una, es esa.
82
+ const wrap = byGen[which].get(gen) ?? (byGen[which].size === 1 ? [...byGen[which].values()][0] : null)
83
+ if (!wrap) return null
84
+ const cek = await openWrapFn(wrap)
85
+ opened[which].set(gen, cek)
86
+ return cek
87
+ }
88
+
89
+ const checkSignature = await makeSealCheck(acta, masterPubkey, undefined, sealers)
90
+
91
+ /** @type {Record<string, string>} */
92
+ const out = {}
93
+ for (const [key, e] of Object.entries(sealed.entries || {})) {
94
+ // UNA PÚBLICA SE ABRE IGUAL QUE UNA PRIVADA (dueño, 2026-09-02). Aquí había un atajo
95
+ // —`if (e.pub) out[key] = e.v`— porque una pública se guardaba en claro. Ya no: `pub`
96
+ // solo dice si se despacha sin aprobación, y el sobre es el mismo. Dejar el atajo
97
+ // sería aceptar un valor en claro dentro de un paquete que se supone todo sellado, o
98
+ // sea la puerta para colar uno.
99
+ if (typeof e.v === 'string' && !e.e) {
100
+ // TAMPOCO SE ARREGLA ESPERANDO, igual que `no-wrapping`. El valor está guardado en
101
+ // claro en la bóveda, de antes de que todo viajara sellado, y solo vuelve a
102
+ // escribirlo quien puede abrirla. Reintentar no lo sella: solo vuelve a timbrar.
103
+ throw Object.assign(
104
+ new Error(`${key} arrived in the clear: since 2026-09-02 every variable travels sealed` +
105
+ ` — rewrite it in the vault (dotrino-vault unlock, then secret set ${ns || '<ns>'} ${key} …) or remove it`),
106
+ { code: 'plaintext-var' })
107
+ }
108
+ // `owner` dice de qué cajón salió, y `gen` con qué llave de ese cajón se abre.
109
+ const which = String(e.owner || '').startsWith('dev:') ? 'dev' : 'ns'
110
+ const gen = e.gen ?? e.e?.gen ?? 0
111
+ await checkSignature(e.owner, key, gen, e.e, e.seal)
112
+ const cek = await cekFrom(which, gen)
113
+ if (!cek) {
114
+ // NO ES UN TROPIEZO: ES UN ESTADO QUE HAY QUE ARREGLAR EN LA BÓVEDA.
115
+ //
116
+ // Un aparato que entra después de escrita una variable no tiene envoltura de ella, y
117
+ // NO PUEDE tenerla: envolver exige abrir la llave del cajón, y eso solo pasa cuando
118
+ // el dueño abre la bóveda. Reintentar no la crea. Lleva `code` porque el mensaje lo
119
+ // empareja otra capa y una frase no es un contrato (ver `dotrino-error-strings`).
120
+ throw Object.assign(
121
+ new Error(`no key to open ${key}: this device has no wrapping in its drawer — open the vault (dotrino-vault unlock) so it hands it the key`),
122
+ { code: 'no-wrapping' })
123
+ }
124
+ out[key] = await decryptWithCek({ cek, envelope: e.e })
125
+ }
126
+ return out
127
+ }
128
+
129
+ /**
130
+ * ¿QUIÉN CONTESTÓ, Y PUEDE? La misma regla que gobierna los sobres, aplicada al
131
+ * transporte: **el acta dice qué llave firma qué**.
132
+ *
133
+ * La maestra no entra aquí. Sus dos trabajos son sellar el acta y reenvolver los sobres
134
+ * de todos los aparatos; servir una petición no es ninguno de los dos, así que exigir su
135
+ * firma la obligaba a estar despierta todo el tiempo — y de paso hacía imposible que
136
+ * sirviera nadie más.
137
+ *
138
+ * Lo que se comprueba, en orden:
139
+ * 1. el acta que llega va firmada por la maestra que este agente lleva pineada desde
140
+ * que se enroló (o por la que aquella nombró al traspasar);
141
+ * 2. la firma del cuerpo cuadra con la llave de sellado que ESA acta nombra para el
142
+ * `seq` con el que se firmó.
143
+ *
144
+ * Sin el paso 1 el paso 2 no vale nada: un acta cualquiera nombraría la llave que
145
+ * quisiera.
146
+ *
147
+ * ¿QUIÉN PUEDE HABERME CONTESTADO ESTO? Hay dos respuestas legítimas y una condición.
148
+ *
149
+ * · **La bóveda.** Firma con la llave de sellado que el acta nombra para ese `seq`. Es
150
+ * el camino de siempre y no cambia.
151
+ * · **Un REPLICADOR** (`seal.by`). No tiene esa llave —no tiene maestra— así que firma
152
+ * con la suya de aparato, y lo que la autoriza es que el acta le reconozca `replica`.
153
+ * Reparte lo que la bóveda ya selló: los sobres de dentro se siguen comprobando contra
154
+ * la llave de sellado (`makeSealCheck`), así que un replicador no puede inventarse
155
+ * contenido, solo entregarlo.
156
+ *
157
+ * LA CONDICIÓN, y es la que cierra el agujero que `replicas.md` §6.1 llama «construir el
158
+ * ataque»: **un replicador solo le contesta a quien YA conoce la cuenta.** Un replicador
159
+ * atrasado presenta un acta donde un aparato revocado sigue siendo miembro; contra eso, a
160
+ * quien tiene `maxSeq` pineado lo protege el pin, pero a un aparato que llega nuevo no hay
161
+ * con qué compararlo. Así que sin pin no se le cree: que conteste la bóveda.
162
+ *
163
+ * El precio, dicho en voz alta: un aparato nuevo necesita la bóveda encendida una vez. El
164
+ * oráculo de frescura (§2.4.2 del acta) es lo que quitaría ese precio; mientras no exista,
165
+ * esto es el freno, y es un freno de verdad y no un aviso.
166
+ *
167
+ * @param {object} args
168
+ * @param {object} args.body lo que firmó quien contesta
169
+ * @param {{ sig?: string, seq?: number, vault?: string, by?: string }} [args.seal]
170
+ * @param {any} [args.acta] el acta que trae la respuesta: JSON de la red, se comprueba aquí
171
+ * @param {number|null} [args.knownSeq] El `seq` más alto que este agente ya vio de esta cuenta.
172
+ * `null`/ausente = no conoce la cuenta, y entonces un replicador no vale.
173
+ * @param {string} args.masterPubkey la maestra pineada al enrolarse
174
+ * @param {string[]|null} [args.knownSealers] quién podía sellar según la última acta aceptada
175
+ * @param {(() => Promise<any[]>)|null} [args.askSealerChain] pide la cadena de selladoras (`sealerChainAsker`)
176
+ */
177
+ export async function verifyResponder ({ body, seal, acta, masterPubkey, knownSeq = null, knownSealers = null, askSealerChain = null }) {
178
+ if (!seal?.sig) {
179
+ throw new Error('the reply carries no sealing signature: this vault is too old to serve (update it)')
180
+ }
181
+ if (!acta) throw new Error('the reply carries no record: cannot tell which key was allowed to sign it')
182
+ // LAS DOS SON MAESTRA (`docs/replicas.md` §11.5): el acta la puede haber sellado cualquier
183
+ // bóveda de la cuenta. Vale la maestra que este agente conoce, o una a la que el acta que YA
184
+ // aceptó le dejaba sellar (`knownSealers`, ver `recordActa`): es la cadena de selladoras,
185
+ // comprobada paso a paso.
186
+ //
187
+ // Y UNA QUE NO HA VISTO, SI LA CADENA LA LLEVA HASTA ELLA (2026-11-04). Un agente que se quedó
188
+ // en una acta de antes de que la cuenta tuviera otra bóveda —o que nunca guardó selladoras—
189
+ // rechazaba la primera acta que sellara la nueva, y como solo aprende de actas que acepta, se
190
+ // quedaba trabado para siempre (aws-glassnote: conocía la #57, la #77 la selló NubeLambda).
191
+ // Ahora pide la cadena de selladoras y la comprueba desde la maestra que conoce
192
+ // (`sealedByChain`): si encadena, la selladora vale; si no, se rechaza como antes.
193
+ const known = acta.sealedBy === masterPubkey || (Array.isArray(knownSealers) && knownSealers.includes(acta.sealedBy))
194
+ if (!known) {
195
+ if (!askSealerChain) {
196
+ throw Object.assign(new Error('the record was not sealed by a vault this agent knows: refusing the reply'), { code: 'unknown-sealer' })
197
+ }
198
+ let chain
199
+ try { chain = await askSealerChain() } catch (e) {
200
+ throw Object.assign(new Error('the record was sealed by a vault this agent does not know, and the sealer chain could not be fetched: ' + e.message), { code: 'unknown-sealer' })
201
+ }
202
+ const r = await sealedByChain({ chain, acta, masterPubkey })
203
+ if (!r.ok) {
204
+ throw Object.assign(new Error('the record was sealed by a vault this agent does not know, and the sealer chain does not vouch for it: ' + r.reason), { code: 'unknown-sealer' })
205
+ }
206
+ }
207
+ if (!(await verifyActa({ acta })).ok) throw new Error('the record does not verify')
208
+
209
+ // NUNCA HACIA ATRÁS. Vale para los dos caminos: un acta con `seq` menor del que ya
210
+ // vimos es un rollback, venga de donde venga.
211
+ if (typeof knownSeq === 'number' && typeof acta.seq === 'number' && acta.seq < knownSeq) {
212
+ throw Object.assign(
213
+ new Error(`the record went backwards (#${acta.seq} after #${knownSeq}): refusing the reply`),
214
+ { code: 'stale-record' })
215
+ }
216
+
217
+ if (seal.by) {
218
+ if (typeof knownSeq !== 'number') {
219
+ throw Object.assign(
220
+ new Error('a replica answered, and this device has never seen the account: ask the vault itself the first time'),
221
+ { code: 'replica-unknown-account' })
222
+ }
223
+ if (!memberCan(acta, seal.by, 'replica')) {
224
+ throw new Error('the reply comes from a device the record does not allow to serve as a replica')
225
+ }
226
+ if (!(await verifyDeviceSig({ publickey: seal.by, data: body, signature: seal.sig }))) {
227
+ throw new Error('the replica signature does not check out')
228
+ }
229
+ return
230
+ }
231
+
232
+ if (typeof seal.seq !== 'number') {
233
+ throw new Error('the reply carries no sealing signature: this vault is too old to serve (update it)')
234
+ }
235
+ // `seal.vault`: la firmó la llave de sellado de UNA bóveda, la que el acta nombra para ella.
236
+ const pub = sealKeyAt(acta, seal.seq, seal.vault ?? null)
237
+ if (!pub) throw new Error(`the record names no sealing key for #${seal.seq}`)
238
+ if (!(await verifyDeviceSig({ publickey: pub, data: body, signature: seal.sig }))) {
239
+ throw new Error('the reply signature does not check out against the key the record names')
240
+ }
241
+ }
242
+
243
+ /**
244
+ * ¿LA CADENA DE SELLADORAS LLEVA, DESDE LA MAESTRA QUE CONOZCO, HASTA QUIEN SELLÓ ESTA ACTA?
245
+ *
246
+ * `chain` es la de `identity.sealerChain()` (génesis, cambios de sellador, la vigente), tal
247
+ * como la manda la bóveda en `vault.devices`. Puede venir de cualquiera —el proxio, otra
248
+ * bóveda—, así que no se le cree nada: se comprueba entera.
249
+ *
250
+ * 1. Encadena (`verifySealerChain`): cada eslabón lo selló alguien a quien el anterior
251
+ * dejaba sellar, desde una raíz firmada por la llave del perfil de ESTA acta.
252
+ * 2. Es MI cuenta: algún eslabón lo firmó la maestra que este agente lleva pineada. Sin
253
+ * esto, cualquiera fabrica una cuenta suya que nombre a mi maestra como selladora.
254
+ * 3. El acta cuelga de esa cadena: se pone detrás del último cambio de sellador anterior a
255
+ * ella y se vuelve a comprobar, así que quien la selló tenía permiso según ese eslabón
256
+ * (y su ancla, si la lleva, apunta a él). Si la cadena ya la trae, tiene que ser la misma.
257
+ */
258
+ export async function sealedByChain ({ chain, acta, masterPubkey }) {
259
+ if (!Array.isArray(chain) || !chain.length) return { ok: false, reason: 'empty-chain' }
260
+ if (!acta || typeof acta.seq !== 'number') return { ok: false, reason: 'no-record' }
261
+ const whole = await verifySealerChain(chain, { expectedProfileId: acta.profileId })
262
+ if (whole.ok === false) return { ok: false, reason: whole.reason }
263
+ if (!chain.some((a) => a.sealedBy === masterPubkey)) return { ok: false, reason: 'not-my-account' }
264
+ const same = chain.find((a) => a.seq === acta.seq)
265
+ let path
266
+ if (same) {
267
+ if (await actaHash(same) !== await actaHash(acta)) return { ok: false, reason: 'other-record' }
268
+ path = chain.filter((a) => a.seq <= acta.seq)
269
+ } else {
270
+ const before = chain.filter((a) => a.seq < acta.seq)
271
+ // Lo último de la cadena puede ser el acta vigente de entonces, que no cambió selladores:
272
+ // el ancla del acta apunta al último CAMBIO, así que eso se quita (la raíz se queda).
273
+ while (before.length > 1 && !before[before.length - 1].sealerChanged) before.pop()
274
+ if (!before.length) return { ok: false, reason: 'record-before-chain' }
275
+ path = [...before, acta]
276
+ }
277
+ if (!path.some((a) => a.sealedBy === masterPubkey)) return { ok: false, reason: 'not-my-account' }
278
+ const v = await verifySealerChain(path, { expectedProfileId: acta.profileId })
279
+ return v.ok === false ? { ok: false, reason: v.reason } : { ok: true }
280
+ }