@dotrino/identity 0.121.7 → 0.121.8

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.
@@ -69,10 +69,10 @@ export async function startDeviceVault (identity, { proxyUrl, client: injectedCl
69
69
  /**
70
70
  * Con qué se juzga un papel: el acta que tiene esta bóveda. Sustituye a `trustedIssuer`,
71
71
  * que fijaba UNA llave y por eso los papeles de una segunda selladora no valían.
72
- * Sin acta van nulos y `verifyDelegation` contesta `no-acta`: no hay con qué decidir, así
72
+ * Sin acta van nulos y `verifyDelegation` contesta `no-record`: no hay con qué decidir, así
73
73
  * que no se decide que sí.
74
74
  */
75
- async function contextoActa () {
75
+ async function actaContext () {
76
76
  const acta = (await identity.profileActa?.().catch(() => null))?.acta || null
77
77
  if (!acta) return { actaSeq: null, sealers: null }
78
78
  return { actaSeq: acta.seq, sealers: sealersOf(acta) }
@@ -81,7 +81,7 @@ export async function startDeviceVault (identity, { proxyUrl, client: injectedCl
81
81
  let _selfCert = null
82
82
  const getSelfCert = async () => {
83
83
  // Se rehace cuando el acta cambia, no cuando pasa el tiempo: el papel ya no caduca.
84
- const { actaSeq } = await contextoActa()
84
+ const { actaSeq } = await actaContext()
85
85
  if (_selfCert && _selfCert.seq === actaSeq) return _selfCert
86
86
  const { cert } = await identity.signDelegation(iss, SIGN_SCOPE)
87
87
  _selfCert = cert
@@ -187,7 +187,7 @@ export async function startDeviceVault (identity, { proxyUrl, client: injectedCl
187
187
  if (typeof d.ts !== 'number' || Math.abs(Date.now() - d.ts) > FRESH_WINDOW_MS) {
188
188
  return send(from, { type: MSG.ERROR, error: 'stale request: ts outside the ±5 min window (possible replay, or the device clock is off)' })
189
189
  }
190
- const chk = await verifyChain({ data: d, signature: p.signature, cert: p.cert, ...(await contextoActa()), revoked: await revocationSet() })
190
+ const chk = await verifyChain({ data: d, signature: p.signature, cert: p.cert, ...(await actaContext()), revoked: await revocationSet() })
191
191
  if (!chk.ok) return send(from, { type: MSG.ERROR, error: 'unauthorized: ' + chk.reason })
192
192
  // Reusar el label del cert original (si sigue registrado en delegations).
193
193
  const { issued } = await identity.listDelegations()
@@ -210,7 +210,7 @@ export async function startDeviceVault (identity, { proxyUrl, client: injectedCl
210
210
  const d = p?.data
211
211
  if (!d || !p.signature || !p.cert) return send(from, { type: MSG.ERROR, error: 'invalid request' })
212
212
  if (typeof d.ts !== 'number' || Math.abs(Date.now() - d.ts) > FRESH_WINDOW_MS) return
213
- const chk = await verifyChain({ data: d, signature: p.signature, cert: p.cert, ...(await contextoActa()) })
213
+ const chk = await verifyChain({ data: d, signature: p.signature, cert: p.cert, ...(await actaContext()) })
214
214
  if (!chk.ok) return send(from, { type: MSG.ERROR, error: 'unauthorized: ' + chk.reason })
215
215
  const { issued, revoked, revokedCerts } = await identity.listDelegations()
216
216
  const devices = await Promise.all((issued || []).map(async (x) => ({
@@ -248,7 +248,7 @@ export async function startDeviceVault (identity, { proxyUrl, client: injectedCl
248
248
  const chk = await verifyChain({
249
249
  data: d, signature: p.signature, cert: p.cert,
250
250
  ...(expectedScope ? { expectedScope } : {}),
251
- ...(await contextoActa()), revoked: await revocationSet(),
251
+ ...(await actaContext()), revoked: await revocationSet(),
252
252
  })
253
253
  if (!chk.ok) {
254
254
  send(from, { type: MSG.ERROR, error: 'unauthorized: ' + chk.reason })
@@ -54,18 +54,18 @@ export const WAKE_WAIT_MS = 30_000
54
54
  */
55
55
  function waitFor (transport, from, match, timeoutMs) {
56
56
  return new Promise((resolve, reject) => {
57
- let listo = false
58
- const fin = (fn, arg) => { if (!listo) { listo = true; clearTimeout(reloj); quitar(); fn(arg) } }
59
- const reloj = setTimeout(() => fin(reject, err('no-answer', 'the vault did not answer in time')), timeoutMs)
60
- const oyente = (quien, payload) => {
61
- if (from && quien !== from) return
57
+ let ready = false
58
+ const fin = (fn, arg) => { if (!ready) { ready = true; clearTimeout(clock); remove(); fn(arg) } }
59
+ const clock = setTimeout(() => fin(reject, err('no-answer', 'the vault did not answer in time')), timeoutMs)
60
+ const listener = (who, payload) => {
61
+ if (from && who !== from) return
62
62
  const p = typeof payload === 'string' ? parseJson(payload) : payload
63
63
  if (p && match(p)) fin(resolve, p)
64
64
  }
65
- const off = transport.on('message', oyente)
66
- const quitar = () => {
65
+ const off = transport.on('message', listener)
66
+ const remove = () => {
67
67
  if (typeof off === 'function') return off()
68
- transport.off?.('message', oyente)
68
+ transport.off?.('message', listener)
69
69
  }
70
70
  })
71
71
  }
@@ -103,8 +103,8 @@ export async function loginWithPassword ({ transport, address, password, label =
103
103
  let tokens = await transport.list(vaultChannel(code))
104
104
  // UNA BÓVEDA QUE DUERME (la de una Lambda): el proxio la está despertando y lo dice. Se
105
105
  // espera a que se anuncie en vez de contestar que esa cuenta no existe.
106
- const hasta = Date.now() + WAKE_WAIT_MS
107
- while (!tokens.length && tokens.waking && Date.now() < hasta) {
106
+ const until = Date.now() + WAKE_WAIT_MS
107
+ while (!tokens.length && tokens.waking && Date.now() < until) {
108
108
  await new Promise((resolve) => setTimeout(resolve, 2000))
109
109
  tokens = await transport.list(vaultChannel(code))
110
110
  }
@@ -115,25 +115,25 @@ export async function loginWithPassword ({ transport, address, password, label =
115
115
  // De una en una, y parando en cuanto la contraseña resulte estar mal: cada intento GASTA
116
116
  // uno del freno en la bóveda que lo atiende (`passwordLogins.js`), así que repartir el
117
117
  // mismo error entre las réplicas solo sirve para bloquearse en todas a la vez.
118
- let ultimo = null
118
+ let last = null
119
119
  for (const token of tokens) {
120
120
  try {
121
- return await unIntento({ transport, token, user, code, dir, password, label, timeoutMs, opaque })
121
+ return await oneAttempt({ transport, token, user, code, dir, password, label, timeoutMs, opaque })
122
122
  } catch (e) {
123
123
  // Se para: son cosas del que entra, y probar con otra bóveda no las arregla.
124
124
  if (e?.code === 'login-failed' || e?.code === 'too-many-tries' || e?.code === 'wrong-account' ||
125
125
  e?.code === 'bad-blob' || e?.code === 'bad-keys' || e?.code === 'bad-reply') throw e
126
- ultimo = e // «esa no atiende inicios de sesión», «no contestó»: quizá la siguiente sí
126
+ last = e // «esa no atiende inicios de sesión», «no contestó»: quizá la siguiente sí
127
127
  }
128
128
  }
129
- throw ultimo || err('no-vault', 'none of the vaults on that address could let you in')
129
+ throw last || err('no-vault', 'none of the vaults on that address could let you in')
130
130
  }
131
131
 
132
- async function unIntento ({ transport, token, user, code, dir, password, label, timeoutMs, opaque }) {
132
+ async function oneAttempt ({ transport, token, user, code, dir, password, label, timeoutMs, opaque }) {
133
133
  const start = await opaque.loginStart({ password })
134
134
  transport.send(token, { type: MSG.LOGIN_START, user, request: start.request })
135
135
  const r1 = await waitFor(transport, token, (p) => p.type === MSG.LOGIN_RESPONSE || p.type === MSG.ERROR, timeoutMs)
136
- if (r1.type === MSG.ERROR) throw deVuelta(r1)
136
+ if (r1.type === MSG.ERROR) throw back(r1)
137
137
 
138
138
  let fin
139
139
  try {
@@ -148,7 +148,7 @@ async function unIntento ({ transport, token, user, code, dir, password, label,
148
148
 
149
149
  transport.send(token, { type: MSG.LOGIN_FINISH, lid: r1.lid, finalization: fin.finalization, label })
150
150
  const ok = await waitFor(transport, token, (p) => p.type === MSG.LOGIN_OK || p.type === MSG.ERROR, timeoutMs)
151
- if (ok.type === MSG.ERROR) throw deVuelta(ok)
151
+ if (ok.type === MSG.ERROR) throw back(ok)
152
152
 
153
153
  const acta = ok.acta
154
154
  const cert = ok.cert
@@ -168,9 +168,9 @@ async function unIntento ({ transport, token, user, code, dir, password, label,
168
168
  if (!keys?.sign) throw err('bad-blob', 'the key package does not carry a signing key')
169
169
 
170
170
  // 4. La llave que salió del paquete tiene que SER la del papel. Se prueba firmando.
171
- const reto = { op: 'login.proof', sub: cert.sub, sid: ok.sid, ts: Date.now() }
172
- const { signature } = await signWithDevice({ privateJwk: keys.sign, data: reto })
173
- if (!(await verifyDeviceSig({ publickey: cert.sub, data: reto, signature }))) {
171
+ const challenge = { op: 'login.proof', sub: cert.sub, sid: ok.sid, ts: Date.now() }
172
+ const { signature } = await signWithDevice({ privateJwk: keys.sign, data: challenge })
173
+ if (!(await verifyDeviceSig({ publickey: cert.sub, data: challenge, signature }))) {
174
174
  throw err('bad-keys', 'the keys in the package are not the ones this certificate is for')
175
175
  }
176
176
 
@@ -196,7 +196,7 @@ async function unIntento ({ transport, token, user, code, dir, password, label,
196
196
  }
197
197
 
198
198
  /** Un error de la bóveda con su `code` intacto: `too-many-tries` se arregla esperando. */
199
- function deVuelta (p) {
199
+ function back (p) {
200
200
  const code = p.code || 'login-error'
201
201
  const e = err(code, p.error || 'the vault refused the login')
202
202
  if (typeof p.waitMs === 'number') e.waitMs = p.waitMs
@@ -227,10 +227,10 @@ export async function closeLogin ({ transport, token, user, sid, publickey, priv
227
227
  if (typeof sign !== 'function' && !privateJwk && !privateKey) {
228
228
  throw err('no-signature', 'closeLogin: give it the device key (privateJwk/privateKey) or a sign(data)')
229
229
  }
230
- const firmado = typeof sign === 'function'
230
+ const signed = typeof sign === 'function'
231
231
  ? await sign(data)
232
232
  : await signWithDevice({ privateJwk, privateKey, publickey, data })
233
- const signature = typeof firmado === 'string' ? firmado : firmado?.signature
233
+ const signature = typeof signed === 'string' ? signed : signed?.signature
234
234
  if (typeof signature !== 'string') throw err('no-signature', 'closeLogin: sign(data) returned no signature')
235
235
  transport.send(token, { type: MSG.LOGIN_CLOSE, data, signature })
236
236
  try {
@@ -489,14 +489,14 @@ export async function registerLogin ({
489
489
  if (scope !== undefined) {
490
490
  throw Object.assign(new Error('registerLogin takes `caps` (account record permissions), not `scope`'), { code: 'use-caps' })
491
491
  }
492
- const pedidos = [...new Set(Array.isArray(caps) ? caps : [])]
493
- const raros = pedidos.filter((c) => !DEVICE_CAPS.includes(c))
494
- if (!pedidos.length || raros.length) {
495
- throw Object.assign(new Error(`not device permissions: ${raros.join(', ') || '(none)'} — expected any of ${DEVICE_CAPS.join(', ')}`), { code: 'bad-caps' })
492
+ const requests = [...new Set(Array.isArray(caps) ? caps : [])]
493
+ const oddOnes = requests.filter((c) => !DEVICE_CAPS.includes(c))
494
+ if (!requests.length || oddOnes.length) {
495
+ throw Object.assign(new Error(`not device permissions: ${oddOnes.join(', ') || '(none)'} — expected any of ${DEVICE_CAPS.join(', ')}`), { code: 'bad-caps' })
496
496
  }
497
497
  // El certificado lleva el scope de los permisos que lo tienen; los demás (`unattended`,
498
498
  // `passkeys`) viven solo en el acta, que es quien decide.
499
- const scopes = pedidos.map((c) => capScope(c)).filter(Boolean)
499
+ const scopes = requests.map((c) => capScope(c)).filter(Boolean)
500
500
  if (typeof identity?.admitMember !== 'function') {
501
501
  throw Object.assign(new Error('this vault cannot add devices to the account record: no login was created'), { code: 'admit-unavailable' })
502
502
  }
@@ -504,9 +504,9 @@ export async function registerLogin ({
504
504
  await logins.registerFinish({ user, upload, pub, encPub, deviceId, label, blob })
505
505
  try {
506
506
  const { cert } = await identity.signDelegation(pub, scopes, { label: label || `login:${user}` })
507
- await identity.admitMember({ pub, encPub, label: label || `login:${user}`, cn: null, caps: pedidos, cert })
507
+ await identity.admitMember({ pub, encPub, label: label || `login:${user}`, cn: null, caps: requests, cert })
508
508
  logins.setCert({ user, cert, iss: identity.me?.publickey || null })
509
- return { ok: true, user, deviceId, cert, caps: pedidos }
509
+ return { ok: true, user, deviceId, cert, caps: requests }
510
510
  } catch (e) {
511
511
  // NADA DE MEDIAS ALTAS: si no entra en el acta, no queda un usuario que pueda entrar a
512
512
  // una cuenta que no lo reconoce. Se deshace y se dice.
@@ -90,8 +90,8 @@ export const sameCommand = (a, b) => {
90
90
  /** El comando en una línea, para un log o una pantalla estrecha. */
91
91
  export function commandLine (ctx, max = 160) {
92
92
  const argv = Array.isArray(ctx?.argv) ? ctx.argv : []
93
- const linea = argv.length ? argv.join(' ') : (ctx?.exe || '')
94
- return linea.length > max ? linea.slice(0, max - 1) + '…' : linea
93
+ const line = argv.length ? argv.join(' ') : (ctx?.exe || '')
94
+ return line.length > max ? line.slice(0, max - 1) + '…' : line
95
95
  }
96
96
 
97
97
  export default { sanitizeContext, commandFingerprint, sameCommand, commandLine, trimArgv }