@dotrino/identity 0.121.8 → 0.123.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/identity",
3
- "version": "0.121.8",
3
+ "version": "0.123.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",
package/src/index.d.ts CHANGED
@@ -312,6 +312,7 @@ export function assertionBody (args: { sub: string; aud: string; nonce: string;
312
312
  export function verifyAssertion (assertion: Assertion, opts: { audience: string; nonce: string; expectedProfileId?: string | null; now?: number; maxSkewMs?: number }): Promise<VerifiedAssertion>
313
313
  /** ¿Este contenido firmado (un pin, una atestación) va dirigido a mí? `aud` obligatorio; `exp` opcional. */
314
314
  export function verifySignedFor (args: { data: any; signature: string; publickey: string; chain: any[]; audience: string; expectedProfileId?: string | null; now?: number; maxSkewMs?: number }): Promise<{ ok: boolean; reason?: string; profileId?: string; signer?: string; seq?: number; aud?: string }>
315
+ export function signedFor (identity: { signData: (d: object) => Promise<{ signature: string; publickey: string; chain?: any[] }> }, opts: { aud: string; fields?: object; ttlMs?: number; now?: number }): Promise<{ body: Record<string, any>; signature: string; publickey: string; chain: any[] }>
315
316
 
316
317
  // ----- Sesiones: entrar sin enrolar (`@dotrino/identity/session`) -----
317
318
 
@@ -215,4 +215,28 @@ export async function verifySignedFor (args = {}) {
215
215
  return { ok: true, profileId: v.profileId, signer: v.signer, seq: v.seq, aud: data.aud }
216
216
  }
217
217
 
218
- export default { ASSERTION_V, ASSERTION_MAX_TTL_MS, ASSERTION_DEFAULT_TTL_MS, ASSERTION_MAX_SKEW_MS, SCOPES, SCOPE_CLAIMS, newAssertionNonce, cleanScopes, claimsAllowed, assertionBody, verifyAssertion, verifySignedFor }
218
+ /**
219
+ * LA OTRA MITAD DE `verifySignedFor`: firma una petición dirigida a un servicio (`aud`) con el
220
+ * perfil activo, lista para mandarla. Es lo que usan las páginas que hablan con un servicio de
221
+ * la cuenta sin sesiones ni cookies (el directorio de nombres, las cuentas de la bóveda
222
+ * alojada): cada petición lleva su firma, la llave del aparato y la cadena de selladores que
223
+ * prueba que ese aparato habla por la cuenta. Una vez aquí, y no copiado en cada página.
224
+ *
225
+ * const req = await signedFor(identity, { aud: 'https://accounts.dotrino.com', fields: { v: 1, op: 'mine' } })
226
+ * → { body: { aud, iat, exp, nonce, v, op }, signature, publickey, chain }
227
+ *
228
+ * Sin cadena no hay petición: el servicio no podría saber de qué cuenta es, y mandarla igual
229
+ * sería mandar algo que va a rechazar. Se para con `no-chain`.
230
+ *
231
+ * @param {{ signData: (d: object) => Promise<{ signature: string, publickey: string, chain?: any[] }> }} identity
232
+ * @param {{ aud: string, fields?: object, ttlMs?: number, now?: number }} opts
233
+ */
234
+ export async function signedFor (identity, { aud, fields = {}, ttlMs = 24 * 60 * 60 * 1000, now = Date.now() } = {}) {
235
+ if (typeof aud !== 'string' || !aud.trim()) throw Object.assign(new Error('signedFor: aud is required'), { code: 'no-audience' })
236
+ const body = { aud: aud.trim(), iat: now, exp: now + ttlMs, nonce: crypto.randomUUID(), ...fields }
237
+ const s = await identity.signData(body)
238
+ if (!Array.isArray(s?.chain) || !s.chain.length) throw Object.assign(new Error('this device cannot prove it belongs to the account'), { code: 'no-chain' })
239
+ return { body, signature: s.signature, publickey: s.publickey, chain: s.chain }
240
+ }
241
+
242
+ export default { ASSERTION_V, ASSERTION_MAX_TTL_MS, ASSERTION_DEFAULT_TTL_MS, ASSERTION_MAX_SKEW_MS, SCOPES, SCOPE_CLAIMS, newAssertionNonce, cleanScopes, claimsAllowed, assertionBody, verifyAssertion, verifySignedFor, signedFor }
package/vault/vault.js CHANGED
@@ -192,7 +192,15 @@ import { useBackend as usePeerBackend } from './peerStore.js'
192
192
  // aprobaciones, consola remota, inicios de sesión. Solo UN iframe por origin es el activo
193
193
  // (navigator.locks): la pestaña VISIBLE sostiene el lock; al pasar a background lo
194
194
  // libera y otra pestaña visible lo toma. Así varias apps abiertas no compiten.
195
+ // EL INTERRUPTOR ES DE UN PERFIL: guarda el `pid` cuya bóveda corre este navegador. Era un
196
+ // «1» global y la pestaña arrancaba la bóveda de la cuenta que tuviera abierta, aunque fuera
197
+ // una entrada con contraseña que no sella nada (2026-10-19). El «1» viejo se lee como apagado:
198
+ // se vuelve a encender una vez desde la consola.
195
199
  const SELF_FLAG = 'dotrino.self-vault.enabled' // persistido en localStorage (kv)
200
+ const selfEnabled = async () => {
201
+ const { id } = await handlers.currentProfile()
202
+ return !!id && kv.getItem(SELF_FLAG) === id
203
+ }
196
204
  const SELF_LOCK = 'dotrino-self-vault'
197
205
  /**
198
206
  * Proxio del mostrador, SOLO en localhost (`?proxy=ws://…` en la URL de este iframe).
@@ -211,6 +219,7 @@ import { useBackend as usePeerBackend } from './peerStore.js'
211
219
  } catch (_) { return null }
212
220
  })()
213
221
  let daemon = null // la bóveda (`startBrowserVault`) cuando ESTE iframe es el activo
222
+ let daemonError = null // por qué no arrancó (`{ code, message }`), para enseñarlo
214
223
  let _lockResolver = null // resolver del callback del lock (libera al resolverlo)
215
224
 
216
225
  // La dirección `nombre@AB12-CD34-EF56` sale del acta de la cuenta.
@@ -238,15 +247,21 @@ import { useBackend as usePeerBackend } from './peerStore.js'
238
247
  // disco en IndexedDB. Import dinámico: el iframe lo cargan las ~30 apps y solo esta
239
248
  // pestaña es bóveda; además aísla un fallo del vendor del arranque de la identidad.
240
249
  const { startBrowserVault } = await import('@dotrino/vault/browser')
250
+ daemonError = null
241
251
  daemon = await startBrowserVault({
242
252
  core,
243
253
  ...(selfProxyUrl ? { proxyUrl: selfProxyUrl } : {}),
244
254
  legacyLogins,
245
255
  onPendingChange: () => broadcast('selfVault', { pending: daemon ? daemon.listPending() : [] }),
256
+ onStopped: (e) => { daemon = null; daemonError = { code: e?.code || null, message: e?.message || String(e) }; broadcast('selfVault', { running: false, error: daemonError.message }) },
246
257
  log: (...a) => console.log(...a)
247
258
  })
248
259
  broadcast('selfVault', { running: true })
249
- } catch (e) { daemon = null; broadcast('selfVault', { error: e?.message || String(e) }) }
260
+ } catch (e) {
261
+ daemon = null
262
+ daemonError = { code: e?.code || null, message: e?.message || String(e) }
263
+ broadcast('selfVault', { error: daemonError.message })
264
+ }
250
265
  }
251
266
  function stopSelfDaemon () {
252
267
  if (!daemon) return
@@ -256,9 +271,9 @@ import { useBackend as usePeerBackend } from './peerStore.js'
256
271
  }
257
272
 
258
273
  // Adquiere el lock solo si el modo self está activado Y la pestaña es visible.
259
- function holdSelfLock () {
274
+ async function holdSelfLock () {
260
275
  if (!navigator.locks) return
261
- if (kv.getItem(SELF_FLAG) !== '1' || document.visibilityState !== 'visible') return
276
+ if (!(await selfEnabled()) || document.visibilityState !== 'visible') return
262
277
  navigator.locks.request(SELF_LOCK, { mode: 'exclusive', ifAvailable: true }, async (lock) => {
263
278
  if (!lock) return // otra pestaña visible lo tiene
264
279
  await startSelfDaemon()
@@ -309,7 +324,7 @@ import { useBackend as usePeerBackend } from './peerStore.js'
309
324
  // hacer RPC al daemon del PC: somos nuestra propia maestra. Así ia/terminal listan
310
325
  // agentes siempre, sin depender de qué pestaña sostenga el lock del daemon.
311
326
  listVaultDevices: async () => {
312
- if (kv.getItem(SELF_FLAG) !== '1') return handlers.listVaultDevices({})
327
+ if (!(await selfEnabled())) return handlers.listVaultDevices({})
313
328
  // Con la bóveda encendida en ESTA pestaña, la lista sale de ella (por el camino
314
329
  // local): trae lo mismo que la del binario. Sin ella encendida, se lee lo guardado.
315
330
  if (daemon) return handlers.listVaultDevices({})
@@ -327,9 +342,11 @@ import { useBackend as usePeerBackend } from './peerStore.js'
327
342
  })))
328
343
  return { devices, revoked: (revoked || []).map((r) => r.nonce || r) }
329
344
  },
330
- selfVaultStatus: async () => ({ enabled: kv.getItem(SELF_FLAG) === '1', running: !!daemon }),
345
+ selfVaultStatus: async () => ({ enabled: await selfEnabled(), running: !!daemon, error: daemon ? null : daemonError }),
331
346
  setSelfVault: async ({ enabled }) => {
332
- kv.setItem(SELF_FLAG, enabled ? '1' : '0')
347
+ const { id } = await handlers.currentProfile()
348
+ if (enabled && !id) throw Object.assign(new Error('no profile: the vault belongs to an account'), { code: 'no-profile' })
349
+ if (enabled) kv.setItem(SELF_FLAG, id); else kv.removeItem(SELF_FLAG)
333
350
  if (enabled) holdSelfLock(); else releaseSelfLock()
334
351
  return { ok: true, enabled: !!enabled }
335
352
  },
@@ -1,4 +1,4 @@
1
- Copia vendorizada de @dotrino/proxy-client@0.38.4 (dotrino-proxy-client/src/{binpack,canonical,client,encpub,errors,index,parts,sealing,signature,stats-log,stats,webrtc}.js).
1
+ Copia vendorizada de @dotrino/proxy-client@0.39.0 (dotrino-proxy-client/src/{binpack,canonical,client,encpub,errors,index,parts,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.
@@ -1384,11 +1384,18 @@ export class WebSocketProxyClient {
1384
1384
  * `channel` (opcional): el canal donde la buscan quienes no saben su llave —quien entra con
1385
1385
  * usuario y contraseña—. Listarlo vacío también la despierta (`list()` devuelve `waking`).
1386
1386
  *
1387
- * @param {{ publicKey:string, sign:Function, url:string, acta:object, channel?:string }} opts
1387
+ * `self` (websocket-proxy ≥ 1.8.0): el timbre es de ESTA llave y no de la cuenta. Lo usa una
1388
+ * réplica que vive en una función: se identifica con su llave, y es a ella a la que le
1389
+ * escribe un servicio cuando la bóveda no contesta. Un proxio que no anuncia `wake-self` lo
1390
+ * guardaría para la cuenta y le quitaría el timbre a la bóveda, así que ahí no se manda.
1391
+ *
1392
+ * @param {{ publicKey:string, sign:Function, url:string, acta:object, channel?:string, self?:boolean }} opts
1388
1393
  */
1389
- async registerWake ({ publicKey, sign, url, acta, channel } = {}) {
1394
+ async registerWake ({ publicKey, sign, url, acta, channel, self = false } = {}) {
1390
1395
  if (!publicKey || typeof sign !== 'function' || !url || !acta) throw errorWithCode('registerWake requires { publicKey, sign, url, acta }', 'bad-args')
1391
- const data = { op: 'push-subscribe', publickey: publicKey, subscription: JSON.stringify({ kind: 'wake', url, ...(channel ? { channel } : {}) }), ts: Date.now() }
1396
+ if (self && channel) throw errorWithCode('registerWake: a self wake has no channel', 'bad-args')
1397
+ if (self && !(Array.isArray(this.caps) && this.caps.includes('wake-self'))) throw errorWithCode('registerWake: this proxy does not support a wake for the device key (needs websocket-proxy >= 1.8.0)', 'no-wake-self-support')
1398
+ const data = { op: 'push-subscribe', publickey: publicKey, subscription: JSON.stringify({ kind: 'wake', url, ...(channel ? { channel } : {}), ...(self ? { self: true } : {}) }), ts: Date.now() }
1392
1399
  const signature = await normalizeSignature(sign, data)
1393
1400
  const r = await this._request({ type: 'push-subscribe', data, signature, acta }, 'push-subscribed')
1394
1401
  return { kind: 'wake', url, profile: r?.publickey || null }
@@ -1,3 +1,3 @@
1
- Copia vendorizada de @dotrino/roadmap@0.4.40 (dotrino-roadmap/src/{index,manifests}.js).
1
+ Copia vendorizada de @dotrino/roadmap@0.4.46 (dotrino-roadmap/src/{index,manifests}.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
  El registro de versiones rotas que viaja con cada versión. Importa @dotrino/compat/ranges.
@@ -8,7 +8,7 @@
8
8
  export const MANIFESTS = Object.freeze({
9
9
  "dotrino": {
10
10
  "manifest": "dotrino",
11
- "seq": 35,
11
+ "seq": 37,
12
12
  "issued": "2026-10-18",
13
13
  "note": "Registro comun de compatibilidad del ecosistema. Se edita a mano en este repo y se consulta con @dotrino/roadmap. Rangos: ver @dotrino/compat/ranges (x.y.z, >= > <= <, «a - b», «*», o una lista que es un O).",
14
14
  "products": {
@@ -22,7 +22,7 @@ export const MANIFESTS = Object.freeze({
22
22
  "env": {
23
23
  "repo": "imdotrino/dotrino-vault",
24
24
  "npm": "@dotrino/env",
25
- "current": "0.93.0",
25
+ "current": "0.93.1",
26
26
  "protocol": 1,
27
27
  "requires": {
28
28
  "vault": ">=0.93.0"
@@ -31,7 +31,7 @@ export const MANIFESTS = Object.freeze({
31
31
  "identity": {
32
32
  "repo": "imdotrino/dotrino-identity",
33
33
  "npm": "@dotrino/identity",
34
- "current": "0.121.6",
34
+ "current": "0.121.8",
35
35
  "protocol": 1,
36
36
  "requires": {
37
37
  "proxy-client": ">=0.13.1"
@@ -109,7 +109,7 @@ export const MANIFESTS = Object.freeze({
109
109
  },
110
110
  "proxy": {
111
111
  "repo": "imdotrino/dotrino-proxy",
112
- "current": "1.7.0",
112
+ "current": "1.8.0",
113
113
  "protocol": 2,
114
114
  "requires": {
115
115
  "vault": ">=0.87.0",
@@ -121,7 +121,7 @@ export const MANIFESTS = Object.freeze({
121
121
  "proxy-client": {
122
122
  "repo": "imdotrino/dotrino-proxy-client",
123
123
  "npm": "@dotrino/proxy-client",
124
- "current": "0.38.4",
124
+ "current": "0.39.0",
125
125
  "protocol": 2,
126
126
  "requires": {
127
127
  "identity": ">=0.53.0",
@@ -131,10 +131,10 @@ export const MANIFESTS = Object.freeze({
131
131
  "remote-agent": {
132
132
  "repo": "imdotrino/dotrino-remote-agent",
133
133
  "npm": "@dotrino/remote-agent",
134
- "current": "0.22.4",
134
+ "current": "0.22.5",
135
135
  "protocol": 1,
136
136
  "requires": {
137
- "identity": ">=0.121.4",
137
+ "identity": ">=0.121.7",
138
138
  "vault": ">=0.85.0",
139
139
  "proxy-client": ">=0.36.1",
140
140
  "vaultd": ">=0.154.0"
@@ -143,11 +143,11 @@ export const MANIFESTS = Object.freeze({
143
143
  "terminal-agent": {
144
144
  "repo": "imdotrino/dotrino-terminal",
145
145
  "npm": "@dotrino/terminal-agent",
146
- "current": "0.49.0",
146
+ "current": "0.49.1",
147
147
  "protocol": 2,
148
148
  "requires": {
149
- "remote-agent": ">=0.22.4",
150
- "identity": ">=0.121.6",
149
+ "remote-agent": ">=0.22.5",
150
+ "identity": ">=0.121.7",
151
151
  "vault": ">=0.93.0",
152
152
  "proxy-client": ">=0.38.4",
153
153
  "vaultd": ">=0.142.0"
@@ -155,7 +155,7 @@ export const MANIFESTS = Object.freeze({
155
155
  },
156
156
  "terminal-ios": {
157
157
  "repo": "imdotrino/dotrino-terminal",
158
- "current": "0.13.2",
158
+ "current": "0.13.7",
159
159
  "protocol": 1,
160
160
  "requires": {
161
161
  "terminal-agent": ">=0.37.0"
@@ -163,7 +163,7 @@ export const MANIFESTS = Object.freeze({
163
163
  },
164
164
  "terminal-android": {
165
165
  "repo": "imdotrino/dotrino-terminal",
166
- "current": "0.13.4",
166
+ "current": "0.13.7",
167
167
  "protocol": 1,
168
168
  "requires": {
169
169
  "terminal-agent": ">=0.37.0"
@@ -171,7 +171,7 @@ export const MANIFESTS = Object.freeze({
171
171
  },
172
172
  "terminal-desktop": {
173
173
  "repo": "imdotrino/dotrino-terminal",
174
- "current": "0.2.77",
174
+ "current": "0.2.80",
175
175
  "protocol": 1,
176
176
  "requires": {
177
177
  "terminal-agent": ">=0.37.0"
@@ -205,13 +205,13 @@ export const MANIFESTS = Object.freeze({
205
205
  "sealers": {
206
206
  "repo": "imdotrino/dotrino-sealers",
207
207
  "npm": "@dotrino/sealers",
208
- "current": "0.10.2",
208
+ "current": "0.10.4",
209
209
  "protocol": 1,
210
210
  "requires": {
211
- "remote-agent": ">=0.20.1",
212
- "identity": ">=0.117.2",
213
- "vault": ">=0.87.0",
214
- "proxy-client": ">=0.36.1"
211
+ "remote-agent": ">=0.22.4",
212
+ "identity": ">=0.121.7",
213
+ "vault": ">=0.93.1",
214
+ "proxy-client": ">=0.38.4"
215
215
  }
216
216
  },
217
217
  "roadmap": {
@@ -253,11 +253,11 @@ export const MANIFESTS = Object.freeze({
253
253
  "vault": {
254
254
  "repo": "imdotrino/dotrino-vault",
255
255
  "npm": "@dotrino/vault",
256
- "current": "0.93.0",
256
+ "current": "0.94.0",
257
257
  "protocol": 1,
258
258
  "requires": {
259
259
  "vaultd": ">=0.105.0",
260
- "proxy-client": ">=0.38.0",
260
+ "proxy-client": ">=0.39.0",
261
261
  "identity": ">=0.118.0",
262
262
  "opaque": ">=0.1.0",
263
263
  "compat": ">=0.4.0",
@@ -269,11 +269,11 @@ export const MANIFESTS = Object.freeze({
269
269
  "vaultd": {
270
270
  "repo": "imdotrino/dotrino-vault",
271
271
  "npm": "@dotrino/vaultd",
272
- "current": "0.165.0",
272
+ "current": "0.166.2",
273
273
  "protocol": 1,
274
274
  "requires": {
275
275
  "identity": ">=0.118.0",
276
- "proxy-client": ">=0.38.0",
276
+ "proxy-client": ">=0.39.0",
277
277
  "store": ">=0.11.0",
278
278
  "passmanager": ">=0.18.4",
279
279
  "compat": ">=0.4.0",
@@ -332,7 +332,7 @@ export const MANIFESTS = Object.freeze({
332
332
  },
333
333
  "app": {
334
334
  "repo": "imdotrino/dotrino-app",
335
- "current": "0.4.22",
335
+ "current": "0.4.24",
336
336
  "protocol": 1,
337
337
  "requires": {
338
338
  "proxy": "1.4.7+",
@@ -342,7 +342,7 @@ export const MANIFESTS = Object.freeze({
342
342
  },
343
343
  "app-ios": {
344
344
  "repo": "imdotrino/dotrino-app",
345
- "current": "0.4.13",
345
+ "current": "0.4.14",
346
346
  "protocol": 1,
347
347
  "requires": {
348
348
  "proxy": "1.4.7+",
@@ -364,12 +364,14 @@ export const MANIFESTS = Object.freeze({
364
364
  "accounts": {
365
365
  "repo": "imdotrino/dotrino-accounts",
366
366
  "npm": null,
367
- "current": "0.1.0",
367
+ "current": "0.3.2",
368
368
  "protocol": 1,
369
369
  "requires": {
370
370
  "identity": ">=0.116.0",
371
371
  "remote-agent": ">=0.19.0",
372
- "vault": ">=0.92.0"
372
+ "vault": ">=0.94.0",
373
+ "pay": ">=0.2.0",
374
+ "vaultd": ">=0.166.2"
373
375
  }
374
376
  },
375
377
  "ai": {
@@ -378,6 +380,13 @@ export const MANIFESTS = Object.freeze({
378
380
  "current": "0.1.1",
379
381
  "protocol": 1,
380
382
  "requires": {}
383
+ },
384
+ "pay": {
385
+ "repo": "imdotrino/dotrino-pay",
386
+ "npm": "@dotrino/pay",
387
+ "current": "0.2.0",
388
+ "protocol": 1,
389
+ "requires": {}
381
390
  }
382
391
  },
383
392
  "broken": [
@@ -1,4 +1,4 @@
1
- Copia vendorizada de @dotrino/vault@0.93.1 (dotrino-vault/lib/src/{admin,b64,browser,core/approvals,core/backup,core/blocked,core/browserDisk,core/commKey,core/disk,core/libVersion,core/machines,core/notices,core/notifiable,core/passwords,core/sealKey,core/sealer,core/sealers,core/secretsStore,core/sha256,core/store,core/subacta,core/threadStore,core/transport,core/vault,enroll,index,loginClient,passwordLogins,procContext,protocol,revocation,sealed}.js).
1
+ Copia vendorizada de @dotrino/vault@0.95.0 (dotrino-vault/lib/src/{admin,b64,browser,core/approvals,core/backup,core/blocked,core/browserDisk,core/commKey,core/disk,core/libVersion,core/machines,core/notices,core/notifiable,core/passwords,core/sealKey,core/sealer,core/sealers,core/secretsStore,core/sha256,core/store,core/subacta,core/threadStore,core/transport,core/vault,enroll,index,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
@@ -38,6 +38,7 @@ const SELF_CERT_EVERY_MS = 60_000
38
38
  * antes de correr el núcleo (`{ state, drop }` o `null`). Se traen UNA vez.
39
39
  * @param {Function} [opts.onPendingChange] un aparato espera aprobación, o dejó de esperar
40
40
  * @param {Function} [opts.onAdopted]
41
+ * @param {Function} [opts.onStopped] `(error)`: la bóveda se paró sola (la cuenta de la pestaña cambió)
41
42
  * @param {Function} [opts.log]
42
43
  * @param {object} [opts.opaque] el servidor de OPAQUE, si el del paquete no se puede cargar aquí
43
44
  * (la extensión: su CSP no deja WASM en la página de la bóveda).
@@ -46,12 +47,18 @@ const SELF_CERT_EVERY_MS = 60_000
46
47
  * @param {Function} [opts.openDisk] `(name) => disk`. Solo para las pruebas (Node no tiene
47
48
  * IndexedDB); por defecto, `openBrowserDisk`.
48
49
  */
49
- export async function startBrowserVault ({ core, proxyUrl = DEFAULT_PROXY, makeClient = null, legacyLogins = null, onPendingChange = () => {}, onAdopted = () => {}, log = console.log, openDisk = openBrowserDisk, opaque = null, servePasswords = true } = {}) {
50
+ export async function startBrowserVault ({ core, proxyUrl = DEFAULT_PROXY, makeClient = null, legacyLogins = null, onPendingChange = () => {}, onAdopted = () => {}, onStopped = () => {}, log = console.log, openDisk = openBrowserDisk, opaque = null, servePasswords = true } = {}) {
50
51
  if (!core?.handlers) throw Object.assign(new Error('startBrowserVault: the identity core is required'), { code: 'no-identity' })
51
52
  const identity = new IdentityFacade(core)
52
53
  if (!identity.me?.publickey) throw Object.assign(new Error('no identity: create or unlock your profile before using this browser as a vault'), { code: 'no-identity' })
53
54
  const { id: pid } = await identity.currentProfile()
54
55
  if (!pid) throw Object.assign(new Error('no profile: the vault belongs to an account'), { code: 'no-profile' })
56
+ // UNA BÓVEDA QUE NO PUEDE SELLAR SU ACTA NO ES UNA BÓVEDA. Arrancaba igual —un aparato
57
+ // entrado con usuario y contraseña es miembro, no selladora— y el fallo salía después, al
58
+ // aprobar a alguien («not the master, nor a co-sealer»), con el código ya en pantalla.
59
+ const info = await identity.profileActa()
60
+ if (!info?.acta) throw Object.assign(new Error('this account has no record yet: open the profile first'), { code: 'no-record' })
61
+ if (!info.isMaster) throw Object.assign(new Error('this browser cannot be the vault of the account open here: its key does not seal the account record'), { code: 'not-sealer' })
55
62
 
56
63
  const disk = await openDisk(`dotrino-vault.${pid}`)
57
64
 
@@ -95,6 +102,15 @@ export async function startBrowserVault ({ core, proxyUrl = DEFAULT_PROXY, makeC
95
102
  // perfil firmándose a sí misma con lo que el acta le deja hoy. Se rehace cada minuto
96
103
  // porque el acta cambia (un permiso que te quitas, un sellado nuevo).
97
104
  const master = identity.me.publickey
105
+ // LA BÓVEDA ES DE UNA CUENTA. Si en esta pestaña se abre otra (crear perfil, entrar con
106
+ // contraseña), la identidad cambia por debajo y la bóveda firmaría como la nueva con el
107
+ // disco de la vieja: se para antes de firmar nada.
108
+ const sameAccount = async () => {
109
+ const { id } = await identity.currentProfile()
110
+ if (id !== pid || identity.me?.publickey !== master) {
111
+ throw Object.assign(new Error('the account open in this tab changed: this vault was started for another one; reload the tab'), { code: 'profile-changed' })
112
+ }
113
+ }
98
114
  const selfCert = async () => {
99
115
  const acta = (await identity.profileActa().catch(() => null))?.acta || null
100
116
  if (!acta) return null
@@ -119,15 +135,36 @@ export async function startBrowserVault ({ core, proxyUrl = DEFAULT_PROXY, makeC
119
135
  log('[vault] this browser administers the account: admin added to its own key')
120
136
  }
121
137
  const open = (onReply) => vault.localChannel(onReply)
138
+ let stopped = false
139
+ let refresh = null
140
+ const shutdown = async () => {
141
+ if (stopped) return
142
+ stopped = true
143
+ clearInterval(refresh)
144
+ try { core.setSelfVault?.(null) } catch (_) {}
145
+ vault.close()
146
+ try { await disk.flush() } catch (e) { log('[vault] some changes could not be saved: ' + (e?.message || e)) }
147
+ disk.close()
148
+ }
122
149
  const present = async () => {
150
+ if (stopped) return
123
151
  try {
152
+ await sameAccount()
124
153
  await ensureAdmin()
125
154
  const cert = await selfCert()
126
155
  core.setSelfVault?.(cert ? { cert, proxy: proxyUrl, open } : null)
127
- } catch (e) { log('[vault] the console in this browser cannot administer this vault yet: ' + (e?.message || e)) }
156
+ } catch (e) {
157
+ if (e?.code === 'profile-changed') {
158
+ log('[vault] ' + e.message)
159
+ await shutdown()
160
+ try { onStopped(e) } catch (_) {}
161
+ return
162
+ }
163
+ log('[vault] the console in this browser cannot administer this vault yet: ' + (e?.message || e))
164
+ }
128
165
  }
129
166
  await present()
130
- const refresh = setInterval(present, SELF_CERT_EVERY_MS)
167
+ if (!stopped) refresh = setInterval(present, SELF_CERT_EVERY_MS)
131
168
 
132
169
  return {
133
170
  ...vault,
@@ -135,7 +172,7 @@ export async function startBrowserVault ({ core, proxyUrl = DEFAULT_PROXY, makeC
135
172
  proxy: proxyUrl,
136
173
  disk,
137
174
  /** Aprueba TIPEANDO el código que muestra el aparato (el núcleo comprueba el compromiso). */
138
- approve: async (_deviceId, code) => { try { return await vault.approveDevice(code) } finally { notify() } },
175
+ approve: async (_deviceId, code) => { try { await sameAccount(); return await vault.approveDevice(code) } finally { notify() } },
139
176
  reject: (deviceId) => { try { return vault.rejectDevice(deviceId) } finally { notify() } },
140
177
  /**
141
178
  * Las máquinas con papel de firma de esta cuenta (excluye los navegadores enrolados con
@@ -154,13 +191,7 @@ export async function startBrowserVault ({ core, proxyUrl = DEFAULT_PROXY, makeC
154
191
  },
155
192
  revokeDevice: (sub) => vault.revokeDevice({ sub }),
156
193
  revoke: (nonce) => vault.revokeDevice(nonce),
157
- async close () {
158
- clearInterval(refresh)
159
- try { core.setSelfVault?.(null) } catch (_) {}
160
- vault.close()
161
- try { await disk.flush() } catch (e) { log('[vault] some changes could not be saved: ' + (e?.message || e)) }
162
- disk.close()
163
- }
194
+ close: shutdown
164
195
  }
165
196
  }
166
197
 
@@ -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.93.1'
8
+ export const LIB_VERSION = '0.95.0'
@@ -370,7 +370,13 @@ export function createEnrollDesk ({
370
370
  // llegue el acta sellada, que es la que este dispositivo dijo que iba a entregar.
371
371
  if (intent === 'adopt' && typeof d.profileId === 'string') pend.profileId = d.profileId
372
372
 
373
- await tell(from, { type: MSG_ENROLL_CHALLENGE, deviceId }, pend.sn)
373
+ // DE QUÉ CUENTA ES ESTA BÓVEDA, demostrable: la cadena de selladoras (su raíz la firma la
374
+ // llave del perfil). Va DENTRO del reto firmado para que el aparato pueda negarse a entrar
375
+ // en otra cuenta ANTES de enseñar su código —la réplica que se pagó para una cuenta, por
376
+ // ejemplo— en vez de descubrirlo cuando ya lo aprobaron. Quien no la mira, no la necesita.
377
+ let chain = null
378
+ try { chain = (await identity.sealerChain?.()) || null } catch (e) { log('[vault] could not build the sealer chain for the challenge:', e.message) }
379
+ await tell(from, { type: MSG_ENROLL_CHALLENGE, deviceId, chain }, pend.sn)
374
380
  fire(onChallenge, { deviceId, scope: pend.scope, label: pend.label || '', machine: pend.machine || null, mode: pend.mode || 'join' })
375
381
  fire(onPendingChange)
376
382
  return { deviceId }