diff --git a/README.md b/README.md index 354dd41b..b7143856 100644 --- a/README.md +++ b/README.md @@ -742,11 +742,11 @@ Com `VARANDA_PHONE_KEY` definida, todo membro hospedado confirma um celular bras O que fica guardado: o `phone.json` no volume `account-data` (modo `0600`), com a chave do membro, o número selado (AES-256-GCM, preso à chave do membro), um índice com chave (HMAC) que serve para a unicidade e para os bloqueios, a data da verificação e, quando houver, o fim (`trocado`, `excluida`, `substituido`, `liberado`). O número nunca vai para os certificados, para a camada P2P, para respostas a outros membros, para os registros, para o painel de moderação nem para o `account export`. O serviço assina com a chave do emissor um atestado `phone-verified` (a chave do membro e a data, nunca o número), que o app guarda no nó, para a versão hospedada abrir sem rede; o atestado só é devolvido quando o serviço tem emissor (sem emissor, a verificação vale mas não vem atestado). Se a chave do emissor vazar e for revogada (`mod revoke-issuer`), os atestados que ela assinou também deixam de valer. -Backup: o `phone.json` e a `VARANDA_PHONE_KEY` vão juntos no backup, guardados em lugares separados. Perder a chave é perder todos os números e todos os bloqueios: o serviço falha fechado (o `phone.json` não abre, a etapa responde `indisponivel` e ninguém consegue se verificar) até a operação restaurar a chave certa. Trocar a chave não é suportado: com outra chave o arquivo não abre e nunca é regravado. +Backup: o `phone.json` e a `VARANDA_PHONE_KEY` vão juntos no backup, guardados em lugares separados. Perder a chave é perder todos os números e todos os bloqueios: o serviço falha fechado (o `phone.json` não abre, a etapa responde `indisponivel` e ninguém consegue se verificar) até a operação restaurar a chave certa. Trocar a chave não é suportado: com outra chave o arquivo não abre e nunca é regravado. O `phone.json` está na versão 2 (mapa `cleared`, #534): o serviço ainda abre um arquivo da versão 1, mas depois da primeira gravação na versão 2 um serviço anterior não o abre mais (a etapa responde `indisponivel`). Antes de atualizar, guarde um backup do arquivo, para poder voltar atrás. -Limites: 5 envios por membro por dia, 3 por número por dia, 60 s entre envios e o teto diário `VARANDA_PHONE_DAILY_LIMIT` (padrão 200, à parte para chaves vinculadas e não vinculadas). No dia em que os membros já vinculados passarem a verificar, suba o teto para esse dia. Um número já verificado por outra conta vinculada é recusado (`telefone-em-uso`); o de uma conta bloqueada pela moderação fica preso enquanto o bloqueio durar. +Limites: 5 envios por membro por dia, 3 por número por dia, 60 s entre envios e o teto diário `VARANDA_PHONE_DAILY_LIMIT` (padrão 200, à parte para chaves vinculadas e não vinculadas). No dia em que os membros já vinculados passarem a verificar, suba o teto para esse dia. Um número já verificado por outra conta vinculada é recusado (`telefone-em-uso`); o de uma conta bloqueada pela moderação fica preso enquanto o bloqueio durar. As tabelas desses limites e dos envios pendentes têm tamanho calculado a partir do teto diário e nunca apagam uma entrada ainda valendo: cheias, o envio recusa com `limite-telefone` e o registro mostra `tabela-cheia`. Limites aceitos pelo dono (2026-11-17, detalhes em `docs/design.md`): entre o envio e a conferência o número fica só na memória do serviço, sem cifra, por até 10 minutos; e, se o app não lê a política do celular e o nó ainda não guarda o atestado `phone-since`, o passo fica desligado naquela abertura. -Registros: o evento `telefone` traz só palavras fixas, nunca o número, o código ou a chave. Na partida, `ligada` ou `desligada`; `indisponivel` (o `phone.json` não abriu com esta chave, a verificação continua exigida e a etapa fica fechada); `arquivo-sem-chave` (há um `phone.json` mas a chave não está definida, então nenhuma retenção corre). Em uso: `enviado`, `verificado`, `em-uso`, `recusado-linha` (fixo, VoIP ou descartável), `tipo-desconhecido` (aceito, tipo de linha que o serviço não conhece), `teto-diario`, `armazenamento-indisponivel`, `gravacao-falhou`, `varredura-falhou`, `varredura-exclusao-falhou`, `resultado-desconhecido`, `didit-envio-bloqueado` e, para falhas do Didit, `didit-envio-` ou `didit-checagem-` seguido de `falha` (a resposta do Didit não foi aceita), `http-NNN`, `tempo`, `rede`, `formato` ou `entrada` (com `-campo-` para cada campo que o Didit apontou). Veja com `docker compose -f deploy/seeder/compose.yaml -f deploy/seeder/compose.web.yaml logs account | grep '"telefone"'`. +Registros: o evento `telefone` traz só palavras fixas, nunca o número, o código ou a chave. Na partida, `ligada` ou `desligada`; `indisponivel` (o `phone.json` não abriu com esta chave, a verificação continua exigida e a etapa fica fechada); `arquivo-sem-chave` (há um `phone.json` mas a chave não está definida, então nenhuma retenção corre). Em uso: `enviado`, `verificado`, `em-uso`, `recusado-linha` (fixo, VoIP ou descartável), `tipo-desconhecido` (aceito, tipo de linha que o serviço não conhece), `teto-diario`, `tabela-cheia`, `armazenamento-indisponivel`, `gravacao-falhou`, `varredura-falhou`, `varredura-exclusao-falhou`, `resultado-desconhecido`, `didit-envio-bloqueado` e, para falhas do Didit, `didit-envio-` ou `didit-checagem-` seguido de `falha` (a resposta do Didit não foi aceita), `http-NNN`, `tempo`, `rede`, `formato` ou `entrada` (com `-campo-` para cada campo que o Didit apontou). Veja com `docker compose -f deploy/seeder/compose.yaml -f deploy/seeder/compose.web.yaml logs account | grep '"telefone"'`. O comando `account phone --member ` mostra os números verificados de um membro, para uma ordem judicial ou para o pedido de acesso do próprio membro (LGPD). Precisa da `VARANDA_PHONE_KEY` no ambiente, roda só no servidor (pode rodar com o serviço no ar), não tem rota HTTP, não registra nada e imprime uma linha JSON `{ member, rows }`. Essa saída nunca é colada em issue, chat ou e-mail: entregue-a pelo canal que a ordem ou o pedido indicar. Quando a ordem traz um nome e não uma chave, `account phone --username ` (com ou sem `@`) acha a conta que teve o nome, atual ou passada: um nome que já foi de um membro nunca vai para outro, então sai no máximo uma linha JSON `{ username, key, kind, current, deletedAt, phone }`, com `kind` `membro` ou `excluido`, `current` dizendo se a conta ainda usa o nome e `phone` com as mesmas linhas do `--member` (lista vazia se não houver número). Para uma página (`kind` `pagina`) a linha traz `owner`, a chave de quem a tem, e nenhum número, e a `VARANDA_PHONE_KEY` não é lida; se o `pages.json` registra a mudança de chave da página, vem também `movedTo` (a dona é a da época da mudança), e uma página sem registro no `pages.json` dá "página sem registro em pages.json". Um nome que nunca foi emitido dá "nome não encontrado". @@ -786,7 +786,7 @@ Confira e anote: ##### Ordem judicial: desbloqueio e liberação do número -1. A conta ainda existe e a ordem levanta o bloqueio: rode `mod unblock ` num terminal (ele publica a lista). O número deixa de ficar preso na próxima varredura, na partida ou em até uma hora, e, se o bloqueio durou menos de 180 dias, o membro fica com a conta e com o número; passados os 180 dias o número selado já foi apagado e o membro precisa verificar de novo (`telefone-pendente`). Um membro bloqueado pela operação continua com o número preso mesmo depois de excluir a conta; só `mod unblock` (ou um recurso aceito) seguido de uma varredura o solta. +1. A conta ainda existe e a ordem levanta o bloqueio: rode `mod unblock ` num terminal (ele publica a lista). O número deixa de ficar preso na próxima varredura, na partida ou em até uma hora, e, se o bloqueio durou menos de 180 dias, o membro fica com a conta e com o número; passados os 180 dias o número selado já foi apagado e o membro precisa verificar de novo (`telefone-pendente`). Um membro bloqueado pela operação continua com o número preso mesmo depois de excluir a conta; só `mod unblock` (ou um recurso aceito) seguido de uma varredura o solta. Já um membro desbloqueado antes de excluir a conta não tem o número preso de novo pelas denúncias antigas: só uma denúncia decidida como bloquear depois do desbloqueio, ou um bloqueio ainda em vigor na exclusão, o prende. 2. A conta não pode voltar (a pessoa a excluiu, ou a ordem libera só o número): pare o serviço `account`, rode `account phone --release --member ` com a `VARANDA_PHONE_KEY` no ambiente e suba o serviço de novo. O comando toma a mesma trava do serviço, então recusa com o serviço no ar ("pare o serviço de conta antes de liberar um número"), imprime só `{ member, released: true, rows }`, nunca o número, e não mexe na moderação. Rodar de novo para confirmar é seguro: um membro já liberado responde com `alreadyReleased: true`, mesmo depois que a retenção apagou as linhas dele, e só uma chave sem número nem liberação dá "sem telefone registrado". Se a gravação falhar, a liberação pode ou não ter valido: confira com `account phone --member ` antes de rodar de novo e não conserte nem apague o `phone.json`. Depois disso o número pode ser confirmado por outra conta, a chave antiga continua bloqueada e o número selado fica guardado por até 180 dias. `account phone --member` precisa da chave do membro; `account reports --member` só filtra por uma chave que você já tem. Para descobrir a chave, use `account reports` sem `--member` (lista só quem foi denunciado) ou a lista pública de bloqueios (`mod show --json`), que traz também quem foi bloqueado sem denúncia. #### Páginas (opcional, serviço `account`) diff --git a/apps/app/App.js b/apps/app/App.js index 6668f547..44aa7545 100644 --- a/apps/app/App.js +++ b/apps/app/App.js @@ -4521,7 +4521,7 @@ function Member () { showToast(text) }} /> - setAjustes(null)} onInfo={ajustesInfo} termsInfo={termsInfo} onTermsReset={dropTermsAndSync} scheduledDeletion={scheduledDeletion} onDeletionChanged={refreshAccount} inviteNudge={inviteNudge} onOpenVarandinha={!deleteFromAviso && node.hosted === true && ownKey ? () => openVarandinha(ownKey) : undefined} onOpenPaginas={!deleteFromAviso && pagesOn({ hosted: node.hosted, accountOrigin: node.accountOrigin }) ? () => pushScreen({ screen: 'paginas' }) : undefined} node={node} member={member} phoneGate={phone.gate} phoneKey={phone.key} phoneChecking={phone.pending} phoneVerified={phone.state === 'verificado' && !phone.error} markVerified={markPhoneVerified} recheckPhone={recheckPhone} termsBeforeCreate={termsBeforeCreate} /> + setAjustes(null)} onInfo={ajustesInfo} termsInfo={termsInfo} onTermsReset={dropTermsAndSync} scheduledDeletion={scheduledDeletion} onDeletionChanged={refreshAccount} inviteNudge={inviteNudge} onOpenVarandinha={!deleteFromAviso && node.hosted === true && ownKey ? () => openVarandinha(ownKey) : undefined} onOpenPaginas={!deleteFromAviso && pagesOn({ hosted: node.hosted, accountOrigin: node.accountOrigin }) ? () => pushScreen({ screen: 'paginas' }) : undefined} node={node} member={member} phoneGate={phone.gate} phoneKey={phone.key} phoneChecking={phone.pending} phoneVerified={phone.state === 'verificado' && !phone.error} phoneProofDate={phone.proofDate} phoneKnownDate={phone.knownDate} markVerified={markPhoneVerified} recheckPhone={recheckPhone} termsBeforeCreate={termsBeforeCreate} /> {/* Mounted after the splash, so it wins: while the boot cover shows it follows the splash, which stays cream on native (Splash.js). */} diff --git a/apps/app/src/phone.js b/apps/app/src/phone.js index d6ceee67..ff82f30f 100644 --- a/apps/app/src/phone.js +++ b/apps/app/src/phone.js @@ -71,3 +71,50 @@ export function phoneErrorText (err) { export const PHONE_SENT_TEXT = 'Enviamos um código para o seu celular.' export const PHONE_UNCERTAIN_TEXT = 'Não deu para confirmar o envio. Se o código chegar, digite abaixo.' + +// A canonical ISO date (Date#toISOString), the shape of an attestation's +// date and of node.info's phoneVerifiedDate. +export function isIsoDate (s) { + if (typeof s !== 'string' || s.length !== 24) return false + const d = new Date(s) + return !Number.isNaN(d.getTime()) && d.toISOString() === s +} + +// Whether Ajustes shows 'Trocar o celular': an unlocked passkey account on a +// hosted node whose phone gate is open, for a known member (the shell's, +// which markVerified accepts a proof under). The same rule on the web page +// and on the app's in-app web node: both hold a passkey there. +export function phoneChangeShown ({ hosted, hasPasskey, unlocked, gate, member } = {}) { + return hosted === true && hasPasskey === true && unlocked === true && gate === 'ok' && typeof member === 'string' +} + +// Trocar o celular: the service never returns the number, only the date of +// the live verification in a 'verificado' answer's proof (a recorded number +// is a new row with a new date). `before` is the date known when the screen +// opened, `after` the answer's. A doubtful date proves nothing. +export function phoneChange (before, after) { + if (!isIsoDate(before) || !isIsoDate(after)) return 'unknown' + const a = Date.parse(after) + const b = Date.parse(before) + if (a > b) return 'changed' + if (a === b) return 'same' + return 'unknown' +} + +export const PHONE_CHANGED_TEXT = 'Celular atualizado.' +export const PHONE_SAME_TEXT = 'Esse já é o seu celular.' +export const PHONE_NOT_CHANGED_TEXT = 'O número ainda não mudou. Confirme o código de novo ou peça outro.' +export const PHONE_CHANGE_UNKNOWN_TEXT = 'Não deu para saber se o número mudou. Se precisar, troque de novo.' + +// via: 'send' (the service answered 'verificado' to a send: the number typed +// is already the member's live one, so no code went, whatever the dates +// say), 'check' (to a code) or 'recheck' (the status read after a check +// whose outcome was unknown). stay: the Trocar screen keeps its code field, +// since the service holds an approved code that a new check can still record. +export function phoneChangeOutcome ({ via, before, after } = {}) { + if (via === 'send') return { stay: false, text: PHONE_SAME_TEXT } + const change = phoneChange(before, after) + if (change === 'changed') return { stay: false, text: PHONE_CHANGED_TEXT } + if (change === 'same' && via === 'recheck') return { stay: true, text: PHONE_NOT_CHANGED_TEXT } + return { stay: false, text: PHONE_CHANGE_UNKNOWN_TEXT } +} diff --git a/apps/app/src/screens/Ajustes.js b/apps/app/src/screens/Ajustes.js index 8e3c785e..cd699f1e 100644 --- a/apps/app/src/screens/Ajustes.js +++ b/apps/app/src/screens/Ajustes.js @@ -89,6 +89,7 @@ import Identidade from './Identidade' import Passkeys from './Passkeys' import Perfil, { KeyboardForm } from './Perfil' import Telefone from './Telefone' +import { PHONE_CHANGE_UNKNOWN_TEXT, phoneChangeShown } from '../phone' import Recurso from './Recurso' import Bloqueados from './Bloqueados' import Aparelhos from './Aparelhos' @@ -195,7 +196,7 @@ function AccountCard ({ ownKey, profile, onPress }) { ) } -export default function Ajustes ({ screen, onNavigate, onClose, onInfo, termsInfo = null, onTermsReset, scheduledDeletion = null, onDeletionChanged, onOpenPaginas, onOpenVarandinha, inviteNudge = 0, node: nodeProp = null, member: gateMember = null, phoneGate = 'off', phoneKey = null, phoneChecking = false, phoneVerified = false, markVerified, recheckPhone, termsBeforeCreate = null }) { +export default function Ajustes ({ screen, onNavigate, onClose, onInfo, termsInfo = null, onTermsReset, scheduledDeletion = null, onDeletionChanged, onOpenPaginas, onOpenVarandinha, inviteNudge = 0, node: nodeProp = null, member: gateMember = null, phoneGate = 'off', phoneKey = null, phoneChecking = false, phoneVerified = false, phoneProofDate = null, phoneKnownDate = null, markVerified, recheckPhone, termsBeforeCreate = null }) { const styles = useStyles(makeStyles) const { colors, mode, setMode } = useTheme() const node = useNode() @@ -438,12 +439,11 @@ export default function Ajustes ({ screen, onNavigate, onClose, onInfo, termsInf // gateKey is the shell's phone-gate key: markVerified stores the proof only // for the session the request started under, which keeps the gate open. - // No proof means the sheet closed on a status recheck after a lost check: - // the status says 'verificado' for the old number too, so it cannot tell - // whether the new one was recorded. - const onPhoneVerified = (proof, key) => { + // text: Telefone's verdict from the proof dates (src/phone.js + // phoneChangeOutcome); without one, nothing tells the numbers apart. + const onPhoneVerified = (proof, key, text) => { if (typeof markVerified === 'function') markVerified(proof, key) - setSaved(proof === undefined ? 'Não deu para saber se o número mudou. Se precisar, troque de novo.' : 'Celular atualizado.') + setSaved(typeof text === 'string' && text !== '' ? text : PHONE_CHANGE_UNKNOWN_TEXT) onNavigate('lista') } const askPhoneAgain = typeof recheckPhone === 'function' ? recheckPhone : undefined @@ -487,7 +487,7 @@ export default function Ajustes ({ screen, onNavigate, onClose, onInfo, termsInf // Prefer the shell member: markVerified only accepts a proof under that key. const phoneMember = typeof gateMember === 'string' ? gateMember : member const phoneNode = nodeProp || node - const showChangePhone = account && phoneNode.hosted === true && unlocked && phoneGate === 'ok' && typeof phoneMember === 'string' + const showChangePhone = phoneChangeShown({ hosted: node.hosted === true && phoneNode.hosted === true, hasPasskey, unlocked, gate: phoneGate, member: phoneMember }) const { ui: pushUi, row: pushRow, trailing: pushTrailing, note: pushNote } = pushRowView({ push, pending: pushPending, error: pushError }) const inviting = account && policy !== null && policy.required === true const lines = versionLines({ app: BUILD, server }) @@ -727,6 +727,8 @@ export default function Ajustes ({ screen, onNavigate, onClose, onInfo, termsInf offline={phoneNode.online === false} statusBusy={phoneChecking} statusVerified={phoneVerified} + statusDate={phoneProofDate} + knownDate={phoneKnownDate} /> diff --git a/apps/app/src/screens/Telefone.js b/apps/app/src/screens/Telefone.js index 93c993f8..1157dd7f 100644 --- a/apps/app/src/screens/Telefone.js +++ b/apps/app/src/screens/Telefone.js @@ -10,7 +10,7 @@ import { useEffect, useRef, useState } from 'react' import { StyleSheet, Text, TextInput, View } from 'react-native' import { useNode } from '../node' -import { codeDigits, isCode } from '../phone' +import { codeDigits, isCode, phoneChangeOutcome } from '../phone' import { cellsOf, shouldAutoSubmit } from '../phoneEntry' import { STEP_HINTS, STEP_TITLES } from '../onboarding' import { usePhoneVerify } from '../usePhoneVerify' @@ -151,12 +151,28 @@ function CodeInput ({ label, value, onChangeText, editable, onSubmitEditing }) { // answered 'verificado'. After an uncertain check the screen holds Confirmar // until that read answers, and a 'verificado' then takes the onVerified path // (proofless, under the key the check started with). -export default function Telefone ({ mode = 'setup', member, gateKey, onVerified, onUncertain, onDropped, offline = false, checking = false, checkError = '', onRecheck, statusBusy = false, statusVerified = false, index = 1, total = 3 }) { +// Mode 'trocar' only: knownDate is the date of the member's verification +// when the screen opened and statusDate the proof date of that read's +// answer. onVerified gets a third argument, the text for Ajustes from +// phoneChangeOutcome (src/phone.js), since the service never says which +// number it holds. A recheck that shows the old date keeps the screen. +export default function Telefone ({ mode = 'setup', member, gateKey, onVerified, onUncertain, onDropped, offline = false, checking = false, checkError = '', onRecheck, statusBusy = false, statusVerified = false, statusDate = null, knownDate = null, index = 1, total = 3 }) { const node = useNode() const verify = usePhoneVerify({ node, member, gateKey, onDropped }) const styles = useStyles(makeStyles) const [phone, setPhone] = useState('') const [code, setCode] = useState('') + // Read once: a proof stored while the screen is open must not move it. + const [before] = useState(knownDate) + // The recheck showed the old date: the approved code can still be recorded. + const [notChanged, setNotChanged] = useState('') + const verified = (proof, key, via, after) => { + if (!onVerified) return + if (mode !== 'trocar') return onVerified(proof, key) + const outcome = phoneChangeOutcome({ via, before, after }) + if (outcome.stay) setNotChanged(outcome.text) + else onVerified(proof, key, outcome.text) + } // The gate key an uncertain check started under, until the recheck answers. const [awaiting, setAwaiting] = useState(null) const sawBusy = useRef(false) @@ -190,8 +206,8 @@ export default function Telefone ({ mode = 'setup', member, gateKey, onVerified, const answered = sawBusy.current sawBusy.current = false setAwaiting(null) - if (answered && statusVerified && onVerified) onVerified(undefined, awaiting) - }, [awaiting, gateKey, checkError, statusBusy, statusVerified]) + if (answered && statusVerified) verified(undefined, awaiting, 'recheck', statusDate) + }, [awaiting, gateKey, checkError, statusBusy, statusVerified, statusDate]) // A new gate drops every answer started before (usePhoneVerify), so no // request or code from the old one holds the new one. useEffect(() => { @@ -199,10 +215,10 @@ export default function Telefone ({ mode = 'setup', member, gateKey, onVerified, lastChecked.current = null }, [gateKey]) - const finish = (r) => { + const finish = (r, via) => { if (r === null) return if (r.state === 'verificado') { - if (onVerified) onVerified(r.proof, r.key) + verified(r.proof, r.key, via, r.proof && typeof r.proof === 'object' ? r.proof.date : undefined) } else if (r.uncertain === true && onUncertain) { onUncertain() } @@ -210,10 +226,11 @@ export default function Telefone ({ mode = 'setup', member, gateKey, onVerified, const send = async () => { const mine = {} if (inFlight.current === null) inFlight.current = mine + setNotChanged('') try { const r = await verify.send(phone) if (r !== null && (r.state === 'enviado' || r.state === 'verificado')) setCode('') - finish(r) + finish(r, 'send') } finally { if (inFlight.current === mine) inFlight.current = null } @@ -225,10 +242,11 @@ export default function Telefone ({ mode = 'setup', member, gateKey, onVerified, const mine = {} inFlight.current = mine lastChecked.current = candidate + setNotChanged('') try { const r = await verify.check(candidate) if (r !== null && r.uncertain === true) setAwaiting(r.key) - finish(r) + finish(r, 'check') } finally { if (inFlight.current === mine) inFlight.current = null } @@ -247,6 +265,7 @@ export default function Telefone ({ mode = 'setup', member, gateKey, onVerified, lastChecked.current = null inFlight.current = null setAwaiting(null) + setNotChanged('') setCode('') verify.reset() } @@ -278,7 +297,9 @@ export default function Telefone ({ mode = 'setup', member, gateKey, onVerified, {verify.sent ? : null} - {verify.error} + {/* It replaces the uncertain check's error, which it answers. */} + {notChanged ? {notChanged} : null} + {notChanged ? '' : verify.error} {offline ? {OFFLINE_TEXT} : null} ) diff --git a/apps/app/src/usePhoneGate.js b/apps/app/src/usePhoneGate.js index 4eeec4b7..02b81e0c 100644 --- a/apps/app/src/usePhoneGate.js +++ b/apps/app/src/usePhoneGate.js @@ -14,18 +14,14 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { phonePolicy as readPhonePolicy, phoneSince as readPhoneSince, phoneStart, phoneStatus } from './account' import { installationOrigin } from './installation' -import { phoneGate, phoneReadAllowed } from './phone.js' +import { isIsoDate, phoneGate, phoneReadAllowed } from './phone.js' + +export { isIsoDate } export const phoneRetryDelay = (n) => (n === 0 ? 5000 : n === 1 ? 15000 : 60000) // The node.info read the gate waits on, as the age step's in App.js. export const phoneInfoDelay = (n) => (n === 0 ? 2000 : n === 1 ? 5000 : n === 2 ? 15000 : 30000) -export function isIsoDate (s) { - if (typeof s !== 'string' || s.length !== 24) return false - const d = new Date(s) - return !Number.isNaN(d.getTime()) && d.toISOString() === s -} - // Pure: what node.info says for this member only (an info read for another // key, or none yet, proves nothing). export function phoneProofs (info, member) { @@ -126,6 +122,9 @@ export function usePhoneGate ({ node, info, hosted, ready, termsOk, locked, memb lockedRef.current = locked const [answer, setAnswer] = useState(null) const state = answer !== null && answer.key === key ? answer.state : undefined + // The date of the proof in the latest 'verificado' this gate took for this + // key (a status read or markVerified), or null. + const proofDate = answer !== null && answer.key === key && typeof answer.date === 'string' ? answer.date : null const [checkTick, setCheckTick] = useState(0) const readKey = key + '#' + checkTick const readKeyRef = useRef(readKey) @@ -143,8 +142,13 @@ export function usePhoneGate ({ node, info, hosted, ready, termsOk, locked, memb // The only sender of a phone-verified attestation and of its clearing: a // service answer for the member and installation the request started with. - const take = (k, who, st, proof) => { - setAnswer({ key: k, state: st }) + // The proof's date rides along: Trocar o celular compares it with the date + // known before (src/phone.js phoneChangeOutcome). + // keep: a proofless markVerified (the screen closing on a status recheck) + // leaves the date that read brought. + const take = (k, who, st, proof, keep = false) => { + const date = st === 'verificado' && isProof(proof) && isIsoDate(proof.date) ? proof.date : null + setAnswer((cur) => ({ key: k, state: st, date: date === null && keep && cur !== null && cur.key === k ? cur.date : date })) if (st === 'verificado' && isProof(proof)) queueProof(k, who, proof) else if (st === 'nenhum') queueProof(k, who, null) else if (st === 'verificado') setProofOp((cur) => (cur !== null && cur.verified === null && cur.member === who ? null : cur)) @@ -250,7 +254,7 @@ export function usePhoneGate ({ node, info, hosted, ready, termsOk, locked, memb if (startedKey !== keyRef.current || lockedRef.current) return seq.current += 1 setFailure(null) - take(startedKey, memberRef.current, 'verificado', proof) + take(startedKey, memberRef.current, 'verificado', proof, true) }, []) // --- the installation's signed since, handed to the node --- @@ -338,6 +342,10 @@ export function usePhoneGate ({ node, info, hosted, ready, termsOk, locked, memb // policy read keeps the step in the meantime. const sinceAccepted = sinceUnseen && sinceShown.since !== null const gate = phoneGate({ hosted, policy: gatePolicy, state, vouched: proofs.vouched && !clearPending, sinceHeld: proofs.sinceHeld || sinceAccepted }) + // The date Trocar o celular starts from: the service's latest proof for + // this key, else the one node.info reports for this member (verified by + // the node against the issuer) when the status read gave none. + const knownDate = proofDate !== null ? proofDate : (proofs.vouched && !clearPending ? info.phoneVerifiedDate : null) const error = failure !== null && failure.key === readKey ? failure.err : null // A status read for the current key has not finished, or the policy is // still unknown (its read is retried; the status cannot be asked before). @@ -376,5 +384,5 @@ export function usePhoneGate ({ node, info, hosted, ready, termsOk, locked, memb setInfoTick((n) => n + 1) }, [online, infoNow]) - return { gate, state, error, pending, key, recheck, markVerified } + return { gate, state, error, pending, key, proofDate, knownDate, recheck, markVerified } } diff --git a/apps/app/test/phone.test.js b/apps/app/test/phone.test.js index 391e3778..05078609 100644 --- a/apps/app/test/phone.test.js +++ b/apps/app/test/phone.test.js @@ -206,3 +206,86 @@ test('phone texts and phoneErrorText', async (t) => { t.absent(text.includes(String.fromCharCode(0x2014)), text) } }) + +const OLD = '2026-11-11T12:00:00.000Z' +const NEW = '2026-11-17T09:30:00.000Z' + +test('phoneChange: a later proof date is a new number, the same date is not', async (t) => { + const { phoneChange } = await load() + t.is(phoneChange(OLD, NEW), 'changed') + t.is(phoneChange(OLD, '2026-11-11T12:00:00.001Z'), 'changed', 'one millisecond later') + t.is(phoneChange(OLD, OLD), 'same') + t.is(phoneChange(NEW, OLD), 'unknown', 'an older answer proves nothing') +}) + +test('phoneChange: a missing or non-canonical date is unknown', async (t) => { + const { phoneChange } = await load() + for (const bad of [undefined, null, '', '2026-11-11T12:00:00Z', '2026-11-11', '2026-02-30T12:00:00.000Z', Date.parse(OLD), {}, ' ' + OLD.slice(1)]) { + t.is(phoneChange(bad, NEW), 'unknown', 'before ' + String(bad)) + t.is(phoneChange(OLD, bad), 'unknown', 'after ' + String(bad)) + } + t.is(phoneChange(), 'unknown') +}) + +test('phoneChangeOutcome: what Trocar o celular says after each answer', async (t) => { + const { phoneChangeOutcome, PHONE_CHANGED_TEXT, PHONE_SAME_TEXT, PHONE_NOT_CHANGED_TEXT, PHONE_CHANGE_UNKNOWN_TEXT } = await load() + t.is(PHONE_CHANGED_TEXT, 'Celular atualizado.') + t.is(PHONE_SAME_TEXT, 'Esse já é o seu celular.') + t.is(PHONE_NOT_CHANGED_TEXT, 'O número ainda não mudou. Confirme o código de novo ou peça outro.') + t.is(PHONE_CHANGE_UNKNOWN_TEXT, 'Não deu para saber se o número mudou. Se precisar, troque de novo.') + for (const via of ['check', 'recheck']) { + t.alike(phoneChangeOutcome({ via, before: OLD, after: NEW }), { stay: false, text: PHONE_CHANGED_TEXT }, via + ': changed') + t.alike(phoneChangeOutcome({ via, before: OLD, after: undefined }), { stay: false, text: PHONE_CHANGE_UNKNOWN_TEXT }, via + ': no proof') + t.alike(phoneChangeOutcome({ via, before: null, after: NEW }), { stay: false, text: PHONE_CHANGE_UNKNOWN_TEXT }, via + ': nothing known before') + } + // The service answers a send with 'verificado' only for the member's live + // number: a newer date there is a change made elsewhere, not by this send. + for (const [before, after] of [[OLD, OLD], [OLD, NEW], [OLD, undefined], [null, NEW]]) { + t.alike(phoneChangeOutcome({ via: 'send', before, after }), { stay: false, text: PHONE_SAME_TEXT }, 'the number typed is already the member\'s: ' + String(before) + ' ' + String(after)) + } + t.alike(phoneChangeOutcome({ via: 'recheck', before: OLD, after: OLD }), { stay: true, text: PHONE_NOT_CHANGED_TEXT }, 'a lost check that recorded nothing keeps the screen') + t.alike(phoneChangeOutcome({ via: 'check', before: OLD, after: OLD }), { stay: false, text: PHONE_CHANGE_UNKNOWN_TEXT }, 'a check never records the old date: doubtful') + t.alike(phoneChangeOutcome(), { stay: false, text: PHONE_CHANGE_UNKNOWN_TEXT }) + for (const text of [PHONE_CHANGED_TEXT, PHONE_SAME_TEXT, PHONE_NOT_CHANGED_TEXT, PHONE_CHANGE_UNKNOWN_TEXT]) { + t.absent(text.includes(String.fromCharCode(0x2014)), text) + t.absent(/[0-9]/.test(text), 'never a number: ' + text) + } +}) + +test('phoneChangeShown: Trocar o celular for a linked, unlocked account behind an open gate', async (t) => { + const { phoneChangeShown } = await load() + const M = 'a'.repeat(64) + const linked = { hosted: true, hasPasskey: true, unlocked: true, gate: 'ok', member: M } + t.is(phoneChangeShown(linked), true, 'a linked account sees it') + for (const gate of ['off', 'loading', 'needed', undefined, 'OK']) { + t.is(phoneChangeShown({ ...linked, gate }), false, 'gate ' + String(gate)) + } + t.is(phoneChangeShown({ ...linked, unlocked: false }), false, 'locked') + t.is(phoneChangeShown({ ...linked, hosted: false }), false, 'not hosted (a hand-typed configuration)') + t.is(phoneChangeShown({ ...linked, hasPasskey: false }), false, 'no passkey account') + t.is(phoneChangeShown({ ...linked, member: null }), false, 'no member known') + for (const v of [1, 'true', null]) { + t.is(phoneChangeShown({ ...linked, hosted: v }), false, 'hosted ' + String(v)) + t.is(phoneChangeShown({ ...linked, unlocked: v }), false, 'unlocked ' + String(v)) + } + t.is(phoneChangeShown(), false) +}) + +test('Ajustes and Telefone use the pure rules for Trocar o celular', (t) => { + const fs = require('fs') + const path = require('path') + const read = (f) => fs.readFileSync(path.join(__dirname, '../src/screens', f), 'utf8') + const ajustes = read('Ajustes.js') + t.ok(ajustes.includes('const showChangePhone = phoneChangeShown({ hosted: node.hosted === true && phoneNode.hosted === true, hasPasskey, unlocked, gate: phoneGate, member: phoneMember })')) + t.ok(ajustes.includes('statusDate={phoneProofDate}') && ajustes.includes('knownDate={phoneKnownDate}')) + t.ok(ajustes.includes("setSaved(typeof text === 'string' && text !== '' ? text : PHONE_CHANGE_UNKNOWN_TEXT)")) + t.absent(ajustes.includes("'Celular atualizado.'"), 'the verdict comes from Telefone') + const telefone = read('Telefone.js') + t.ok(telefone.includes('const [before] = useState(knownDate)'), 'the date before is read once, when the screen opens') + t.ok(telefone.includes("if (answered && statusVerified) verified(undefined, awaiting, 'recheck', statusDate)")) + t.ok(telefone.includes("finish(r, 'send')") && telefone.includes("finish(r, 'check')")) + t.ok(telefone.includes('if (mode !== \'trocar\') return onVerified(proof, key)'), 'the setup step is unchanged') + t.ok(telefone.includes('if (outcome.stay) setNotChanged(outcome.text)')) + const app = fs.readFileSync(path.join(__dirname, '../App.js'), 'utf8') + t.ok(app.includes('phoneProofDate={phone.proofDate} phoneKnownDate={phone.knownDate}')) +}) diff --git a/apps/app/test/phoneEntry.test.js b/apps/app/test/phoneEntry.test.js index 6ad8d1f8..f91d0754 100644 --- a/apps/app/test/phoneEntry.test.js +++ b/apps/app/test/phoneEntry.test.js @@ -151,7 +151,7 @@ test('Telefone: a completed code is checked once from the edit, never from an ef t.ok(check.indexOf('inFlight.current = mine') < check.indexOf('await verify.check(candidate)')) t.ok(check.includes('if (inFlight.current === mine) inFlight.current = null')) t.ok(check.includes('if (r !== null && r.uncertain === true) setAwaiting(r.key)')) - t.ok(code.includes("import { codeDigits, isCode } from '../phone'")) + t.ok(code.includes("import { codeDigits, isCode, phoneChangeOutcome } from '../phone'")) t.ok(code.includes('const confirm = () => {\n if (!canConfirm) return\n checkCode(code.trim())\n }'), 'Enter does no more than the button') t.ok(code.includes('const codeLocked = locked || awaiting !== null')) t.ok(code.includes('const canConfirm = !codeLocked && code.trim().length === 6')) diff --git a/apps/app/test/usePhoneGate.test.js b/apps/app/test/usePhoneGate.test.js index 0e8c0fc0..37ccccec 100644 --- a/apps/app/test/usePhoneGate.test.js +++ b/apps/app/test/usePhoneGate.test.js @@ -701,3 +701,61 @@ test('an accepted clear keeps masking the vouch until node.info shows it', async await tick() t.is(r.out.gate, 'ok', 'once shown, the mask is gone (a later proof vouches again)') }) + +// Trocar o celular (src/phone.js phoneChangeOutcome) compares these dates. +const NEW_DATE = '2026-11-17T09:30:00.000Z' +const dated = (date) => ({ ...PROOF, date }) + +test('proofDate: the date of the latest verificado proof, for this key only', async (t) => { + let answer = { state: 'verificado', proof: dated(DATE) } + const { r } = await mount(t, { + phonePolicy: async () => ({ required: true }), + phoneStatus: async () => answer + }) + t.is(r.out.proofDate, DATE, 'the status read\'s proof') + t.is(r.out.knownDate, DATE) + r.out.markVerified(dated(NEW_DATE), r.out.key) + await tick() + t.is(r.out.proofDate, NEW_DATE, 'a recorded number moves it') + t.is(r.out.knownDate, NEW_DATE) + answer = { state: 'verificado' } + r.out.recheck() + await tick() + t.is(r.out.proofDate, null, 'a verificado without a proof (no issuer) has no date') + answer = { state: 'verificado', proof: dated('2026-11-17T09:30:00Z') } + r.out.recheck() + await tick() + t.is(r.out.proofDate, null, 'a non-canonical date is no date') + answer = { state: 'verificado', proof: dated(DATE) } + r.out.recheck() + await tick() + t.is(r.out.proofDate, DATE) + r.out.markVerified(undefined, r.out.key) + await tick() + t.is(r.out.proofDate, DATE, 'a proofless markVerified keeps the date the recheck read') + r.rerender({ generation: 2 }) + t.is(r.out.proofDate, null, 'an answer under another key gives none') +}) + +test('knownDate: node.info\'s date for this member when the status gave none', async (t) => { + const err = Object.assign(new Error('serviço indisponível'), { code: 'indisponivel' }) + const failing = { phonePolicy: async () => ({ required: true }), phoneStart: async () => { throw err } } + const vouched = await mount(t, failing, { info: { publicKey: M, phoneVerifiedDate: DATE, phoneSince: null } }) + t.is(vouched.r.out.gate, 'ok') + t.is(vouched.r.out.proofDate, null) + t.is(vouched.r.out.knownDate, DATE, 'the node\'s proof') + const other = await mount(t, failing, { info: { publicKey: OTHER, phoneVerifiedDate: DATE, phoneSince: null } }) + t.is(other.r.out.knownDate, null, 'node.info of another key') + const odd = await mount(t, failing, { info: { publicKey: M, phoneVerifiedDate: '2026-11-11', phoneSince: null } }) + t.is(odd.r.out.knownDate, null, 'a non-canonical date') + const fresher = await mount(t, { + phonePolicy: async () => ({ required: true }), + phoneStatus: async () => ({ state: 'verificado', proof: dated(NEW_DATE) }) + }, { info: { publicKey: M, phoneVerifiedDate: DATE, phoneSince: null } }) + t.is(fresher.r.out.knownDate, NEW_DATE, 'the service\'s answer wins over the node\'s copy') + const cleared = await mount(t, { + phonePolicy: async () => ({ required: true }), + phoneStatus: async () => ({ state: 'nenhum' }) + }, { info: { publicKey: M, phoneVerifiedDate: DATE, phoneSince: null } }) + t.is(cleared.r.out.knownDate, null, 'a nenhum masks the node\'s old proof') +}) diff --git a/apps/cli/lib/account/age-routes.js b/apps/cli/lib/account/age-routes.js index b515890d..be49c268 100644 --- a/apps/cli/lib/account/age-routes.js +++ b/apps/cli/lib/account/age-routes.js @@ -7,6 +7,7 @@ const { isCanonicalIso } = require('@varanda/core/lib/cert') const { inviteId, CODE_RE } = require('./invites-store') const { staleUnlinked, AGE_UNLINKED_TTL_MS } = require('./age-store') const { isAppRequest, ageReturnUrl } = require('./app-return') +const { createStartNonces, MAX_SPENT } = require('./start-nonces') // Hosted age verification with Didit (mounted by ./server.js): // @@ -37,9 +38,10 @@ const { isAppRequest, ageReturnUrl } = require('./app-return') // at most every 30 s), and each failure is logged once per episode. A // separate route because installed apps parse the policy strictly. // - start mints a single-use nonce for a member key with no proof and no -// directory link (the key may be a fresh passkey that is not linked yet), -// bounded like the other unsigned starts by its table and the global -// bucket. +// directory link (the key may be a fresh passkey that is not linked yet). +// The nonce is stateless (./start-nonces.js): start stores nothing, so a +// flood of unsigned starts cannot push out a member's unspent nonce; only +// the global bucket bounds it. // - session and result each need the member's diary-key proof over that // nonce (packages/core/lib/age.js), action-bound, the nonce spent first. // session opens one paid Didit session per member and client (web or @@ -83,8 +85,6 @@ const { isAppRequest, ageReturnUrl } = require('./app-return') // signature as the web does. const MAX_BODY = 4096 -const NONCE_TTL_MS = 600 * 1000 -const MAX_NONCES = 1000 const URL_REUSE_MS = 3600 * 1000 const SESSION_TTL_MS = 24 * 3600 * 1000 const MAX_SESSIONS = 10000 @@ -101,7 +101,6 @@ function rawPath (req) { return q === -1 ? target : target.slice(0, q) } const HEX64_RE = /^[0-9a-f]{64}$/ -const TOKEN_RE = /^[A-Za-z0-9_-]{43}$/ const LOG_TOKEN_RE = /^[a-z0-9_-]{1,48}$/ // Only a 4xx from the provider (it refused the request) or our own input check // proves no session was created; after a timeout, a dropped connection, a 5xx @@ -152,6 +151,8 @@ function createAgeRoutes ({ now = Date.now, http, dailyLimit = 200, + // Spent start nonces kept (./server.js sizes it from its token bucket). + maxSpent = MAX_SPENT, since = null, issuer = null, ageCheck = null, @@ -203,8 +204,7 @@ function createAgeRoutes ({ since: fixedWindow(6000, 60 * 1000, now) } - // nonce -> { member, expiresAt }, single-use, the oldest evicted for room. - const nonces = new Map() + const nonces = createStartNonces({ label: 'varanda-age-start-v1', now, max: maxSpent }) // slot -> { sessionId, url, createdAt }, the oldest evicted for room. A // slot is the member and the client kind (see slotOf): the return URL is // fixed when the session is created, so a web session is never handed to @@ -313,7 +313,6 @@ function createAgeRoutes ({ function sweep () { const t = now() - for (const [k, v] of nonces) if (v.expiresAt <= t) nonces.delete(k) // An abandoned session still holds images at the provider: drop it there too. for (const [k, v] of sessions) { if (t - v.createdAt >= SESSION_TTL_MS) { @@ -323,14 +322,12 @@ function createAgeRoutes ({ } } - // Spends the nonce before anything else, then checks the member, the - // expiry and the signature for `action`. + // Spends the nonce (minted for this member, live and unspent) before + // anything else, then checks the signature for `action`. function prove (body, action) { const member = memberParam(body.member) - const nonce = typeof body.nonce === 'string' && TOKEN_RE.test(body.nonce) ? body.nonce : null - const row = nonce === null ? undefined : nonces.get(nonce) - if (nonce !== null) nonces.delete(nonce) - if (row === undefined || row.member !== member || row.expiresAt <= now()) throw refuse('expirado') + const nonce = body.nonce + if (!nonces.spend(member, nonce)) throw refuse('expirado') if (!verifyAge({ action, nonce, member, association }, body.signature).ok) throw refuse('assinatura-invalida') return member } @@ -484,10 +481,7 @@ function createAgeRoutes ({ available() const member = memberParam(body.member) sweep() - while (nonces.size >= MAX_NONCES) nonces.delete(nonces.keys().next().value) - const nonce = nodeCrypto.randomBytes(32).toString('base64url') - nonces.set(nonce, { member, expiresAt: now() + NONCE_TTL_MS }) - send(res, 200, { nonce }) + send(res, 200, { nonce: nonces.mint(member) }) } // A key that deleted its account (Excluir conta) never links again, so it @@ -688,7 +682,7 @@ function createAgeRoutes ({ // Sizes only, never a nonce, a session id or a URL. function stats () { - return { nonces: nonces.size, sessions: sessions.size } + return { nonces: nonces.size(), sessions: sessions.size } } return { owns, handle, required, verified, stats, sweepRecords } diff --git a/apps/cli/lib/account/moderation-store.js b/apps/cli/lib/account/moderation-store.js index 310eb7a3..f5077ed3 100644 --- a/apps/cli/lib/account/moderation-store.js +++ b/apps/cli/lib/account/moderation-store.js @@ -1253,6 +1253,33 @@ function openModerationStore (dataDir, { now = Date.now, association } = {}) { })) } + // Read-only, for the phone rule: is `member` in the published list, or + // does any change for it still wait for the operator? Excluir conta's own + // block (by OWNER_ACTOR) counts too: a 'bloquear' decided while it waits + // joins it. An unblock still waiting does not let go of a number, even + // next to the claimed block it lifts: it may be cancelled, and the burn + // itself is only lifted by the published list. An invalid member is false. + function held (member) { + usable() + if (!isLowerHex(member, 32)) return false + if (blockedSet(state.published.snapshot).has(member)) return true + return state.pending.some((c) => c.member === member) + } + + // Read-only: how many 'bloquear' reports blocked `member` with a decision + // at or after `since` (canonical ISO, so strings compare in time order), + // or all of them when `since` is null. An invalid member is 0. + function blockReportsAfter (member, since) { + usable() + if (since !== null && !isCanonicalIso(since)) throw new TypeError('since must be null or a canonical ISO date') + if (!isLowerHex(member, 32)) return 0 + let n = 0 + for (const r of Object.values(state.reports)) { + if (r.status === 'bloquear' && blockedKey(r) === member && (since === null || r.decidedAt >= since)) n++ + } + return n + } + function stats () { usable() let open = 0 @@ -1331,7 +1358,7 @@ function openModerationStore (dataDir, { now = Date.now, association } = {}) { return false } - return { add, addDm, anexoOf, list, get, addAppeal, listAppeals, getAppeal, blockedBy, decideAppeal, decide, reopen, reopenedIds, unblock, requestDeletion, cancel, pending, pull, ack, newestModeratorDate, blocked, groupKeys, stats, exportRows, humanReversed } + return { add, addDm, anexoOf, list, get, addAppeal, listAppeals, getAppeal, blockedBy, decideAppeal, decide, reopen, reopenedIds, unblock, requestDeletion, cancel, pending, pull, ack, newestModeratorDate, blocked, held, blockReportsAfter, groupKeys, stats, exportRows, humanReversed } } module.exports = { diff --git a/apps/cli/lib/account/phone-routes.js b/apps/cli/lib/account/phone-routes.js index 153378b4..ca166bb4 100644 --- a/apps/cli/lib/account/phone-routes.js +++ b/apps/cli/lib/account/phone-routes.js @@ -4,6 +4,7 @@ const nodeCrypto = require('node:crypto') const { verifyPhone, isBrMobile } = require('@varanda/core/lib/phone') const { createPhoneVerified, createPhoneSince } = require('@varanda/core/lib/phone-proof') const { ceiling } = require('./age-routes') +const { createStartNonces, MAX_SPENT } = require('./start-nonces') // Hosted verification of a Brazilian mobile number with Didit (mounted by // ./server.js), modelled on ./age-routes.js: @@ -16,8 +17,9 @@ const { ceiling } = require('./age-routes') // tell offline that the association requires a verified number. It // never vouches for a certificate. A store that cannot answer is a 503, // never null: null tells the node to drop the one it holds. -// - start mints a single-use nonce for a member key; it reads no state and -// reveals nothing. +// - start mints a single-use nonce for a member key (./start-nonces.js); +// it reads no state, stores nothing and reveals nothing, so a flood of +// unsigned starts cannot push out a member's unspent nonce. // - send, check and status each need the member's diary-key proof over // that nonce (packages/core/lib/phone.js), action-bound, the nonce spent // first. send asks the provider to text a code, check hands the code to @@ -38,12 +40,14 @@ const { ceiling } = require('./age-routes') // asks for a new code. No answer and no log line carries the number, a mask, // its index, the code, a provider id or a member key. Logs carry only // { event, reason }. +// +// No table here evicts a live entry to make room, since that would reset a +// window or drop someone's code: each send is charged to one of the two daily +// ceilings, so the keys a table can hold are bounded (see maxKeysFor), and a +// table still full of live entries refuses the send before the provider call. const MAX_BODY = 4096 -const NONCE_TTL_MS = 600 * 1000 -const MAX_NONCES = 1000 const PENDING_TTL_MS = 600 * 1000 -const MAX_PENDING = 10000 const RESEND_MS = 60 * 1000 const MAX_ATTEMPTS = 3 const DAY_MS = 24 * 3600 * 1000 @@ -51,7 +55,6 @@ const SWEEP_MS = 3600 * 1000 const SINCE_RESIGN_MS = 60 * 1000 const HEX64_RE = /^[0-9a-f]{64}$/ -const TOKEN_RE = /^[A-Za-z0-9_-]{43}$/ const CODE_RE = /^[0-9]{6}$/ const LOG_TOKEN_RE = /^[a-z0-9_-]{1,48}$/ @@ -68,10 +71,21 @@ function sameIndex (a, b) { return x.length === y.length && nodeCrypto.timingSafeEqual(x, y) } +// Every send that charges a keyed window or fills pending and lastSent is +// first charged to dailyNew or dailyLinked, two fixed windows of dailyLimit, +// and any 24-hour interval meets at most two windows of each: at most +// 4 * dailyLimit keys are ever live. +function maxKeysFor (dailyLimit) { + return 4 * dailyLimit +} + // A keyed fixed window that can be checked without spending it, so a request -// refused by one window never spends another. At most `max` live keys, the -// expired windows then the oldest evicted for room. -function keyedCeiling (limit, windowMs, now, max = 10000) { +// refused by one window never spends another. At most `max` live keys: a live +// window is never evicted (that would reset someone's limit), so has() answers +// false for a new key while the table is full of live windows. take() follows +// a has() that answered true, in the same tick. +function keyedCeiling (limit, windowMs, now, max) { + if (!Number.isSafeInteger(max) || max < 1) throw new TypeError('max must be a positive integer') const windows = new Map() function current (key) { const w = windows.get(key) @@ -84,20 +98,23 @@ function keyedCeiling (limit, windowMs, now, max = 10000) { return { has (key) { const w = current(key) - return w === undefined || w.count < limit + if (w !== undefined) return w.count < limit + if (windows.size >= max) { + const t = now() + for (const [k, v] of windows) if (t - v.start >= windowMs) windows.delete(k) + } + return windows.size < max }, take (key) { let w = current(key) if (w === undefined) { - const t = now() - if (windows.size >= max) { - for (const [k, v] of windows) if (t - v.start >= windowMs) windows.delete(k) - if (windows.size >= max) windows.delete(windows.keys().next().value) - } - w = { start: t, count: 0 } + w = { start: now(), count: 0 } windows.set(key, w) } w.count++ + }, + size () { + return windows.size } } } @@ -113,20 +130,29 @@ function createPhoneRoutes ({ deleted, burnable, blocked = () => false, + cleared = () => false, issuer = null, log = () => {}, now = Date.now, http, - dailyLimit = 200 + dailyLimit = 200, + // Spent start nonces kept (./server.js sizes it from its token bucket). + maxSpent = MAX_SPENT, + // Tests only: smaller bounds than maxKeysFor(dailyLimit). + maxWindows = null, + maxPending = null }) { const { send, readJsonBody, checkPost, RouteError, refuse, keyedWindow, fixedWindow } = http if (client !== null && (typeof client.send !== 'function' || typeof client.check !== 'function')) { throw new TypeError('phoneClient inválido') } - for (const [name, fn] of [['ageVerified', ageVerified], ['linked', linked], ['deleted', deleted], ['burnable', burnable], ['blocked', blocked]]) { + for (const [name, fn] of [['ageVerified', ageVerified], ['linked', linked], ['deleted', deleted], ['burnable', burnable], ['blocked', blocked], ['cleared', cleared]]) { if (typeof fn !== 'function') throw new TypeError(name + ' must be a function') } if (!Number.isSafeInteger(dailyLimit) || dailyLimit < 1) throw new TypeError('phoneDailyLimit must be a positive integer') + const windowBound = maxWindows ?? maxKeysFor(dailyLimit) + const pendingBound = maxPending ?? maxKeysFor(dailyLimit) + if (!Number.isSafeInteger(pendingBound) || pendingBound < 1) throw new TypeError('maxPending must be a positive integer') if (issuer !== null && (typeof issuer !== 'object' || !issuer.keyPair || !issuer.cert)) throw new TypeError('issuer must be { keyPair, cert } or null') // A store that failed to open is still on: the gates then stay shut @@ -135,19 +161,20 @@ function createPhoneRoutes ({ // Evaluated at each call, so the server can widen them (a link in flight). const callbacks = { linked: (m) => linked(m), - burnable: (m) => burnable(m), + burnable: (m, since) => burnable(m, since), deleted: (m) => deleted(m), // Any published block, a self-deletion's included: a burn is never // lifted while the key stays on the list. - blocked: (m) => blocked(m) + blocked: (m) => blocked(m), + cleared: (m, since) => cleared(m, since) } // Member keys are free to make, so the unlinked keys share their own daily // ceiling of paid sends; linked members have a separate one, so disposable // keys cannot lock them out. The number window is keyed by its HMAC index. const limits = { - member: keyedCeiling(5, DAY_MS, now), - number: keyedCeiling(3, DAY_MS, now), + member: keyedCeiling(5, DAY_MS, now, windowBound), + number: keyedCeiling(3, DAY_MS, now, windowBound), check: keyedWindow(10, 600 * 1000, now), status: keyedWindow(30, 600 * 1000, now), dailyNew: ceiling(dailyLimit, DAY_MS, now), @@ -156,16 +183,16 @@ function createPhoneRoutes ({ since: fixedWindow(6000, 60 * 1000, now) } - // nonce -> { member, expiresAt }, single-use, the oldest evicted for room. - const nonces = new Map() - // member -> { phone, index, sentAt, attempts, approved }, the oldest - // evicted for room. + const nonces = createStartNonces({ label: 'varanda-phone-start-v1', now, max: maxSpent }) + // member -> { phone, index, sentAt, attempts, approved }, at most + // pendingBound counting the sends in flight (see room). const pending = new Map() // member -> { index, done: Promise<{ state } | { error }> } of a send in // flight. const sending = new Map() // member -> time of the last send that (maybe) texted a code. Apart from // pending, which three wrong codes drop, so the resend wait outlives it. + // Bounded like pending. const lastSent = new Map() // Members with a check in flight: one at a time, so parallel checks can // neither pass the attempt limit nor drop the entry an approval is about @@ -253,7 +280,6 @@ function createPhoneRoutes ({ function prune () { const t = now() - for (const [k, v] of nonces) if (v.expiresAt <= t) nonces.delete(k) for (const [k, v] of pending) if (t - v.sentAt >= PENDING_TTL_MS) pending.delete(k) for (const [k, at] of lastSent) if (t - at >= RESEND_MS) lastSent.delete(k) } @@ -268,13 +294,28 @@ function createPhoneRoutes ({ return p } + // Whether pending and lastSent can take this member once its send returns. + // The sends in flight count as taken, so remember never needs to evict. + function room (member) { + prune() + const taken = sending.size + 1 + return (pending.has(member) || pending.size + taken <= pendingBound) && + (lastSent.has(member) || lastSent.size + taken <= pendingBound) + } + + // Also on a timer, so the number leaves memory when its code expires + // even if no other request comes in to prune it. + let seq = 0 function remember (member, phone, index) { prune() pending.delete(member) - while (pending.size >= MAX_PENDING) pending.delete(pending.keys().next().value) - pending.set(member, { phone, index, sentAt: now(), attempts: 0, approved: false }) + const id = ++seq + pending.set(member, { id, phone, index, sentAt: now(), attempts: 0, approved: false }) + setTimeout(() => { + const p = pending.get(member) + if (p !== undefined && p.id === id) pending.delete(member) + }, PENDING_TTL_MS).unref() lastSent.delete(member) - while (lastSent.size >= MAX_PENDING) lastSent.delete(lastSent.keys().next().value) lastSent.set(member, now()) } @@ -282,14 +323,12 @@ function createPhoneRoutes ({ if (pending.get(member) === p) pending.delete(member) } - // Spends the nonce before anything else, then checks the member, the - // expiry and the signature for `action`. + // Spends the nonce (minted for this member, live and unspent) before + // anything else, then checks the signature for `action`. function prove (body, action) { const member = memberParam(body.member) - const nonce = typeof body.nonce === 'string' && TOKEN_RE.test(body.nonce) ? body.nonce : null - const row = nonce === null ? undefined : nonces.get(nonce) - if (nonce !== null) nonces.delete(nonce) - if (row === undefined || row.member !== member || row.expiresAt <= now()) throw refuse('expirado') + const nonce = body.nonce + if (!nonces.spend(member, nonce)) throw refuse('expirado') if (!verifyPhone({ action, nonce, member, association }, body.signature).ok) throw refuse('assinatura-invalida') return member } @@ -344,10 +383,7 @@ function createPhoneRoutes ({ if (!on) throw refuse('indisponivel') const member = memberParam(body.member) prune() - while (nonces.size >= MAX_NONCES) nonces.delete(nonces.keys().next().value) - const nonce = nodeCrypto.randomBytes(32).toString('base64url') - nonces.set(nonce, { member, expiresAt: now() + NONCE_TTL_MS }) - send(res, 200, { nonce }) + send(res, 200, { nonce: nonces.mint(member) }) } async function sendCode (req, res, body) { @@ -393,6 +429,10 @@ function createPhoneRoutes ({ } if (!limits.member.has(member)) throw refuse('limite-telefone') if (!limits.number.has(index)) throw refuse('limite-telefone') + if (!room(member)) { + log({ event: 'telefone', reason: 'tabela-cheia' }) + throw refuse('limite-telefone') + } limits.member.take(member) limits.number.take(index) daily.take() @@ -551,10 +591,10 @@ function createPhoneRoutes ({ // Sizes only, never a nonce, a number or a member key. function stats () { - return { nonces: nonces.size, pending: pending.size } + return { nonces: nonces.size(), pending: pending.size } } return { owns, handle, required, verified, settled, sweepNow, stats } } -module.exports = { createPhoneRoutes } +module.exports = { createPhoneRoutes, keyedCeiling, maxKeysFor } diff --git a/apps/cli/lib/account/phone-store.js b/apps/cli/lib/account/phone-store.js index a3e5b704..67d5f156 100644 --- a/apps/cli/lib/account/phone-store.js +++ b/apps/cli/lib/account/phone-store.js @@ -35,7 +35,7 @@ const { isLowerHex, isCanonicalIso, isPlainObject, refuseSymlinkDir } = require( const { isBrMobile } = require('@varanda/core/lib/phone') const FILE = 'phone.json' -const VERSION = 1 +const VERSION = 2 const DAY = 24 * 3600 * 1000 // Both periods: sujeita a revisão jurídica (LGPD section of docs/design.md). // RETENTION_MS is how long a number stays sealed after it stops being a @@ -46,7 +46,10 @@ const UNLINKED_TTL_MS = 7 * DAY const ENDS = Object.freeze(['trocado', 'excluida', 'substituido', 'liberado']) const END_REASONS = Object.freeze(['excluida', 'trocado', 'substituido']) -const FILE_KEYS = ['v', 'check', 'since', 'rows', 'released'] +// Version 2 added `cleared`; a version 1 file still reads (nothing +// cleared) and the next write makes it version 2. +const FILE_KEYS = ['v', 'check', 'since', 'rows', 'released', 'cleared'] +const FILE_KEYS_V1 = ['v', 'check', 'since', 'rows', 'released'] const ROW_KEYS = ['member', 'index', 'sealed', 'verifiedAt', 'endedAt', 'end', 'burnedAt'] const SEALED_KEYS = ['iv', 'tag', 'data'] const SEAL_LABEL = 'varanda-phone-seal-v1' @@ -89,6 +92,7 @@ function checkCallbacks (cbs) { if (typeof cbs[name] !== 'function') throw new TypeError('linked, burnable and deleted must be functions') } if (cbs.blocked !== undefined && typeof cbs.blocked !== 'function') throw new TypeError('blocked must be a function') + if (cbs.cleared !== undefined && typeof cbs.cleared !== 'function') throw new TypeError('cleared must be a function') } function hmac (key, data) { @@ -136,12 +140,27 @@ function copyRow (r) { } function emptyState () { - return { since: null, rows: [], released: Object.create(null) } + return { since: null, rows: [], released: Object.create(null), cleared: Object.create(null) } } function copyState (s) { - const out = { since: s.since, rows: s.rows.map(copyRow), released: Object.create(null) } + const out = { since: s.since, rows: s.rows.map(copyRow), released: Object.create(null), cleared: Object.create(null) } for (const m of Object.keys(s.released)) out.released[m] = s.released[m] + for (const m of Object.keys(s.cleared)) out.cleared[m] = s.cleared[m] + return out +} + +function memberTimes (from, into) { + if (!isPlainObject(from)) throw invalid() + for (const [m, at] of Object.entries(from)) { + if (!validMember(m) || !isCanonicalIso(at)) throw invalid() + into[m] = at + } +} + +function sortedTimes (map) { + const out = {} + for (const m of Object.keys(map).sort()) out[m] = map[m] return out } @@ -150,9 +169,11 @@ function invalid () { } function fromJson (obj, check) { - if (!isPlainObject(obj) || !exactKeys(obj, FILE_KEYS) || obj.v !== VERSION) throw invalid() + if (!isPlainObject(obj)) throw invalid() + const v1 = obj.v === 1 && exactKeys(obj, FILE_KEYS_V1) + if (!v1 && !(obj.v === VERSION && exactKeys(obj, FILE_KEYS))) throw invalid() if (!isLowerHex(obj.check, 32) || !nodeCrypto.timingSafeEqual(Buffer.from(obj.check, 'hex'), check)) throw invalid() - if (!isCanonicalIso(obj.since) || !Array.isArray(obj.rows) || !isPlainObject(obj.released)) throw invalid() + if (!isCanonicalIso(obj.since) || !Array.isArray(obj.rows)) throw invalid() const state = emptyState() state.since = obj.since const liveMembers = new Set() @@ -166,17 +187,13 @@ function fromJson (obj, check) { } state.rows.push(copyRow(r)) } - for (const [m, at] of Object.entries(obj.released)) { - if (!validMember(m) || !isCanonicalIso(at)) throw invalid() - state.released[m] = at - } + memberTimes(obj.released, state.released) + if (!v1) memberTimes(obj.cleared, state.cleared) return state } function toJson (state, check) { - const released = {} - for (const m of Object.keys(state.released).sort()) released[m] = state.released[m] - return { v: VERSION, check, since: state.since, rows: state.rows.map(copyRow), released } + return { v: VERSION, check, since: state.since, rows: state.rows.map(copyRow), released: sortedTimes(state.released), cleared: sortedTimes(state.cleared) } } // The file's state, or null when it does not exist. O_NOFOLLOW so a symlink @@ -342,13 +359,18 @@ function openPhoneStore (dataDir, { key, now = Date.now, guard = () => true, rea return result } + function clearedOf (s, m) { + return has(s.cleared, m) ? s.cleared[m] : null + } + function ownerTest (cbs, s) { const cache = new Map() return (name, owner) => { const k = name + ':' + owner if (!cache.has(k)) { - let v = cbs[name](owner) === true - if (name === 'burnable') v = v && !has(s.released, owner) + let v + if (name === 'burnable') v = cbs.burnable(owner, clearedOf(s, owner)) === true && !has(s.released, owner) + else v = cbs[name](owner) === true cache.set(k, v) } return cache.get(k) @@ -464,12 +486,23 @@ function openPhoneStore (dataDir, { key, now = Date.now, guard = () => true, rea return enqueue(() => { checkCallbacks(cbs) return mutate((s) => { - const counts = { ended: 0, burned: 0, unburned: 0, unsealed: 0, removed: 0, released: 0 } + const counts = { ended: 0, burned: 0, unburned: 0, unsealed: 0, removed: 0, released: 0, cleared: 0 } const t = now() const stamp = new Date(t).toISOString() + // First, so the burns below already see it: a member seen under no + // block after its 'bloquear' reports keeps those reports from + // burning its number once it deletes its account (issue #534). + if (typeof cbs.cleared === 'function') { + for (const m of new Set(s.rows.map((r) => r.member))) { + if (cbs.cleared(m, clearedOf(s, m)) === true) { + s.cleared[m] = stamp + counts.cleared++ + } + } + } const lifted = typeof cbs.blocked === 'function' ? (m) => cbs.blocked(m) === false - : (m) => cbs.burnable(m) !== true + : (m) => cbs.burnable(m, clearedOf(s, m)) !== true const liftedOf = new Map() const isLifted = (m) => { if (!liftedOf.has(m)) liftedOf.set(m, lifted(m)) @@ -523,6 +556,14 @@ function openPhoneStore (dataDir, { key, now = Date.now, guard = () => true, rea kept.push(r) } s.rows = kept + // Bounded by the rows: an entry only matters while its member has one. + const withRows = new Set(kept.map((r) => r.member)) + for (const m of Object.keys(s.cleared)) { + if (!withRows.has(m)) { + delete s.cleared[m] + counts.cleared++ + } + } const changed = Object.values(counts).some((n) => n > 0) return [changed, counts] }) diff --git a/apps/cli/lib/account/server.js b/apps/cli/lib/account/server.js index f34d08d9..56b1e09a 100644 --- a/apps/cli/lib/account/server.js +++ b/apps/cli/lib/account/server.js @@ -15,6 +15,7 @@ const { createPushRoutes } = require('./push-routes') const { createSeenRoutes } = require('./seen-routes') const { createAgeRoutes } = require('./age-routes') const { createPhoneRoutes } = require('./phone-routes') +const { spentCapacity } = require('./start-nonces') const { phoneSub } = require('./store') const { createRecoveryRoutes } = require('./recovery-routes') const { createDeleteRoutes } = require('./delete-routes') @@ -62,7 +63,9 @@ const { createOgRoutes } = require('./og-routes') // verified (finish, rename/finish) and keyed on the member it // proved; the public reads share one wide // window; the routes that need no proof (start, rename/start) are bounded -// by their tables (oldest evicted) and by the one global token bucket. +// by their tables (oldest evicted) and by the one global token bucket; +// phone/start and age/start hold no table at all (stateless nonces, +// ./start-nonces.js), only the bucket bounds them. // Residual: a flood can still drain the global bucket (by default 20/s, // burst 100; `ratePerSecond` and `burst` configure it, and `maxConnections` // the socket ceiling, by default 64) for everyone. A per-source limit needs client addresses, which the @@ -872,6 +875,7 @@ function createAccountServer ({ log, now, dailyLimit: ageDailyLimit, + maxSpent: spentCapacity(ratePerSecond, burst), since: ageSince, ageCheck, directoryFloor: ageDirectoryFloor, @@ -881,9 +885,14 @@ function createAccountServer ({ }) // Always mounted, so /account/phone/policy answers even when the feature - // is off. Excluir conta also queues a block with no report id - // (moderation-store.js requestDeletion): only a block that is not that one - // alone burns the number. + // is off. Any listing burns a live member's number. Excluir conta also + // queues a block with no report id (moderation-store.js requestDeletion), + // so a deleted member's number burns only through a 'bloquear' report + // decided at or after `since`: the last time the sweep saw the member + // under no block (`cleared`), so the reports of a block lifted before the + // deletion never hold it again (issue #534). held() counts that pending + // block, so no member is cleared while it waits, and a 'bloquear' decided + // after the deletion keeps the member from being cleared. // Members with a phone finish in flight -> count. A number another member // records meanwhile must not end the row this finish is about to link. const linking = new Map() @@ -896,16 +905,19 @@ function createAccountServer ({ forgetAge: forgetRefusedAge, linked: (m) => store.status(m).linked || linking.has(m), deleted: (m) => store.deletedAt(m) !== null, - burnable: (m) => { - if (moderation === null) return false - const b = moderation.blocked().find((x) => x.member === m) - return b !== undefined && (b.reportIds.length > 0 || store.deletedAt(m) === null) + burnable: (m, since) => moderation !== null && moderation.blocked().some((x) => x.member === m) && + (store.deletedAt(m) === null || moderation.blockReportsAfter(m, since) > 0), + cleared: (m, since) => { + if (moderation === null || moderation.held(m) || moderation.blockReportsAfter(m, since) === 0) return false + const at = store.deletedAt(m) + return at === null || moderation.blockReportsAfter(m, at) === 0 }, blocked: (m) => moderation !== null && moderation.blocked().some((x) => x.member === m), issuer, log, now, dailyLimit: phoneDailyLimit, + maxSpent: spentCapacity(ratePerSecond, burst), http: { send, sendError, redirect, readJsonBody, checkPost: (req, opts) => checkPost(req, origin, opts), RouteError, refuse, fromStore, keyedWindow, fixedWindow } }) @@ -949,11 +961,12 @@ function createAccountServer ({ } catch { log({ event: 'telefone', reason: 'varredura-exclusao-falhou' }) // Once deleted, a block with no report id no longer burns: a blocked - // member's deletion waits until the burn is written. Nobody else is - // held by a failing phone store. + // member's deletion waits until the burn is written. So does one + // with 'bloquear' reports, whose lifted block the sweep may not have + // cleared yet. Nobody else is held by a failing phone store. let held = true try { - held = moderation !== null && moderation.blocked().some((x) => x.member === member) + held = moderation !== null && (moderation.blocked().some((x) => x.member === member) || moderation.blockReportsAfter(member, null) > 0) } catch {} if (held) throw refuse('indisponivel') } diff --git a/apps/cli/lib/account/start-nonces.js b/apps/cli/lib/account/start-nonces.js new file mode 100644 index 00000000..ef491e7a --- /dev/null +++ b/apps/cli/lib/account/start-nonces.js @@ -0,0 +1,119 @@ +'use strict' + +const nodeCrypto = require('node:crypto') + +// Stateless single-use nonces for the unsigned start routes of ./phone-routes.js +// and ./age-routes.js. start allocates nothing, so a flood of starts cannot +// push out a member's unspent nonce; only spent nonces are kept, until they +// expire, to refuse a replay. +// +// A nonce is base64url of exactly 32 bytes (43 characters, the same opaque +// token clients already handle): 12 random bytes, a 4-byte big-endian expiry +// in unix seconds, and the first 16 bytes of HMAC-SHA256 under a per-process +// secret over the route's label, the member key, the random bytes and the +// expiry. A restart draws a new secret, which expires every outstanding nonce. + +const TTL_MS = 600 * 1000 +// Every spend needs a request through the service's one global token bucket +// (./server.js, by default 20/s with a burst of 100), so within one 10-minute +// TTL at most about 12100 nonces can be spent. A full table refuses the spend +// instead of evicting a live entry, which would reopen a replay. This is the +// floor: ./server.js sizes the table from its bucket with spentCapacity. +const MAX_SPENT = 16384 +const RAW_BYTES = 32 +const RANDOM_BYTES = 12 +const EXPIRY_BYTES = 4 +const MAC_BYTES = 16 +const TOKEN_RE = /^[A-Za-z0-9_-]{43}$/ +const HEX64_RE = /^[0-9a-f]{64}$/ + +// createStartNonces({ label, now, ttlMs, max }) -> { mint, spend, size }. +// `label` keeps one route's nonces from spending at another. +function createStartNonces ({ label, now = Date.now, ttlMs = TTL_MS, max = MAX_SPENT }) { + if (typeof label !== 'string' || label.length === 0 || label.includes('\n')) throw new TypeError('label must be a non-empty string') + if (!Number.isSafeInteger(ttlMs) || ttlMs < 1000) throw new TypeError('ttlMs must be an integer of at least 1000') + if (!Number.isSafeInteger(max) || max < 1) throw new TypeError('max must be a positive integer') + const prefix = Buffer.from(label + '\n') + let secret = nodeCrypto.randomBytes(32) + // nonce -> expiresAt (ms) of the nonces already spent. + const spent = new Map() + + // Never steps back, as the recovery nonce clock (./recovery-routes.js): a + // wall clock corrected backwards must not revive a nonce whose spent entry + // was already pruned. A step back of more than one TTL voids every + // outstanding nonce instead (a new secret fails each old MAC, which is what + // makes clearing the spent table safe). + let highWater = 0 + function clock () { + const t = now() + if (t + ttlMs < highWater) { + secret = nodeCrypto.randomBytes(32) + spent.clear() + highWater = t + } else if (t > highWater) { + highWater = t + } + return highWater + } + + function macOf (member, random, expiry) { + const h = nodeCrypto.createHmac('sha256', secret) + h.update(prefix) + h.update(Buffer.from(member, 'hex')) + h.update(random) + h.update(expiry) + return h.digest().subarray(0, MAC_BYTES) + } + + function prune (t) { + for (const [k, at] of spent) if (at <= t) spent.delete(k) + } + + function mint (member) { + if (typeof member !== 'string' || !HEX64_RE.test(member)) throw new TypeError('member must be hex64') + const random = nodeCrypto.randomBytes(RANDOM_BYTES) + const expiry = Buffer.alloc(EXPIRY_BYTES) + expiry.writeUInt32BE(Math.ceil((clock() + ttlMs) / 1000)) + return Buffer.concat([random, expiry, macOf(member, random, expiry)]).toString('base64url') + } + + // -> true when this process minted `nonce` for `member`, it has not expired + // and was not spent yet; it is then spent. Only the canonical spelling is + // accepted (43 characters carry 2 spare bits), so the spent table cannot be + // dodged by re-spelling a nonce. The clock is read before the MAC, so a + // secret rotation it triggers fails this nonce. + function spend (member, nonce) { + const t = clock() + if (typeof member !== 'string' || !HEX64_RE.test(member)) return false + if (typeof nonce !== 'string' || !TOKEN_RE.test(nonce)) return false + const raw = Buffer.from(nonce, 'base64url') + if (raw.length !== RAW_BYTES || raw.toString('base64url') !== nonce) return false + const random = raw.subarray(0, RANDOM_BYTES) + const expiry = raw.subarray(RANDOM_BYTES, RANDOM_BYTES + EXPIRY_BYTES) + const mac = raw.subarray(RANDOM_BYTES + EXPIRY_BYTES) + if (!nodeCrypto.timingSafeEqual(mac, macOf(member, random, expiry))) return false + const expiresAt = expiry.readUInt32BE(0) * 1000 + if (expiresAt <= t || spent.has(nonce)) return false + if (spent.size >= max) prune(t) + if (spent.size >= max) return false + spent.set(nonce, expiresAt) + return true + } + + // The live spent entries. + function size () { + prune(clock()) + return spent.size + } + + return { mint, spend, size } +} + +// The spent table a service needs when every spend rides one request through +// a token bucket of `ratePerSecond` and `burst`: one TTL holds at most +// rate x TTL + burst of them. Never below MAX_SPENT. +function spentCapacity (ratePerSecond, burst, ttlMs = TTL_MS) { + return Math.max(MAX_SPENT, Math.ceil(ratePerSecond * ttlMs / 1000) + burst) +} + +module.exports = { createStartNonces, spentCapacity, MAX_SPENT } diff --git a/apps/cli/test/account-age.test.js b/apps/cli/test/account-age.test.js index 2544ca35..c56c0c7d 100644 --- a/apps/cli/test/account-age.test.js +++ b/apps/cli/test/account-age.test.js @@ -236,7 +236,7 @@ async function setup (t, { age = true, phone = false, inviting = false, maxMembe const decisions = () => fake.seen.filter((r) => r.method === 'GET') const lastSession = () => [...fake.sessions.keys()].pop() - return { dir, base, numbers, c, iss, store, ages, invites, feiraStore, fake, google, linked, logs, texts, api, post, signFor, start, step, feiraStep, raw, creates, deletes, decisions, lastSession } + return { dir, base, numbers, c, iss, store, ages, invites, feiraStore, fake, google, linked, logs, texts, server, api, post, signFor, start, step, feiraStep, raw, creates, deletes, decisions, lastSession } } // Opens a session for `who` and scripts its Didit decision. @@ -922,13 +922,17 @@ test('age nonces: single-use, member-bound, expiring, action-bound, never a term const m = member() const other = member() - // Issued to m, presented by other with its own signature: spent. + // Issued to m, presented by other with its own signature: refused, and + // not spent for m (the nonce is bound to m), which a failed proof then + // spends. const a = await s.start(m) const stolen = await s.post('/account/age/session', { member: other.hex, nonce: a.body.nonce, signature: s.signFor(other, 'session', a.body.nonce) }) t.is(stolen.status, 404) t.alike(stolen.body, { error: 'expirado' }) + const own = await s.post('/account/age/session', { member: m.hex, nonce: a.body.nonce, signature: s.signFor(m, 'result', a.body.nonce) }) + t.alike(own.body, { error: 'assinatura-invalida' }, 'still live for m after the other member\'s attempt') const late = await s.post('/account/age/session', { member: m.hex, nonce: a.body.nonce, signature: s.signFor(m, 'session', a.body.nonce) }) - t.is(late.status, 404, 'spent by the other member\'s attempt') + t.is(late.status, 404, 'spent by m\'s failed proof') // Expired. const b = await s.start(m) @@ -963,6 +967,22 @@ test('age nonces: single-use, member-bound, expiring, action-bound, never a term noPersonalData(t, s) }) +test('age nonces: a flood of unsigned starts never pushes out a member\'s unspent nonce', async (t) => { + const s = await setup(t, { burst: 5000 }) + const m = member() + const nonce = (await s.start(m)).body.nonce + // More than the 1000 nonces the old table held, each for a fresh key. + let failed = 0 + for (let i = 0; i < 1100; i++) { + if ((await s.start(member())).status !== 200) failed++ + } + t.is(failed, 0, '1100 unsigned starts answered') + t.is(s.server.ageStats().nonces, 0, 'start stores nothing') + const r = await s.post('/account/age/session', { member: m.hex, nonce, signature: s.signFor(m, 'session', nonce) }) + t.is(r.status, 200, r.text) + t.is(s.server.ageStats().nonces, 1, 'only the spent nonce is kept') +}) + test('age decisions: bands stored, refusals and inconclusive store nothing, every final decision deletes the session', async (t) => { const s = await setup(t) diff --git a/apps/cli/test/account-phone-burn.test.js b/apps/cli/test/account-phone-burn.test.js new file mode 100644 index 00000000..18700eb9 --- /dev/null +++ b/apps/cli/test/account-phone-burn.test.js @@ -0,0 +1,352 @@ +'use strict' + +// Issue #534: which blocks burn a number through Excluir conta. server.js +// wires the phone store's burnable and cleared rules to a real moderation +// store; snapshots are signed here with a local moderator certificate and +// acked as the operator's `mod apply` would. Loopback only: the Didit fake +// of helpers/fake-didit.js, real stores in a tmp dir, a fake passkey. + +const test = require('brittle') +const fs = require('node:fs') +const nodeCrypto = require('node:crypto') +const path = require('node:path') +const b4a = require('b4a') +const crypto = require('hypercore-crypto') +const { createIssuerCert, createModeratorCert } = require('@varanda/core/lib/cert') +const { createSnapshot } = require('@varanda/core/lib/blocklist') +const { signAccountLink } = require('@varanda/core/lib/account-link') +const { signPhone } = require('@varanda/core/lib/phone') +const { openAccountStore } = require('../lib/account/store') +const { openPhoneStore, FILE } = require('../lib/account/phone-store') +const { openModerationStore } = require('../lib/account/moderation-store') +const { createPhoneClient } = require('../lib/account/phone-client') +const { openPasskeyStore } = require('../lib/account/passkey-store') +const { keyFromAttestation } = require('../lib/account/webauthn') +const { createFakePasskey } = require('./helpers/fake-passkey') +const { createAccountServer } = require('../lib/account/server') +const { startFakeDidit, loopbackFetch, PHONE_CODE } = require('./helpers/fake-didit') +const { tmpDir } = require('./helpers/net') + +const ORIGIN = 'https://varanda.test' +const API_KEY = 'test-phone-key-123' +const EMAIL = 'membro@example.test' +const PHONE_A = '+5511987654321' +const MOD = 'mod@example.test' +const SIG = 'ab'.repeat(64) +const NONCE = 'n'.repeat(43) + +function googleStub () { + return { + authorizeUrl: () => 'https://accounts.google.test/auth?state=x', + exchange: async () => { throw new Error('google called') } + } +} + +function member () { + const kp = crypto.keyPair() + return { kp, hex: b4a.toString(kp.publicKey, 'hex') } +} + +let subSeq = 100 +async function linkDirect (store, iss, m, username) { + const row = store.start({ member: m.hex, username }) + store.reserve(row.id) + store.putGoogle(row.id, { sub: '40000000000000000' + String(subSeq++).padStart(5, '0'), email: EMAIL }) + await store.finish(row.id, { signature: 'a'.repeat(128) }, iss.keyPair, iss.cert, iss.association) +} + +async function setup (t) { + const dir = path.join(tmpDir(t), 'account') + // Every step moves the clock on, so report decisions and sweep stamps + // never share a millisecond. + const c = { offset: 0 } + c.now = () => Date.now() + c.offset + const assoc = crypto.keyPair() + const kp = crypto.keyPair() + const iss = { keyPair: kp, cert: createIssuerCert({ issuer: b4a.toString(kp.publicKey, 'hex') }, assoc) } + iss.association = iss.cert.association + const modKp = crypto.keyPair() + const modCert = createModeratorCert({ moderator: b4a.toString(modKp.publicKey, 'hex'), date: '2026-10-01T00:00:00.000Z' }, assoc) + const store = openAccountStore(dir, { now: c.now }) + const fake = await startFakeDidit() + t.teardown(() => fake.close(), { force: true }) + const phones = openPhoneStore(dir, { key: nodeCrypto.randomBytes(32), now: c.now }) + const moderation = openModerationStore(dir, { now: c.now, association: iss.association }) + const passkeys = openPasskeyStore(dir, { now: c.now }) + const client = () => createPhoneClient({ apiKey: API_KEY, endpoints: { base: fake.base }, fetch: loopbackFetch(fake.base) }) + const opts = { + association: iss.association, + origin: ORIGIN, + google: googleStub(), + store, + issuer: { keyPair: iss.keyPair, cert: iss.cert }, + moderation, + passkeys, + phoneClient: client(), + phones, + log: () => {}, + now: c.now + } + const server = createAccountServer(opts) + const listener = await server.listen({ host: '127.0.0.1', port: 0 }) + t.teardown(() => listener.close(), { force: true }) + const base = 'http://127.0.0.1:' + listener.port + + async function post (pathname, body) { + const res = await fetch(base + pathname, { + method: 'POST', + redirect: 'manual', + headers: { origin: ORIGIN, 'content-type': 'application/json' }, + body: JSON.stringify(body) + }) + const text = await res.text() + let parsed = null + try { parsed = JSON.parse(text) } catch {} + return { status: res.status, body: parsed, text } + } + + async function step (who, action, extra = {}) { + const started = await post('/account/phone/start', { member: who.hex }) + if (started.status !== 200) return started + const nonce = started.body.nonce + const signature = signPhone({ action, nonce, member: who.hex, association: iss.association }, who.kp) + return post('/account/phone/' + action, { member: who.hex, nonce, signature, ...extra }) + } + + async function verify (who, number) { + tick() + const sent = await step(who, 'send', { phone: number }) + if (sent.status !== 200 || sent.body.state !== 'enviado') return sent + return step(who, 'check', { code: PHONE_CODE }) + } + + // A linked member with a verified number and a passkey, so Excluir conta + // can run. + async function holder (username) { + const who = member() + await linkDirect(store, iss, who, username) + t.is((await verify(who, PHONE_A)).body.state, 'verificado', username + ' verifies') + const pk = createFakePasskey({ rpId: 'varanda.test' }) + const key = keyFromAttestation({ attestationObject: pk.attestationObject(), credentialId: pk.credentialId, rpId: 'varanda.test' }) + await passkeys.add({ member: who.hex, credentialId: pk.credentialId, ...key }) + who.pk = pk + return who + } + + async function remove (who) { + tick() + const st = await post('/account/delete/start', { member: who.hex }) + t.is(st.status, 200, st.text) + const done = await post('/account/delete/finish', { + member: who.hex, + nonce: st.body.nonce, + signature: signAccountLink({ phase: 'delete', nonce: st.body.nonce, member: who.hex, username: st.body.username, association: iss.association, sub: '' }, who.kp), + assertion: who.pk.assert({ challenge: Buffer.from(st.body.nonce, 'base64url'), origin: ORIGIN }) + }) + t.is(done.status, 200, done.text) + t.ok(store.deletedAt(who.hex) !== null, 'deleted') + } + + async function reportBlock (who) { + tick() + const { report } = await moderation.add({ reporter: member().hex, target: who.hex, seq: 3, reason: 'spam', text: 'propaganda', quote: 'compre já', signature: SIG, nonce: NONCE }) + tick() + await moderation.decide(report.id, { decision: 'bloquear', by: MOD }) + } + + // The operator's `mod apply`: every pending change into the next snapshot. + let seq = 0 + async function publish () { + tick() + const { changes, published } = await moderation.pull() + const list = new Set(published.snapshot ? published.snapshot.blocked : []) + for (const ch of changes) { + if (ch.op === 'block') list.add(ch.member) + else list.delete(ch.member) + } + const snapshot = createSnapshot({ seq: ++seq, date: new Date(c.now()).toISOString(), blocked: [...list].sort() }, modKp, modCert) + await moderation.ack({ changeIds: changes.map((ch) => ch.id), snapshot, moderatorCert: modCert }) + } + + async function unblock (who) { + tick() + return moderation.unblock(who.hex, { by: MOD }) + } + + // A second service on the same stores runs the start sweep with the + // server's own callbacks; resolves once that sweep is done. + async function sweep (who) { + tick() + createAccountServer({ ...opts, google: googleStub(), phoneClient: client() }) + await phones.settled(who.hex) + } + + function tick () { + c.offset += 61 * 1000 + } + + const burned = () => phones.counts().burned + const cleared = () => JSON.parse(fs.readFileSync(path.join(dir, FILE), 'utf8')).cleared + return { c, store, phones, moderation, verify, holder, remove, reportBlock, publish, unblock, sweep, burned, cleared } +} + +test('burn: a member unblocked before Excluir conta keeps no burn once the deletion block publishes', async (t) => { + const s = await setup(t) + const ana = await s.holder('ana') + await s.reportBlock(ana) + await s.publish() + await s.sweep(ana) + t.is(s.burned(), 1, 'burned while blocked') + + await s.unblock(ana) + await s.publish() + await s.sweep(ana) + t.is(s.burned(), 0, 'the unblock gives it back') + + await s.remove(ana) + t.ok(s.moderation.pending().changes.some((ch) => ch.member === ana.hex && ch.op === 'block'), 'Excluir conta queues its own block') + await s.publish() + t.ok(s.moderation.blocked().some((b) => b.member === ana.hex && b.reportIds.length === 1), 'listed again with the old report') + await s.sweep(ana) + t.is(s.burned(), 0, 'the old report no longer burns the number') + t.is((await s.verify(member(), PHONE_A)).body.state, 'verificado', 'another member records it') +}) + +test('burn: a member deleting while the block is in force keeps the burn', async (t) => { + const s = await setup(t) + const bia = await s.holder('bia') + await s.reportBlock(bia) + await s.publish() + await s.sweep(bia) + t.is(s.burned(), 1) + await s.remove(bia) + await s.publish() + await s.sweep(bia) + t.is(s.burned(), 1, 'burn kept after the deletion') + t.alike((await s.verify(member(), PHONE_A)).body, { error: 'telefone-em-uso' }) +}) + +test('burn: a block decided but not published at Excluir conta burns once both blocks publish', async (t) => { + const s = await setup(t) + const caio = await s.holder('caio') + await s.reportBlock(caio) + await s.remove(caio) + t.is(s.burned(), 0, 'not yet: nothing published') + await s.sweep(caio) + t.is(s.burned(), 0) + await s.publish() + await s.sweep(caio) + t.is(s.burned(), 1, 'burned once published') + t.alike((await s.verify(member(), PHONE_A)).body, { error: 'telefone-em-uso' }) +}) + +test('burn: a report decided after Excluir conta burns, even with a sweep before the operator publishes', async (t) => { + const s = await setup(t) + const zeca = await s.holder('zeca') + await s.remove(zeca) + await s.reportBlock(zeca) + t.ok(s.moderation.pending().changes.some((ch) => ch.member === zeca.hex && ch.op === 'block' && ch.reportIds.length === 1), 'the report joins the deletion block') + await s.sweep(zeca) + t.alike(s.cleared(), {}, 'a report after the deletion clears nothing') + await s.publish() + await s.sweep(zeca) + t.is(s.burned(), 1, 'burned once published') + t.alike((await s.verify(member(), PHONE_A)).body, { error: 'telefone-em-uso' }) +}) + +test('burn: a report decided while a failed deletion waits burns once the account goes', async (t) => { + const s = await setup(t) + const fabio = await s.holder('fabio') + // Excluir conta queued its block, then the account store failed + // (resultado-incerto): the account is still there. + await s.moderation.requestDeletion(fabio.hex) + t.is(s.store.deletedAt(fabio.hex), null, 'not deleted') + await s.reportBlock(fabio) + await s.sweep(fabio) + t.alike(s.cleared(), {}, 'a report joining the waiting deletion block clears nothing') + await s.remove(fabio) + await s.publish() + await s.sweep(fabio) + t.is(s.burned(), 1, 'burned once published') + t.alike((await s.verify(member(), PHONE_A)).body, { error: 'telefone-em-uso' }) +}) + +test('burn: an unblock published with no sweep before Excluir conta is cleared by the deletion\'s own sweep', async (t) => { + const s = await setup(t) + const gil = await s.holder('gil') + await s.reportBlock(gil) + await s.publish() + await s.sweep(gil) + t.is(s.burned(), 1) + await s.unblock(gil) + await s.publish() + t.alike(s.cleared(), {}, 'no sweep yet') + await s.remove(gil) + t.ok(s.cleared()[gil.hex], 'the sweep before the deletion block clears it') + await s.publish() + await s.sweep(gil) + t.is(s.burned(), 0, 'the old report no longer burns the number') + t.is((await s.verify(member(), PHONE_A)).body.state, 'verificado', 'another member records it') +}) + +test('burn: a lift of a claimed block, cancelled before the operator publishes, clears nothing', async (t) => { + const s = await setup(t) + const hugo = await s.holder('hugo') + await s.reportBlock(hugo) + await s.moderation.pull() + const { change } = await s.unblock(hugo) + t.is(change.op, 'unblock', 'appended next to the claimed block') + await s.sweep(hugo) + t.alike(s.cleared(), {}, 'nothing cleared while both wait') + await s.moderation.cancel(change.id, { by: MOD }) + await s.remove(hugo) + await s.publish() + await s.sweep(hugo) + t.is(s.burned(), 1, 'burned once the block publishes') + t.alike((await s.verify(member(), PHONE_A)).body, { error: 'telefone-em-uso' }) +}) + +test('burn: a report decided after the unblock burns again, through the deletion', async (t) => { + const s = await setup(t) + const davi = await s.holder('davi') + await s.reportBlock(davi) + await s.publish() + await s.sweep(davi) + await s.unblock(davi) + await s.publish() + await s.sweep(davi) + t.is(s.burned(), 0, 'unblocked and cleared') + + await s.reportBlock(davi) + await s.publish() + await s.sweep(davi) + t.is(s.burned(), 1, 'a new block burns while the account exists') + await s.remove(davi) + await s.publish() + await s.sweep(davi) + t.is(s.burned(), 1, 'and the deletion keeps it') + t.alike((await s.verify(member(), PHONE_A)).body, { error: 'telefone-em-uso' }) +}) + +test('burn: an unblock still waiting for the operator clears nothing; cancelled, the deletion keeps the burn', async (t) => { + const s = await setup(t) + const eva = await s.holder('eva') + await s.reportBlock(eva) + await s.publish() + await s.sweep(eva) + t.is(s.burned(), 1) + + const { change } = await s.unblock(eva) + t.is(change.op, 'unblock', 'queued, not applied') + await s.sweep(eva) + t.alike(s.cleared(), {}, 'a pending unblock does not clear') + t.is(s.burned(), 1, 'nor lift the burn') + + await s.moderation.cancel(change.id, { by: MOD }) + await s.remove(eva) + await s.publish() + await s.sweep(eva) + t.alike(s.cleared(), {}, 'still nothing cleared') + t.is(s.burned(), 1, 'the number stays burned after the deletion') + t.alike((await s.verify(member(), PHONE_A)).body, { error: 'telefone-em-uso' }) +}) diff --git a/apps/cli/test/account-phone.test.js b/apps/cli/test/account-phone.test.js index fe3323cb..81ee705b 100644 --- a/apps/cli/test/account-phone.test.js +++ b/apps/cli/test/account-phone.test.js @@ -24,7 +24,7 @@ const { openAgeStore } = require('../lib/account/age-store') const { openPhoneStore } = require('../lib/account/phone-store') const { openInvitesStore } = require('../lib/account/invites-store') const { createPhoneClient } = require('../lib/account/phone-client') -const { createPhoneRoutes } = require('../lib/account/phone-routes') +const { createPhoneRoutes, keyedCeiling, maxKeysFor } = require('../lib/account/phone-routes') const { openPasskeyStore } = require('../lib/account/passkey-store') const { keyFromAttestation } = require('../lib/account/webauthn') const { createFakePasskey } = require('./helpers/fake-passkey') @@ -188,10 +188,20 @@ async function setup (t, { loopback = false, phone = true, age = true, inviting } // The published blocklist is c.blocked; Excluir conta's own block request -// leaves it as it is (a pending change, not yet published). +// leaves it as it is (a pending change, not yet published). Nothing is +// pending and reports carry no decision time: a listed key is held, and its +// reports all count until the sweep first clears it. function fakeModeration (c) { + const entry = (m) => c.blocked.find((b) => b.member === m) return { blocked: () => c.blocked.map((b) => ({ member: b.member, reportIds: [...b.reportIds], kind: 'conta' })), + held: (m) => entry(m) !== undefined, + // c.reports: 'bloquear' reports of members no longer listed. + blockReportsAfter: (m, since) => { + if (since !== null) return 0 + const b = entry(m) + return b !== undefined ? b.reportIds.length : (c.reports && c.reports[m]) || 0 + }, requestDeletion: async () => ({ change: null, kind: 'igual' }) } } @@ -508,6 +518,23 @@ test('phone nonces: single-use, member-bound, expiring, action-bound, never an a t.alike(Object.keys((await s.start(member())).body), ['nonce'], 'start reveals nothing') }) +test('phone nonces: a flood of unsigned starts never pushes out a member\'s unspent nonce', async (t) => { + const s = await setup(t, { burst: 5000 }) + const m = member() + await s.band(m) + const nonce = (await s.start(m)).body.nonce + // More than the 1000 nonces the old table held, each for a fresh key. + let failed = 0 + for (let i = 0; i < 1100; i++) { + if ((await s.start(member())).status !== 200) failed++ + } + t.is(failed, 0, '1100 unsigned starts answered') + t.is(s.server.phoneStats().nonces, 0, 'start stores nothing') + const r = await s.post('/account/phone/send', { member: m.hex, nonce, signature: s.signFor(m, 'send', nonce), phone: PHONE_A }) + t.alike(r.body, { state: 'enviado' }) + t.is(s.server.phoneStats().nonces, 1, 'only the spent nonce is kept') +}) + test('phone limits: a 60 s cooldown, five sends a day per member, three per number', async (t) => { const s = await setup(t) const m = member() @@ -565,6 +592,112 @@ test('phone limits: refused sends never charge the daily ceiling, which answers t.alike((await s.step(late, 'send', { phone: PHONE_D })).body, { state: 'enviado' }, 'linked between two calls: the other ceiling') }) +test('phone limits: a full keyed window table refuses a new key and never evicts a live window', (t) => { + let now = 1_800_000_000_000 + const k = keyedCeiling(1, DAY, () => now, 2) + k.take('a') + k.take('b') + t.absent(k.has('c'), 'full of live windows: a new key is refused') + if (k.has('c')) k.take('c') + t.absent(k.has('a'), 'a stays limited') + t.absent(k.has('b'), 'b stays limited') + now += DAY + t.ok(k.has('c'), 'room once the windows expired') + k.take('c') + t.ok(k.has('a'), 'a new window for a') + t.is(maxKeysFor(200), 800, 'the routes size the tables from the daily ceiling') + t.exception.all(() => keyedCeiling(1, DAY, () => now), /max/) +}) + +// The phone routes alone, on a fake clock, with a fake provider that counts +// its sends and a store that holds nothing. +function bareRoutes (opts = {}) { + const c = { t: 1_800_000_000_000, sends: 0, logs: [] } + const iss = issuer() + const http = { + send: (res, status, body) => { res.status = status; res.body = body }, + readJsonBody: async (req) => req.body, + checkPost () {}, + RouteError: Error, + refuse: (token) => Object.assign(new Error(token), { token }), + keyedWindow: () => () => true, + fixedWindow: () => () => true + } + const client = { + send: async () => { c.sends++; return { ok: true, status: 'enviado' } }, + check: async () => ({ ok: false, reason: 'entrada' }) + } + const phones = { + available: () => true, + indexOf: (phone) => nodeCrypto.createHash('sha256').update(phone).digest('hex'), + verified: () => false, + live: () => null, + sweep: async () => {}, + settled: async () => {} + } + const routes = createPhoneRoutes({ + client, + phones, + association: iss.association, + store: { isFull: () => false }, + ageVerified: () => true, + linked: () => false, + deleted: () => false, + burnable: () => false, + log: (e) => c.logs.push(e.reason), + now: () => c.t, + http, + ...opts + }) + async function call (pathname, body) { + const res = {} + try { + await routes.handle({ method: 'POST', body }, res, new URL('http://127.0.0.1' + pathname)) + } catch (err) { + return { error: err.token } + } + return res.body + } + c.send = async (who, phone) => { + const { nonce } = await call('/account/phone/start', { member: who.hex }) + return call('/account/phone/send', { member: who.hex, nonce, signature: signPhone({ action: 'send', nonce, member: who.hex, association: iss.association }, who.kp), phone }) + } + c.routes = routes + return c +} + +test('phone limits: full pending codes refuse a send before the provider call, never evicting one', async (t) => { + const c = bareRoutes({ maxPending: 1 }) + const a = member() + const b = member() + t.alike(await c.send(a, PHONE_A), { state: 'enviado' }) + t.is(c.sends, 1) + t.alike(await c.send(b, PHONE_B), { error: 'limite-telefone' }, 'a pending code is never evicted') + t.is(c.sends, 1, 'the provider was not called') + t.alike(c.logs, ['enviado', 'tabela-cheia']) + c.t += 61 * 1000 + t.alike(await c.send(b, PHONE_B), { error: 'limite-telefone' }, 'a\'s code is still pending') + t.alike(await c.send(a, PHONE_A), { state: 'enviado' }, 'a member that holds an entry has room') + t.is(c.sends, 2) + t.is(c.routes.stats().pending, 1) + c.t += 600 * 1000 + t.alike(await c.send(b, PHONE_B), { state: 'enviado' }, 'room once a\'s code expired') + t.is(c.sends, 3) +}) + +test('phone limits: the keyed windows are sized from the daily ceiling and refuse a new key when full', async (t) => { + const c = bareRoutes({ maxWindows: 1 }) + const a = member() + t.alike(await c.send(a, PHONE_A), { state: 'enviado' }) + c.t += 601 * 1000 + t.alike(await c.send(member(), PHONE_B), { error: 'limite-telefone' }, 'a new member and number while the windows are full') + t.is(c.sends, 1) + c.t += DAY + t.alike(await c.send(member(), PHONE_B), { state: 'enviado' }, 'room once the windows expired') + t.exception.all(() => bareRoutes({ maxPending: 0 }), /maxPending/) + t.exception.all(() => bareRoutes({ maxWindows: 0 }), /max/) +}) + test('phone: two concurrent sends for one member make one provider call', async (t) => { const s = await setup(t) s.fake.script({ phoneSend: (req, res, ctx) => setTimeout(() => ctx.json(res, 200, { status: 'Success' }), 150) }) @@ -713,6 +846,17 @@ test('phone send: provider refusals map to tokens and log field names, never val noPersonalData(t, s, [m]) }) +test('phone: an expired code leaves memory on the next start, with no send or check for it', async (t) => { + const s = await setup(t) + const m = member() + await s.band(m) + t.alike((await s.step(m, 'send', { phone: PHONE_A })).body, { state: 'enviado' }) + t.is(s.server.phoneStats().pending, 1) + s.c.offset += 601 * 1000 + t.is((await s.start(member())).status, 200) + t.is(s.server.phoneStats().pending, 0, 'the number is gone') +}) + test('phone: a timeout on send leaves a pending entry that a later check approves', async (t) => { const s = await setup(t, { sendTimeoutMs: 200 }) s.fake.script({ phoneSend: () => {} }) @@ -1075,7 +1219,7 @@ test('phone limits: three wrong codes never open an early resend', async (t) => t.is(s.sends().length, 2) }) -test('phone: Excluir conta waits for the burn of a blocked member when the sweep fails; nobody else is held', async (t) => { +test('phone: Excluir conta waits for the burn of a blocked or once-blocked member when the sweep fails; nobody else is held', async (t) => { const s = await setup(t, { passkeys: true }) const enrol = async (who) => { const pk = createFakePasskey({ rpId: 'varanda.test' }) @@ -1119,6 +1263,14 @@ test('phone: Excluir conta waits for the burn of a blocked member when the sweep t.is(done.status, 200, done.text) t.ok(s.store.deletedAt(free.hex) !== null, 'a member who is not blocked is deleted') + const lifted = member() + await linkDirect(s.store, s.iss, lifted, 'lia') + const liftedKey = await enrol(lifted) + s.c.reports = { [lifted.hex]: 1 } + const waits = await remove(lifted, liftedKey) + t.alike(waits.body, { error: 'indisponivel' }, 'nor one unblocked whose old reports the sweep may not have cleared') + t.is(s.store.deletedAt(lifted.hex), null) + s.c.guardOk = true const later = await remove(holder, holderKey) t.is(later.status, 200, later.text) diff --git a/apps/cli/test/moderation-store.test.js b/apps/cli/test/moderation-store.test.js index 766df001..92ba124a 100644 --- a/apps/cli/test/moderation-store.test.js +++ b/apps/cli/test/moderation-store.test.js @@ -1547,3 +1547,71 @@ test('reopen: humanReversed remembers a reopened AI block a person later undid, t.is(later.get(r.id).status, 'descartar') t.is(later.humanReversed(target), true, 'the reopened AI block row still counts') }) + +test('held: published and pending blocks count, a pending unblock does not lift, an owner deletion block counts', async (t) => { + const { store, m } = setup(t) + const target = key() + const leaver = key() + t.absent(store.held(target), 'nothing at all') + t.absent(store.held('nope'), 'an invalid member is false') + const { report: row } = await store.add(report(target)) + const { change } = await store.decide(row.id, { decision: 'bloquear', by: MOD }) + t.ok(store.held(target), 'a pending moderator block holds') + await store.ack({ changeIds: [change.id], snapshot: m.snap(1, [target]), moderatorCert: m.cert }) + t.ok(store.held(target), 'published') + const u = await store.unblock(target, { by: MOD }) + t.ok(store.held(target), 'a pending unblock does not let go: it may still be cancelled') + await store.ack({ changeIds: [u.change.id], snapshot: m.snap(2, []), moderatorCert: m.cert }) + t.absent(store.held(target), 'unblocked') + + const del = await store.requestDeletion(target) + t.ok(store.held(target), 'the owner block, pending, holds') + await store.requestDeletion(leaver) + t.ok(store.held(leaver), 'so does one with no report behind it') + // Once published, the owner block is in the snapshot like any other. + await store.ack({ changeIds: [del.change.id], snapshot: m.snap(3, [target]), moderatorCert: m.cert }) + t.ok(store.held(target), 'a published key is held whoever asked') + t.is(store.pending().changes.length, 1, 'read-only: nothing else changed') +}) + +test('held: a lift waiting next to the claimed block it lifts still holds, and lets go once both publish', async (t) => { + const { store, m } = setup(t) + const target = key() + const { report: row } = await store.add(report(target)) + const { change } = await store.decide(row.id, { decision: 'bloquear', by: MOD }) + await store.pull() + const lift = await store.unblock(target, { by: MOD }) + t.is(lift.change.op, 'unblock', 'appended: the block is claimed') + t.ok(store.held(target), 'still held while both wait') + await store.ack({ changeIds: [change.id], snapshot: m.snap(1, [target]), moderatorCert: m.cert }) + t.ok(store.held(target), 'the block published, the lift still waits') + await store.ack({ changeIds: [lift.change.id], snapshot: m.snap(2, []), moderatorCert: m.cert }) + t.absent(store.held(target), 'both published') +}) + +test('blockReportsAfter: counts the bloquear reports decided at or after since, all of them with null', async (t) => { + const { store, c } = setup(t) + const target = key() + const other = key() + t.is(store.blockReportsAfter(target, null), 0) + const a = (await store.add(report(target))).report + const b = (await store.add(report(target))).report + const d = (await store.add(report(target))).report + const o = (await store.add(report(other))).report + await store.decide(a.id, { decision: 'bloquear', by: MOD }) + c.t += HOUR + const mid = new Date(c.t).toISOString() + c.t += 1000 + await store.decide(b.id, { decision: 'bloquear', by: AI_ACTOR }) + await store.decide(d.id, { decision: 'descartar', by: MOD }) + await store.decide(o.id, { decision: 'bloquear', by: MOD }) + t.is(store.blockReportsAfter(target, null), 2, 'descartar and another member do not count') + t.is(store.blockReportsAfter(target, mid), 1, 'only the one decided after since') + t.is(store.blockReportsAfter(target, new Date(c.t).toISOString()), 1, 'decided at since counts') + t.is(store.blockReportsAfter(target, new Date(c.t + 1).toISOString()), 0, 'decided before since does not') + t.is(store.blockReportsAfter('nope', null), 0) + t.exception.all(() => store.blockReportsAfter(target, '2026-10-24'), TypeError) + t.exception.all(() => store.blockReportsAfter(target, undefined), TypeError) + await store.reopen(b.id, { by: MOD }) + t.is(store.blockReportsAfter(target, mid), 0, 'a report a person reopened no longer counts') +}) diff --git a/apps/cli/test/phone-store.test.js b/apps/cli/test/phone-store.test.js index 937607c6..39ec4ed4 100644 --- a/apps/cli/test/phone-store.test.js +++ b/apps/cli/test/phone-store.test.js @@ -124,8 +124,9 @@ test('record round trip: exact file shape, mode 0600, since fixed, no digits on noDigits(t, file) const json = readFile(file) - t.alike(Object.keys(json), ['v', 'check', 'since', 'rows', 'released']) - t.is(json.v, 1) + t.alike(Object.keys(json), ['v', 'check', 'since', 'rows', 'released', 'cleared']) + t.is(json.v, 2) + t.alike(json.cleared, {}) t.ok(/^[0-9a-f]{64}$/.test(json.check)) t.is(json.since, iso(T0)) t.alike(json.released, {}) @@ -590,7 +591,14 @@ test('validation refuses what this module would not write', async (t) => { 'short iv': (j) => { j.rows[0].sealed.iv = 'AAAA' }, 'extra row key': (j) => { j.rows[0].phone = 'x' }, 'bad released member': (j) => { j.released = { x: iso(T0) } }, - 'bad released time': (j) => { j.released = { [a]: 'soon' } } + 'bad released time': (j) => { j.released = { [a]: 'soon' } }, + 'no cleared': (j) => { delete j.cleared }, + 'cleared not an object': (j) => { j.cleared = [] }, + 'bad cleared member': (j) => { j.cleared = { ['A'.repeat(64)]: iso(T0) } }, + 'bad cleared time': (j) => { j.cleared = { [a]: '2026-11-11' } }, + 'v 1 with cleared': (j) => { j.v = 1 }, + 'v 2 without cleared': (j) => { delete j.cleared }, + 'v 3': (j) => { j.v = 3 } } for (const [name, mutate] of Object.entries(variants)) { const j = JSON.parse(JSON.stringify(good)) @@ -1021,3 +1029,145 @@ test('a refused mutation adopts the disk state it read', async (t) => { await rejects(t, third.record({ member: b, phone: '+5531991234567' }, cbs), 'conta-excluida', 'refused') t.ok(third.verified(d), 'conta-excluida: disk adopted') }) + +// Issue #534: a member unblocked before Excluir conta must not have the old +// reports burn its number again once the deletion's own block publishes. +function clearedSetup (t) { + const base = setup(t) + const held = new Set() + // member -> decision times (ms) of its 'bloquear' reports. + const reports = new Map() + const listed = new Set() + const after = (m, since) => (reports.get(m) || []).filter((at) => since === null || iso(at) > since).length + const calls = [] + const rule = { + linked: base.cbs.linked, + deleted: base.cbs.deleted, + blocked: (m) => listed.has(m), + burnable: (m, since) => { + calls.push(['burnable', m, since]) + return listed.has(m) && (!base.deleted.has(m) || after(m, since) > 0) + }, + cleared: (m, since) => { + calls.push(['cleared', m, since]) + return !held.has(m) && after(m, since) > 0 + } + } + return { ...base, held, reports, listed, rule, calls } +} + +test('cleared: an unblocked member who deletes keeps no burn from the old reports', async (t) => { + const { store, file, c, rule, held, reports, listed, deleted } = clearedSetup(t) + const a = memberKey() + await store.record({ member: a, phone: PHONE }, rule) + reports.set(a, [T0 + 1000]) + held.add(a) + listed.add(a) + c.t = T0 + 2000 + const burnt = await store.sweep(rule) + t.is(burnt.burned, 1) + t.is(burnt.cleared, 0, 'never cleared while held') + t.alike(readFile(file).cleared, {}) + + held.delete(a) + listed.delete(a) + c.t = T0 + 3000 + const lifted = await store.sweep(rule) + t.is(lifted.unburned, 1) + t.is(lifted.cleared, 1) + t.alike(readFile(file).cleared, { [a]: iso(T0 + 3000) }) + const snap = snapshot(file) + c.t = T0 + 4000 + t.is((await store.sweep(rule)).cleared, 0, 'no report after the clear: nothing to do') + unchanged(t, file, snap, 'and nothing written') + + // Excluir conta: the owner block publishes, it alone holds nothing. + deleted.add(a) + listed.add(a) + c.t = T0 + 5000 + const out = await store.sweep(rule) + t.is(out.burned, 0, 'the old reports no longer burn it') + t.is(store.counts().burned, 0) + t.alike(await store.record({ member: memberKey(), phone: PHONE }, rule), { changed: true }, 'another member records it') +}) + +test('cleared: a report decided after the clear burns a deleted member again', async (t) => { + const { store, file, c, rule, held, reports, listed, deleted, calls } = clearedSetup(t) + const a = memberKey() + await store.record({ member: a, phone: PHONE }, rule) + reports.set(a, [T0 + 1000]) + c.t = T0 + 2000 + await store.sweep(rule) + t.alike(readFile(file).cleared, { [a]: iso(T0 + 2000) }, 'cleared at once: no block yet') + + reports.get(a).push(T0 + 3000) + held.add(a) + listed.add(a) + c.t = T0 + 4000 + calls.length = 0 + t.is((await store.sweep(rule)).burned, 1) + t.alike(calls.filter((x) => x[1] === a).map((x) => x[2]), [iso(T0 + 2000), iso(T0 + 2000)], 'both callbacks get the clear time') + deleted.add(a) + c.t = T0 + 5000 + await store.sweep(rule) + t.is(store.counts().burned, 1, 'burn kept after the deletion') + await rejects(t, store.record({ member: memberKey(), phone: PHONE }, rule), 'telefone-em-uso', 'still held') +}) + +test('cleared: set before the burns of the same sweep; release leaves it; dropped with the last row', async (t) => { + const { store, file, c, rule, reports, listed, deleted, linked } = clearedSetup(t) + const a = memberKey() + await store.record({ member: a, phone: PHONE }, rule) + reports.set(a, [T0 + 1000]) + // Deleted and listed (owner block) but no longer held: the clear in this + // very sweep keeps the burn from happening. + deleted.add(a) + listed.add(a) + c.t = T0 + 2000 + const out = await store.sweep(rule) + t.is(out.cleared, 1) + t.is(out.burned, 0, 'the burn already sees the clear') + t.is(out.ended, 1) + + c.t = T0 + 3000 + await store.release(a) + t.alike(readFile(file).cleared, { [a]: iso(T0 + 2000) }, 'release leaves cleared alone') + + // The ended row ages out: its member's entry goes with it. + linked.add(a) + c.t = T0 + 3000 + RETENTION_MS + const gone = await store.sweep(rule) + t.is(gone.removed, 1) + t.is(gone.cleared, 1) + t.alike(readFile(file).rows, []) + t.alike(readFile(file).cleared, {}, 'no rows, no entry') +}) + +test('cleared: a version 1 file reads and the next write makes it version 2', async (t) => { + const { store, open, file, c, cbs, linked } = setup(t) + const a = memberKey() + linked.add(a) + await store.record({ member: a, phone: PHONE }, cbs) + const v1 = readFile(file) + delete v1.cleared + v1.v = 1 + writeFile(file, v1) + const old = open() + t.ok(old.available(), 'version 1 still reads') + t.ok(old.verified(a)) + const snap = snapshot(file) + await old.sweep(cbs) + unchanged(t, file, snap, 'a sweep with nothing to do keeps version 1') + c.t = T0 + 1000 + await old.end(a, 'trocado') + const json = readFile(file) + t.is(json.v, 2) + t.alike(Object.keys(json), ['v', 'check', 'since', 'rows', 'released', 'cleared']) + t.alike(json.cleared, {}) + t.ok(open().available(), 'and reads back') +}) + +test('cleared must be a function when given', async (t) => { + const { store, cbs } = setup(t) + await t.exception.all(store.sweep({ ...cbs, cleared: 1 }), TypeError) +}) diff --git a/apps/cli/test/start-nonces.test.js b/apps/cli/test/start-nonces.test.js new file mode 100644 index 00000000..73e0c049 --- /dev/null +++ b/apps/cli/test/start-nonces.test.js @@ -0,0 +1,128 @@ +'use strict' + +// apps/cli/lib/account/start-nonces.js: the stateless nonces of the unsigned +// phone and age start routes. A fake clock throughout. + +const test = require('brittle') +const nodeCrypto = require('node:crypto') +const { createStartNonces, spentCapacity, MAX_SPENT } = require('../lib/account/start-nonces') + +const TTL = 600 * 1000 +const TOKEN_RE = /^[A-Za-z0-9_-]{43}$/ + +function hex () { + return nodeCrypto.randomBytes(32).toString('hex') +} + +function clock (start = 1_800_000_000_000) { + const c = { t: start } + c.now = () => c.t + return c +} + +test('start nonces: a 43-character token that spends once, for its member only', (t) => { + const c = clock() + const n = createStartNonces({ label: 'varanda-phone-start-v1', now: c.now }) + const a = hex() + const b = hex() + const nonce = n.mint(a) + t.ok(TOKEN_RE.test(nonce), 'the wire format clients already handle') + t.is(Buffer.from(nonce, 'base64url').length, 32) + t.is(n.size(), 0, 'minting stores nothing') + t.absent(n.spend(b, nonce), 'minted for another member') + t.ok(n.spend(a, nonce)) + t.absent(n.spend(a, nonce), 'a second spend is refused') + t.is(n.size(), 1) + t.not(n.mint(a), n.mint(a), 'random per mint') +}) + +test('start nonces: expired, malformed and tampered nonces are refused', (t) => { + const c = clock() + const n = createStartNonces({ label: 'varanda-phone-start-v1', now: c.now }) + const a = hex() + const late = n.mint(a) + c.t += TTL + 1000 + t.absent(n.spend(a, late), 'expired') + + const nonce = n.mint(a) + const raw = Buffer.from(nonce, 'base64url') + for (let i = 0; i < raw.length; i++) { + const bad = Buffer.from(raw) + bad[i] ^= 1 + t.absent(n.spend(a, bad.toString('base64url')), 'byte ' + i + ' tampered') + } + // The last character carries 2 spare bits: another spelling of the same bytes. + const last = nonce[42] + const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_' + const respelled = nonce.slice(0, 42) + alphabet[alphabet.indexOf(last) ^ 1] + t.alike(Buffer.from(respelled, 'base64url'), raw, 'decodes to the same bytes') + t.absent(n.spend(a, respelled), 'a non-canonical spelling is refused') + for (const v of [undefined, null, 42, '', nonce.slice(0, 42), nonce + 'A', 'A'.repeat(43), nonce.replace(/.$/, '=')]) { + t.absent(n.spend(a, v), 'malformed: ' + String(v)) + } + t.absent(n.spend('A'.repeat(64), nonce), 'a malformed member') + t.ok(n.spend(a, nonce), 'the untouched nonce still spends') +}) + +test('start nonces: a phone nonce never spends at the age table, nor after a restart', (t) => { + const c = clock() + const a = hex() + const phone = createStartNonces({ label: 'varanda-phone-start-v1', now: c.now }) + const age = createStartNonces({ label: 'varanda-age-start-v1', now: c.now }) + t.absent(age.spend(a, phone.mint(a)), 'another route') + const restarted = createStartNonces({ label: 'varanda-phone-start-v1', now: c.now }) + const nonce = phone.mint(a) + t.absent(restarted.spend(a, nonce), 'a second instance has another secret') + t.ok(phone.spend(a, nonce)) +}) + +test('start nonces: a full spent table refuses instead of evicting, and frees room as entries expire', (t) => { + const c = clock() + const n = createStartNonces({ label: 'varanda-phone-start-v1', now: c.now, max: 2 }) + const a = hex() + const first = n.mint(a) + const second = n.mint(a) + const third = n.mint(a) + t.ok(n.spend(a, first)) + t.ok(n.spend(a, second)) + t.absent(n.spend(a, third), 'full of live entries: refused') + t.absent(n.spend(a, first), 'the first spent entry was not evicted') + t.is(n.size(), 2) + c.t += TTL + 1000 + const fresh = n.mint(a) + t.ok(n.spend(a, fresh), 'room again once the spent entries expired') + t.is(n.size(), 1) + t.is(MAX_SPENT, 16384) +}) + +test('start nonces: a clock that steps back never revives a spent nonce', (t) => { + const c = clock() + const n = createStartNonces({ label: 'varanda-phone-start-v1', now: c.now, max: 1 }) + const a = hex() + const nonce = n.mint(a) + t.ok(n.spend(a, nonce)) + // Forward past the expiry (the entry is pruned to make room), then back. + c.t += TTL + 1000 + t.ok(n.spend(a, n.mint(a))) + c.t -= TTL + t.absent(n.spend(a, nonce), 'held clock: still expired') + c.t -= 10 * TTL + t.absent(n.spend(a, nonce), 'a large step back draws a new secret') + t.ok(n.spend(a, n.mint(a)), 'new nonces work') +}) + +test('start nonces: malformed options throw', (t) => { + t.exception.all(() => createStartNonces({}), /label/) + t.exception.all(() => createStartNonces({ label: 'a\nb' }), /label/) + t.exception.all(() => createStartNonces({ label: 'x', max: 0 }), /max/) + t.exception.all(() => createStartNonces({ label: 'x', ttlMs: 10 }), /ttlMs/) + t.exception.all(() => createStartNonces({ label: 'x' }).mint('zz'), /member/) +}) + +test('start nonces: the spent table grows with the token bucket, never below the floor', (t) => { + t.is(spentCapacity(20, 100), MAX_SPENT, 'the default bucket fits the floor') + t.ok(20 * TTL / 1000 + 100 <= MAX_SPENT) + t.is(spentCapacity(100, 100), 100 * 600 + 100, 'a faster bucket: one TTL of spends plus the burst') + t.is(spentCapacity(1, 1), MAX_SPENT) + t.is(spentCapacity(30, 50, 1000), MAX_SPENT, 'a shorter TTL') +}) diff --git a/docs/changelog/fix-phone-verification-leftovers.md b/docs/changelog/fix-phone-verification-leftovers.md new file mode 100644 index 00000000..c13ba8a3 --- /dev/null +++ b/docs/changelog/fix-phone-verification-leftovers.md @@ -0,0 +1,6 @@ +### Corrigido + +- `/account/phone/start` e `/account/age/start` não guardam mais nada por pedido: o código de uso único é assinado pelo serviço de conta e traz a própria validade (10 min), e só o código já usado fica numa tabela, que recusa o pedido quando enche em vez de apagar o mais antigo (#534; PR `fix/phone-verification-leftovers`). Verificação em `docs/verification/fix-phone-verification-leftovers.md`. +- Os limites do celular por membro e por número, os envios pendentes e o intervalo entre envios têm tamanho calculado a partir dos tetos diários e nunca apagam uma entrada ainda valendo; cheios, recusam com `limite-telefone` e registram `tabela-cheia`. O número de um envio pendente sai da memória quando o código vence, mesmo sem outro pedido. A tabela dos códigos de início já usados cresce com `VARANDA_ACCOUNT_RATE` e a rajada, nunca abaixo de 16384 (#534). +- Em Ajustes, "Trocar o celular" compara a data da confirmação antes e depois: diz "Celular atualizado." quando o número mudou e "Esse já é o seu celular." quando o número digitado já era o da conta (sem mandar SMS); depois de uma conferência sem resposta clara que ainda mostra o número antigo, fica na tela para confirmar o código de novo (#534). +- Um membro desbloqueado que depois exclui a conta não tem mais o número preso pelas denúncias do bloqueio desfeito: o `phone.json` passa à versão 2, com o mapa `cleared`, e um arquivo da versão 1 ainda abre. Depois da primeira gravação na versão 2, um serviço anterior não abre mais o arquivo: guarde um backup antes de atualizar. Uma denúncia decidida como bloquear depois da exclusão, ou enquanto uma exclusão que falhou espera, continua prendendo o número, e uma exclusão com denúncias antigas espera quando a varredura do celular falha (decisão do dono, 2026-11-17; #534). diff --git a/docs/design.md b/docs/design.md index 04e0d546..d5da1886 100644 --- a/docs/design.md +++ b/docs/design.md @@ -244,7 +244,12 @@ Todo membro hospedado confirma um celular brasileiro (`+55`) com um código de u **Lembrada por conta.** O nó hospedado guarda um atestado `phone-verified`, assinado pela chave do emissor e sem o número, para que um membro verificado abra o app sem o serviço de conta, e o atestado `phone-since`, que marca que a associação exige um celular. Um registro do aparelho nunca abre a porta (regra do dono de 2026-11-04, estendida ao celular em 2026-11-11). Sem nenhuma das duas provas e sem resposta do serviço, uma instalação que nunca exigiu celular abre como antes. -**Desbloqueio e liberação por ordem judicial.** Decisão do dono (2026-11-11). O desbloqueio devolve o número na varredura seguinte, se o bloqueio durou menos de 180 dias; depois disso o número selado já foi apagado e o membro verifica de novo (`telefone-pendente`). A liberação por ordem judicial libera o número para uma conta nova, e a chave antiga continua bloqueada. Depois da liberação o número selado fica até 180 dias. Sujeita a revisão jurídica. +**Desbloqueio e liberação por ordem judicial.** Decisão do dono (2026-11-11). O desbloqueio devolve o número na varredura seguinte, se o bloqueio durou menos de 180 dias; depois disso o número selado já foi apagado e o membro verifica de novo (`telefone-pendente`). A liberação por ordem judicial libera o número para uma conta nova, e a chave antiga continua bloqueada. Depois da liberação o número selado fica até 180 dias. Sujeita a revisão jurídica. Um membro desbloqueado que depois exclui a conta não tem o número preso de novo pelas denúncias do bloqueio desfeito: o bloqueio que a exclusão publica só prende o número por uma denúncia decidida depois do desbloqueio (decisão do dono, 2026-11-17). + +**Limites aceitos.** Decisão do dono (2026-11-17), registrada aqui para não virar dívida esquecida: + +- Entre o envio do código e a conferência, o serviço de conta guarda o número em memória, sem cifra, por até 10 minutos, porque a conferência no Didit precisa dele. Fica só na memória do processo, nunca em disco nem em log, e uma reinicialização o esquece. Cifrar com uma chave do mesmo processo pouco protegeria; protegeria de verdade só com uma mudança no protocolo, em que o app guardasse a chave. +- Se o app não consegue ler a política do celular e o nó ainda não guarda o atestado `phone-since`, o passo fica desligado naquela abertura, porque nada assinado diz que a instalação exige celular. A leitura é repetida (5 s, 15 s e depois a cada 60 s) e, quando responde, o passo volta a reter o app. Enquanto isso o serviço continua recusando vínculo, troca de @nome, convites, push, gravação de lidas, criação de página e códigos da Feira. Fechar o passo nesse caso travaria toda abertura hospedada durante qualquer queda do serviço de conta. ## LGPD diff --git a/docs/protocol.md b/docs/protocol.md index c1ffec4d..b180dfc4 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -113,15 +113,15 @@ Member recovery: extra passkeys and the recovery code (`packages/web-member/lib/ - `POST /account/recovery/put` `{ member, nonce, signature, kind, lookupId, blob }`, `POST /account/recovery/remove` `{ member, nonce, signature, kind, lookupId }` and `POST /account/recovery/list` `{ member, nonce, signature }`. Bodies: put -> `{ createdAt, changed }`, remove -> `{ changed }` (`changed` false for a no-op: the entry was already there, or already gone), list -> `{ entries: [{ lookupId, kind, createdAt }] }` (never the nonce or ciphertext). For each: the nonce must be one this process minted for that member, live and not yet spent; then the statement is verified with the service's association and, for put, `blobHash` recomputed from the validated blob; a per-member window (10 per 600 s) is charged only after the proof, then the nonce is recorded as spent until its own expiry (a refused proof spends nothing, so the spent set grows only with validly signed requests), then the link is checked, then the store. A put or remove that fails after a possible write (answered 503 `resultado-incerto`: a lost lock or a failed write) is an unknown outcome: the app keeps its unknown-outcome handling and never retries by itself; listing settles it. - `POST /account/recovery/fetch` `{ lookupId }` -> `{ member, kind, blob }` or 404 `{ "error": "nao-encontrado", "recovery": true }`. The `recovery: true` mark tells this route's miss from any other 404 (an unknown route of an older service, a proxy page): clients signing in with a marked passkey or entering a code read only the marked body as "no entry" and treat every other 404 as the service being unavailable (a sign-in that cannot ask stays locked; a passkey without the mark is never looked up). The `lookupId` travels only in a POST body, never in a path or query string. A malformed id answers `pedido-invalido` without touching the store, and neither unknown nor malformed ids grow any state. It is charged on the shared lookup window and the global bucket only, with no per-IP limit (the service never reads the client address). - Recovery statement (`packages/core/lib/recovery-proof.js`): the UTF-8 bytes of `'varanda-recovery-v1'`, action (`'put'`, `'remove'` or `'list'`), nonce, member, association, kind, `lookupId`, `blobHash` joined by LF with no trailing LF, signed by the member's diary key. `kind` and `lookupId` are `''` for list; `blobHash` is `''` except for put, where it is the lowercase hex BLAKE2b-256 (`hypercore-crypto` `hash`) of utf8(kind + LF + `lookupId` + LF + `blob.nonce` + LF + `blob.ciphertext`). The action is signed, so a put never verifies as a remove or a list. -- `/phone.json` (`apps/cli/lib/account/phone-store.js`) holds the verified phone numbers. It exists only once a first number was verified with `VARANDA_PHONE_KEY` set; it is ONE sidecar file, mode `0o600`, replaced whole through `writeJsonAtomic`, and never part of the directory files. Shape: `{ v: 1, check, since, rows, released }`. `check` is the lowercase hex HMAC-SHA256 that ties the file to its key: two subkeys are derived from the 32-byte `VARANDA_PHONE_KEY` (HMAC-SHA256 under the labels `'varanda-phone-seal-v1'` and `'varanda-phone-index-v1'`) and `check` is the index subkey's HMAC of `'varanda-phone-check-v1'`, so a file written under another key fails closed instead of being rewritten. `since` is the canonical ISO time of the first verification. Each row is exactly `{ member, index, sealed, verifiedAt, endedAt, end, burnedAt }`: `member` the diary key (hex64); `index` the lowercase hex HMAC of the E.164 number under the index subkey (uniqueness and burns compare it, never the number); `sealed` `{ iv, tag, data }` (canonical base64, AES-256-GCM under the seal subkey with the AAD `'varanda-phone-v1\n' + member`, so a seal moved to another member's row never opens) or `null` once only a burn is left; `verifiedAt` canonical ISO; `end` `null` (live) or one of `'trocado'`, `'excluida'`, `'substituido'`, `'liberado'`, with `endedAt` set exactly when `end` is; `burnedAt` canonical ISO or `null` (the number of an owner blocked by the moderation desk stays taken while the block lasts). At most one live row per member and per index. `released` maps a member to the time of a court-ordered release (`account phone --release`). Retention: an ended or burned row keeps its seal 180 days, then a burn keeps only the index and an ended row goes; a live row of a key that never linked goes after 7 days (`apps/cli/lib/account/phone-routes.js` sweeps at start and every hour). Validation is total: a file the store would not have written (unknown key, bad shape, another `check`) is never rewritten, and `send`, `check`, `status` and, when the service has an issuer, `since` then answer 503 `indisponivel`, while `policy` answers 200 `{ required: true }`, `start` answers 200 `{ nonce }` and `since` without an issuer answers 200 `{ since: null }` (none of these three reads the store). The number is in no certificate, swarm message, log line, moderation view or `account export`; only the operator command `account phone --member ` (no HTTP route) prints it, also reached by name with `account phone --username `, which prints at most one line `{ username, key, kind, current, deletedAt, phone }` for the name's single holder (`nameHolder`, current or past; a page prints `owner` and no number). +- `/phone.json` (`apps/cli/lib/account/phone-store.js`) holds the verified phone numbers. It exists only once a first number was verified with `VARANDA_PHONE_KEY` set; it is ONE sidecar file, mode `0o600`, replaced whole through `writeJsonAtomic`, and never part of the directory files. Shape: `{ v: 2, check, since, rows, released, cleared }` (a `{ v: 1, check, since, rows, released }` file still reads, with nothing cleared, and the next write makes it version 2). `check` is the lowercase hex HMAC-SHA256 that ties the file to its key: two subkeys are derived from the 32-byte `VARANDA_PHONE_KEY` (HMAC-SHA256 under the labels `'varanda-phone-seal-v1'` and `'varanda-phone-index-v1'`) and `check` is the index subkey's HMAC of `'varanda-phone-check-v1'`, so a file written under another key fails closed instead of being rewritten. `since` is the canonical ISO time of the first verification. Each row is exactly `{ member, index, sealed, verifiedAt, endedAt, end, burnedAt }`: `member` the diary key (hex64); `index` the lowercase hex HMAC of the E.164 number under the index subkey (uniqueness and burns compare it, never the number); `sealed` `{ iv, tag, data }` (canonical base64, AES-256-GCM under the seal subkey with the AAD `'varanda-phone-v1\n' + member`, so a seal moved to another member's row never opens) or `null` once only a burn is left; `verifiedAt` canonical ISO; `end` `null` (live) or one of `'trocado'`, `'excluida'`, `'substituido'`, `'liberado'`, with `endedAt` set exactly when `end` is; `burnedAt` canonical ISO or `null` (the number of an owner blocked by the moderation desk stays taken while the block lasts). At most one live row per member and per index. `released` maps a member to the time of a court-ordered release (`account phone --release`). `cleared` maps a member (hex64) to the canonical ISO time the sweep last saw it under no block (not in the published list, and no change for it still waiting for the operator, Excluir conta's own block included) while it had `'bloquear'` reports decided at or after its previous `cleared` time; once a member's account is deleted, only a `'bloquear'` report decided at or after that time burns its number, so the reports of a block lifted before Excluir conta never hold it again (a live member's number still burns while it is listed at all). An entry goes once its member has no rows left. Retention: an ended or burned row keeps its seal 180 days, then a burn keeps only the index and an ended row goes; a live row of a key that never linked goes after 7 days (`apps/cli/lib/account/phone-routes.js` sweeps at start and every hour). Validation is total: a file the store would not have written (unknown key, bad shape, another `check`) is never rewritten, and `send`, `check`, `status` and, when the service has an issuer, `since` then answer 503 `indisponivel`, while `policy` answers 200 `{ required: true }`, `start` answers 200 `{ nonce }` and `since` without an issuer answers 200 `{ since: null }` (none of these three reads the store). The number is in no certificate, swarm message, log line, moderation view or `account export`; only the operator command `account phone --member ` (no HTTP route) prints it, also reached by name with `account phone --username `, which prints at most one line `{ username, key, kind, current, deletedAt, phone }` for the name's single holder (`nameHolder`, current or past; a page prints `owner` and no number). - Phone routes (`apps/cli/lib/account/phone-routes.js`), HTTPS from the app to the account service, never from the swarm. The POSTs have the same origin check as the other account POSTs and a 4096-byte body cap. The feature is on when the service has both a phone client and a phone store (`VARANDA_PHONE_KEY` set), even when the store could not open: then the gate stays shut and the routes answer `indisponivel`. - `GET /account/phone/policy` -> exactly `{ required }` (also with the feature off). - `GET /account/phone/since` -> `{ since: null | PhoneSince }` (section 3 "Phone attestations"): `null` while the feature is off, without an issuer or before a first verification; an unreadable store answers 503 `indisponivel`, never `null`. - - `POST /account/phone/start` `{ member }` -> `{ nonce }` (single use, 10 minutes, in memory). It reads no state; with the feature off it answers 503 `indisponivel`. + - `POST /account/phone/start` `{ member }` -> `{ nonce }` (single use, 10 minutes). The nonce stays an opaque 43-character token; it is stateless (`apps/cli/lib/account/start-nonces.js`, a MAC under a per-process secret over the member and its expiry), so the service keeps no table of issued nonces, only of spent ones until they expire, and a restart expires every outstanding nonce. A full spent table refuses the spend (`expirado`) instead of evicting a live entry. It reads no state; with the feature off it answers 503 `indisponivel`. - `POST /account/phone/send` `{ member, nonce, signature, phone }` (signature: the phone-verification request for `'send'`, section 3 "Reports and operator requests"; `phone` a Brazilian mobile in E.164, `+55` and 11 digits; a `channel` field is refused) -> `{ state: 'enviado' }` once the provider was asked to text a 6-digit code by SMS, or `{ state: 'verificado', proof? }` when that number is already the member's. It needs the member's age band (`idade-pendente` otherwise) and, for a key without a link, room in the directory (`lista-de-espera`). It answers the same for a free, a taken and a burned number. - `POST /account/phone/check` `{ member, nonce, signature, code }` (`code` 6 digits) -> `{ state: 'verificado', proof? }`, where `proof` is a phone-verified attestation dated the row's `verifiedAt` when the service has an issuer. Only after a correct code is the number checked against the others (`telefone-em-uso`). - `POST /account/phone/status` `{ member, nonce, signature }` -> `{ state: 'verificado', proof? }` or `{ state: 'nenhum' }`. - - Errors (`{ error }`): 400 `pedido-invalido`, `assinatura-invalida`, `telefone-invalido`, `codigo-invalido`; 403 `idade-pendente`; 409 `telefone-em-uso`, `telefone-recusado` (landline, VoIP or disposable line), `conta-excluida`; 410 `codigo-expirado` (no code pending, the code expired or the attempts are used up); 429 `limite-telefone` (5 sends per member and 3 per number per day, 60 s between sends, 10 checks and 30 status reads per member per 10 minutes); 503 `lista-de-espera`, `indisponivel` (feature off, store unreadable, daily ceiling, or the provider refused the request) and `resultado-incerto` (a send or check whose outcome is unknown; the client never repeats it on its own); the nonce errors are `expirado` and `assinatura-invalida` as for the age routes. + - Errors (`{ error }`): 400 `pedido-invalido`, `assinatura-invalida`, `telefone-invalido`, `codigo-invalido`; 403 `idade-pendente`; 409 `telefone-em-uso`, `telefone-recusado` (landline, VoIP or disposable line), `conta-excluida`; 410 `codigo-expirado` (no code pending, the code expired or the attempts are used up); 429 `limite-telefone` (5 sends per member and 3 per number per day, 60 s between sends, 10 checks and 30 status reads per member per 10 minutes; a send is also refused, before any provider call, while the per-member and per-number windows or the pending codes are full of live entries, at most 4 times the daily ceiling, since no live entry is ever evicted); 503 `lista-de-espera`, `indisponivel` (feature off, store unreadable, daily ceiling, or the provider refused the request) and `resultado-incerto` (a send or check whose outcome is unknown; the client never repeats it on its own); the nonce errors are `expirado` and `assinatura-invalida` as for the age routes. - The gate: with the feature on, `POST /account/finish`, `/account/rename/finish` and `/account/invites/finish`, and after the signature and the linked check the push finish for `on`, the seen finish for `write` and a page create by the member (not by a delegate), answer 403 `telefone-pendente` until the member holds a live sealed row. `POST /account/authorize` is not on this gate: the member Google sign-in is retired and that route answers 410 `versao-antiga` before any check. Push `off`, seen `read` and `remove`, terms, deletion, recovery and passkeys are never gated. For Feira codes a seller (author or page owner) with no live row counts as not linked, so the route answers 404 `nao-encontrado` as for an unlinked owner. The number never appears in a certificate or a swarm message; the phone-verified attestation carries only the member key and a date. - Followed logs (replicas) are `store.get({ key: b4a.from(hex, 'hex'), valueEncoding: 'json' })` (`openReplica`); they are never writable. Their blocks are read only with `core.get(i, { raw: true, ... })` followed by `decodeBlock` (R4.1), never through the JSON value encoding. - A not-yet-accepted log is NEVER opened in the main Corestore; its block 0 is fetched through the quarantine store (section 4, R5.4). An empty core must not exist in the main store. @@ -823,7 +823,7 @@ A report is neither a diary record nor a message on any swarm channel: it travel - **Signup-invite request** (`packages/core/lib/invite.js`, signed by the member's diary key, RPC `invite.sign`, `docs/rpc.md` 5.30): `'varanda-invite-v1'`, action (`'issue'` or `'summary'`), nonce, member, association, with no date (the account service records its own). Sent over HTTPS to the account service only (`POST /account/invites/start`, `POST /account/invites/finish` and `POST /account/invites/summary`) by a linked member asking for one signup invite (`issue`) or reading their own weekly allowance (`summary`, which mints nothing and answers `{ mode, perWeek, opened, used, remaining, resetsAt }`; the action is a signed line, so a signature for one never verifies as the other); the account service keeps only a SHA-256 of the issued code in its `invites.json`, the statement never travels on a swarm channel, and it carries no e-mail, name, `sub` or key of the invited person. - **Invite card** (`packages/core/lib/invite-card.js`, signed by the member's diary key, RPC `inviteCard.sign`, `docs/rpc.md` 5.101): `'varanda-invite-card-v1'`, code, design, expires (decimal), nameDigest, messageDigest, member, association, where the digests are the lowercase hex BLAKE2b-256 of the UTF-8 bytes of the name and of the message, always computed by the signer. It is the greeting a member attaches to a signup invite link: it travels only in the link's URL fragment (`#c1.` plus base64url), never to the account service and never on a swarm channel, and it carries no e-mail. A reader checks it with `inviteCard.verify` (5.102); it proves only that this key wrote this greeting for this code and association until `expires`. - **Push opt-in** (`packages/core/lib/push-proof.js`, signed by the member's diary key, RPC `push.sign`, `docs/rpc.md` 5.31): `'varanda-push-v1'`. The fields, the canonical endpoint and the routes are under "Push relay" above. HTTPS to the account service only, never a swarm channel and never a diary block. -- **Age-verification request** (`packages/core/lib/age.js`, signed by the member's diary key, RPC `age.sign`, `docs/rpc.md` 5.32): `'varanda-age-v1'`, action (`'session'` or `'result'`), nonce, member, association, with no date (the account service records its own). Sent over HTTPS to the account service only (`POST /account/age/session` and `POST /account/age/result`) by a hosted member asking to start an age verification or to read its result. It proves only that the member asked, never an age: the account service keeps only the age band (with the method and its own date) in its `age.json`, never a birth date, a document or a provider session, and the statement never travels on a swarm channel. +- **Age-verification request** (`packages/core/lib/age.js`, signed by the member's diary key, RPC `age.sign`, `docs/rpc.md` 5.32): `'varanda-age-v1'`, action (`'session'` or `'result'`), nonce, member, association, with no date (the account service records its own). Sent over HTTPS to the account service only (`POST /account/age/session` and `POST /account/age/result`) by a hosted member asking to start an age verification or to read its result. The nonce comes from `POST /account/age/start` `{ member }` -> `{ nonce }` (single use, 10 minutes, no proof): an opaque 43-character token, stateless like the phone start nonce (`apps/cli/lib/account/start-nonces.js`, under its own label, so a phone nonce never spends at the age routes), so the service keeps no table of issued nonces, only of spent ones until they expire. It proves only that the member asked, never an age: the account service keeps only the age band (with the method and its own date) in its `age.json`, never a birth date, a document or a provider session, and the statement never travels on a swarm channel. - **Phone-verification request** (`packages/core/lib/phone.js`, signed by the member's diary key, RPC `phone.sign`, `docs/rpc.md` 5.115): `'varanda-phone-v1'`, action (`'send'`, `'check'` or `'status'`), nonce, member, association, with no date (the account service records its own). Sent over HTTPS to the account service only by a hosted member asking to send a code, check a code, or read the status of that verification. It proves only that the member asked: the statement carries no phone number and no code, and it is never a swarm message, a diary block or a certificate field. - **Age-verified attestation** (`packages/core/lib/age-proof.js`, signed by the account service's issuer key, not by a member): `'varanda-age-verified-v1'`, member, date, association, issuer, issuerDate, issuerSignature. Format and verification under "Age attestations" (section 3). Sent over HTTPS by the account service to the member's own client only, kept only in that client's node storage, never a diary block and never a swarm message; it carries no age band. - **Age-since attestation** (`packages/core/lib/age-proof.js`, signed by the account service's issuer key, not by a member): `'varanda-age-since-v1'`, since, date, association, issuer, issuerDate, issuerSignature. Format and verification under "Age attestations" (section 3). Same transport and storage as the age-verified attestation. diff --git a/docs/verification/fix-phone-verification-leftovers.md b/docs/verification/fix-phone-verification-leftovers.md new file mode 100644 index 00000000..e297e7b0 --- /dev/null +++ b/docs/verification/fix-phone-verification-leftovers.md @@ -0,0 +1,68 @@ +# fix/phone-verification-leftovers + +Fecha a #534 (sobras da verificação de celular, serviço `account` e app). + +## O que mudou + +- `apps/cli/lib/account/start-nonces.js` (novo): códigos de início sem estado para `/account/phone/start` e `/account/age/start`. O código traz a própria validade (10 min) e um HMAC sob um segredo do processo, preso à rota e à chave do membro. Só os códigos já usados ficam numa tabela, que recusa (`expirado`) quando enche em vez de apagar o mais antigo. O tamanho dela vem do balde global (`spentCapacity`: taxa x 10 min + rajada, nunca abaixo de 16384). Um relógio que volta não revive um código usado. +- `apps/cli/lib/account/phone-routes.js`: as tabelas dos limites por membro e por número, dos envios pendentes e do intervalo entre envios têm tamanho `4 x VARANDA_PHONE_DAILY_LIMIT` e nunca apagam uma entrada valendo. Cheias, o envio recusa com `limite-telefone` antes de chamar o Didit e o registro mostra `tabela-cheia`. O envio pendente, que guarda o número, sai da memória quando o código vence: por um temporizador próprio e também no próximo início. +- `apps/cli/lib/account/phone-store.js`, `moderation-store.js` e `server.js`: um membro desbloqueado que depois exclui a conta não tem o número preso de novo pelas denúncias do bloqueio desfeito (decisão do dono, 2026-11-17). O `phone.json` passa à versão 2, com o mapa `cleared`: a varredura anota quando viu o membro sem bloqueio depois das denúncias. Uma denúncia decidida como bloquear depois da exclusão continua prendendo o número. `held` conta qualquer mudança do membro que ainda espera o operador, inclusive o bloqueio da própria exclusão: nenhum membro é liberado enquanto ela espera (nem depois de uma exclusão que falhou no meio, nem com um desbloqueio pendente ao lado do bloqueio que ele desfaz, que pode ser cancelado). Uma denúncia decidida no mesmo milissegundo da marca conta como posterior. Se a varredura falhar durante Excluir conta, a exclusão de um membro bloqueado ou com denúncias de bloqueio espera (`indisponivel`). +- App, Ajustes > "Trocar o celular" (`phone.js`, `usePhoneGate.js`, `Telefone.js`, `Ajustes.js`, `App.js`): o resultado vem da data da confirmação antes e depois. Um envio que o serviço responde com `verificado` diz "Esse já é o seu celular." (nenhum código enviado). Uma data nova diz "Celular atualizado.". Depois de uma conferência sem resposta clara que ainda mostra a data antiga, a tela continua aberta para confirmar o código. Nos outros casos aparece "Não deu para saber se o número mudou.". A linha só aparece numa conta hospedada, com passkey, destravada e com o passo do celular liberado (`phoneChangeShown`). +- Documentos: `docs/protocol.md` (código de início, recusa com as tabelas cheias, `phone.json` v2), `docs/design.md` (limites aceitos pelo dono, a nova regra das denúncias) e o `README.md` (limites, `tabela-cheia`, backup antes de atualizar, ordem judicial). + +## Testes + +- `apps/cli/test/start-nonces.test.js` (novo, 7 testes): uso único preso ao membro; vencido, malformado ou adulterado é recusado; um código do celular não vale na idade nem depois de reiniciar; a tabela cheia recusa e libera espaço quando vence; o relógio que volta; opções inválidas; o tamanho que cresce com o balde. +- `apps/cli/test/account-phone-burn.test.js` (novo, 9 testes, lojas reais e a lista assinada como no `mod apply`): desbloqueado antes de excluir não volta a prender; excluir com o bloqueio em vigor mantém; bloqueio decidido e ainda não publicado na exclusão prende quando publica; denúncia decidida depois da exclusão prende, mesmo com uma varredura antes da publicação; denúncia decidida enquanto uma exclusão que falhou espera prende; desbloqueio publicado sem varredura antes de excluir é liberado pela varredura da própria exclusão; desbloqueio de um bloqueio já pego pelo operador, cancelado antes da publicação, não libera nada; denúncia nova depois do desbloqueio prende de novo; desbloqueio pendente não solta nada. +- `apps/cli/test/account-phone.test.js`: inundação de inícios não apaga o código de um membro; tabela cheia recusa sem apagar janela valendo; envios pendentes cheios recusam antes do Didit; tamanho das tabelas a partir do teto diário; Excluir conta espera com a varredura falhando para membro bloqueado ou com denúncias antigas, e só para eles; um código vencido sai da memória no próximo início. +- `apps/cli/test/account-age.test.js`: inundação de inícios da idade. +- `apps/cli/test/phone-store.test.js`: o mapa `cleared` (5 testes, incluindo ler um arquivo da versão 1 e gravar na 2). +- `apps/cli/test/moderation-store.test.js`: `held` (o bloqueio pendente da exclusão conta, e um desbloqueio pendente ao lado do bloqueio pego pelo operador também) e `blockReportsAfter` (a denúncia decidida no instante `since` conta). +- `apps/app/test/phone.test.js`: `phoneChange`, `phoneChangeOutcome`, `phoneChangeShown`, e Ajustes e Telefone usando essas regras. +- `apps/app/test/usePhoneGate.test.js`: `proofDate` (inclusive um `markVerified` sem prova que mantém a data lida) e `knownDate`. + +## Falha sem a correção + +Cada correção foi revertida com o teste mantido, rodada e restaurada: + +- Códigos de início, tabelas de limite, `cleared` e `held`: os testes novos de cada área falham com o código da `main` (feito por área, numa cópia temporária de `apps/cli`). +- Denúncia depois da exclusão (`cleared` em `server.js`): `account-phone-burn.test.js` dá 5/6 testes e 49/52 asserções; com a correção, 6/6 e 52/52. +- `held` sem o bloqueio pendente da exclusão: `account-phone-burn.test.js` dá 7/8 e 66/69, `moderation-store.test.js` 77/78 e 613/615; com `>` no lugar de `>=` também, `moderation-store.test.js` dá 76/78. Com a correção, 8/8 e 69/69, 78/78 e 615/615. +- `held` que olha só o resultado das mudanças pendentes (sem contar um desbloqueio ao lado do bloqueio pego pelo operador): `account-phone-burn.test.js` dá 8/9 e 74/77, `moderation-store.test.js` 78/79 e 618/619; com a correção, 9/9 e 77/77, 79/79 e 619/619. +- Sem o `prune()` no início: `account-phone.test.js` dá 38/39 e 438/439; com a correção, 39/39 e 439/439. O temporizador de 10 minutos não tem teste (o relógio dos testes é falso e o temporizador usa o real). +- Exclusão com a varredura falhando e denúncias antigas: `account-phone.test.js` dá 37/38 testes e 433/435 asserções; com a correção, 38/38 e 435/435 (antes do teste do código vencido). +- Envio respondido com `verificado` sempre como "Esse já é o seu celular.": `phone.test.js` dá 21/22; com a correção, 22/22. +- `markVerified` sem prova mantendo a data: a asserção nova de `usePhoneGate.test.js` falha sem o `keep`. + +## Comandos + +```sh +npx standard +node apps/cli/test/start-nonces.test.js +node apps/cli/test/account-phone-burn.test.js +node apps/cli/test/account-phone.test.js +node apps/cli/test/account-age.test.js +node apps/cli/test/phone-store.test.js +node apps/cli/test/moderation-store.test.js +node apps/app/test/phone.test.js +node apps/app/test/usePhoneGate.test.js +node apps/app/test/phoneEntry.test.js +``` + +## Aparelhos + +- Android (emulador `varanda-api36`, build de debug) e simulador iOS (iPhone 17 Pro), com o JS desta branch servido pelo Metro (porta 8103, `--clear`): os dois abrem na tela de boas-vindas, sem erro. O fluxo de celular com conta não é alcançável aqui: o build de debug não entra com passkey de produção e o iOS depende do domínio associado (`docs/development.md`). Os passos com conta foram para a #224. +- Web, no laboratório hospedado (`node apps/cli/scripts/hosted-lab.js --port 8080 --expo http://127.0.0.1:8103`, DHT local, celular de mentira com o código 123456), em Chrome sem janela com autenticador virtual (ctap2, PRF): + - cadastro com o passo do celular: envio e código funcionam; + - Ajustes mostra "Trocar o celular" para a conta vinculada e destravada; + - o mesmo número volta para a lista com "Esse já é o seu celular.", sem tela de código; + - um número novo com o código 123456 volta com "Celular atualizado.". + + A conferência do mesmo número rodou antes da última mudança em `phoneChangeOutcome`, que só faz todo envio respondido com `verificado` dizer o mesmo texto. Ela está coberta por `phone.test.js`. + +## O que ficou de fora + +- "Trocar o celular" no app nativo com conta, no APK de preview e no TestFlight (passos na #224). +- Os formulários de privacidade das lojas (App Store e Google Play) com o número de celular, antes de definir `VARANDA_PHONE_KEY` em produção (na #224). +- Limites aceitos pelo dono, por escrito em `docs/design.md`: o número fica só na memória do serviço, sem cifra, por até 10 minutos entre o envio e a conferência; e, sem resposta da política e sem o atestado `phone-since`, o passo fica desligado naquela abertura. +- Com um limite de envios pendentes menor que o normal (opção só de teste), `room()` pode deixar passar uma entrada a mais quando um pendente vence durante a chamada ao Didit. No tamanho real (`4 x` o teto diário) isso não acontece.