Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1231,7 +1231,7 @@ Na exclusão, o serviço:

Ficam as denúncias e as decisões dos moderadores (`moderation.json`, retenção em aberto na issue #38). Quem ainda é dono de uma página recebe `paginas-ativas` e precisa encerrá-la ou transferi-la antes.

O app promete que o diário sai dos semeadores em até 7 dias, então rode `mod apply --yes` agendado (a cada hora, como na seção anterior): ele assina as exclusões sem esperar o terminal. `GET /account/status?member=<chave>` responde `{ "linked": false, "deleted": "pendente" }` até a lista com a chave chegar ao semeador e o painel confirmá-la, e `"concluida"` depois; o app usa isso para avisar a pessoa. Cada exclusão ocupa uma das 4096 vagas da lista de bloqueio (`MAX_BLOCKED`).
O app promete que o diário sai dos semeadores em até 7 dias, então rode `mod apply --yes` agendado (a cada hora, como na seção anterior): ele assina as exclusões sem esperar o terminal. `GET /account/status?member=<chave>` responde `{ "linked": false, "deleted": "pendente" }` até a lista com a chave chegar ao semeador e o painel confirmá-la, e `"concluida"` depois; o app usa isso para avisar a pessoa. Cada exclusão ocupa para sempre uma das 16384 vagas da lista de bloqueio (`MAX_BLOCKED`), e hoje a lista está muito abaixo de 4096 chaves. Um nó de versão anterior aceita no máximo 4096: de 4097 a 5796 chaves, ele recusa a lista nova e continua aplicando a última lista válida que recebeu até ser atualizado; acima disso, faz o mesmo, mas o app e o PWA de versão anterior não concluem mais a sincronização (todo Sincronizar termina em `tempo esgotado: blocklist`) até serem atualizados. Veja `docs/protocol.md` seção 3, "Blocklist snapshot".

A primeira exclusão grava `deleted` no `directory.json`: voltar a uma versão anterior a esta precisa do backup de antes dela, como na primeira página.

Expand Down Expand Up @@ -1447,7 +1447,7 @@ Limites desta fase:
- A identidade piloto da versão web mantém o certificado v1 (um diário não aceita um segundo certificado). Ela pode vincular a conta ao celular verificado e ganhar um @nome pelo registro de @nome, mas o certificado dela continua v1.
- O @nome troca no máximo uma vez a cada 7 dias e um nome já usado por um membro não vai para outro; um nó antigo ou um seguidor que ainda não sincronizou pode mostrar por um tempo o nome anterior.
- A lista de bloqueio é obedecida só por nós atualizados e honestos: um nó de antes da PR B2 não a aplica, um app modificado ainda pode falar direto com a conta bloqueada, e o app oficial da própria conta bloqueada guarda o diário e pode servi-lo a quem já conhece a chave de descoberta. A versão web sem rede aplica a lista que já guardou e só recebe uma nova pelo semeador. Bloquear não apaga nada do aparelho do autor. Veja `docs/verification.md` seção 13.
- A lista tem no máximo 4096 contas bloqueadas e 64 emissores revogados. Cada conexão troca no máximo uma lista a cada 10 s e é derrubada depois de 5 mensagens inválidas no canal `varanda/blocklist/1`.
- A lista tem no máximo 16384 contas bloqueadas (um nó de versão anterior aceita até 4096, veja "Excluir conta") e 64 emissores revogados. Cada conexão troca no máximo uma lista a cada 10 s e é derrubada depois de 5 mensagens inválidas no canal `varanda/blocklist/1`.
- Só o nó hospedado denuncia (a versão web hospedada e o app instalado com a instalação): o app com configuração manual, o `varanda-serve` e a CLI não têm como assinar ou enviar uma denúncia (a folha avisa), e só quem vinculou a conta denuncia, até 20 vezes a cada 24 horas. O trecho citado da publicação é o que quem denuncia enviou e não é conferido pelo serviço, e a pessoa denunciada não vê nada. Veja `docs/verification.md` seção 14.
- As sessões do painel acabam quando o serviço `account` reinicia. A lista que o painel mostra como publicada é o espelho verificado da última lista que o operador confirmou com `mod apply`, e o `blocklist.json` do operador é a que vale; "aplicado" é a palavra do operador, e a propagação segue as regras do `varanda/blocklist/1`.
- Certificados de membro individuais não são revogáveis (bloqueie a chave do diário). A chave do emissor do serviço de conta é revogada com `mod revoke-issuer`; depois disso gere outra (`account key`), certifique (`assoc certify-issuer`), `account cert add`, reinicie o serviço e peça que os membros vinculem de novo, porque os certificados v2 antigos deixam de valer. A reemissão automática fica para uma PR futura.
Expand Down
92 changes: 59 additions & 33 deletions apps/cli/lib/account/mod-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ const { MAX_REPORTS, MAX_APPEALS, AI_ACTOR, OWNER_ACTOR, ANEXO_MAX_BYTES, ANEXO_
// Google account may report, so every report has an accountable author.
// POST /account/report/anexo is the same report carrying one image or
// one voice note (a private or group message, statements dm v2 / v3):
// the only route with
// a body above REPORT_BODY_MAX, and at most MAX_ANEXO_INFLIGHT such
// bodies are read at once. The image is stored as the reporter's word
// the only member route with a body above REPORT_BODY_MAX (the
// operator's api/ack is the other large one), and at most
// MAX_ANEXO_INFLIGHT such bodies are read at once. The image is stored as the reporter's word
// and served to the panel from local disk only; it never reaches the AI
// triage, a log or the seeder.
// - a blocked member's appeal (POST /account/appeal/start, POST
Expand All @@ -39,6 +39,11 @@ const { MAX_REPORTS, MAX_APPEALS, AI_ACTOR, OWNER_ACTOR, ANEXO_MAX_BYTES, ANEXO_
// cookie and no Origin rule; a signature by the association-certified
// moderator key over a single-use server nonce, bound to this origin and
// the exact body (packages/core/lib/mod-request.js), is the authority.
// api/ack carries a whole blocklist snapshot, so it is read like an
// anexo (a declared length, an idle cut, a deadline that grows with the
// length) but with no slot cap: a slot taken before the moderator
// signature is checked would let an anonymous sender keep the operator
// out, so ack reads share only the service's socket ceiling.
//
// Every server.js rule holds here: { error: token } bodies, no CORS, the
// browser POST rules (exact Origin + JSON) on every cookie route, which with
Expand Down Expand Up @@ -98,29 +103,43 @@ const REPORT_BODY_MAX = 8192
const ANEXO_B64_MAX = 4 * Math.ceil(ANEXO_MAX_BYTES / 3)
const ANEXO_BODY_MAX = ANEXO_B64_MAX + REPORT_BODY_MAX
const MAX_ANEXO_INFLIGHT = 4
// Reading an anexo body is anonymous until its nonce and signature check, so
// a slot is never held by a sender that stops: a body with no chunk for
// ANEXO_IDLE_MS is cut, and every body has a deadline of ANEXO_READ_SLACK_MS
// plus its declared length at ANEXO_MIN_BITS_PER_MS (1 Mbit/s, a slow mobile
// link): a full ANEXO_BODY_MAX (about 1.4 MB, 11.3 s at that rate) would get
// about 13.3 s, a small image a couple of seconds. The service's
// requestTimeout (server.js) is the headers timeout plus ANEXO_READ_MAX_MS,
// so it never ends an anexo body before this deadline does.
const ANEXO_IDLE_MS = 5000
const ANEXO_READ_SLACK_MS = 2000
const ANEXO_MIN_BITS_PER_MS = 1000
const ANEXO_READ_MAX_MS = ANEXO_READ_SLACK_MS + Math.ceil(ANEXO_BODY_MAX * 8 / ANEXO_MIN_BITS_PER_MS)
// Reading an anexo or an ack body is anonymous until its nonce and signature
// check, so a slot is never held by a sender that stops: a body with no
// chunk for LARGE_BODY_IDLE_MS is cut, and every body has a deadline of
// LARGE_BODY_SLACK_MS plus its declared length at LARGE_BODY_MIN_BITS_PER_MS
// (1 Mbit/s, a slow mobile link): a full ANEXO_BODY_MAX (about 1.4 MB, 11.3 s
// at that rate) gets about 13.3 s, a full ACK_BODY_MAX (1.5 MiB) about
// 14.6 s, a small image a couple of seconds. The service's requestTimeout
// (server.js) is the headers timeout plus LARGE_BODY_READ_MAX_MS, so it never
// ends such a body before this deadline does.
const LARGE_BODY_IDLE_MS = 5000
const LARGE_BODY_SLACK_MS = 2000
const LARGE_BODY_MIN_BITS_PER_MS = 1000
const DECIMAL_RE = /^[0-9]{1,10}$/
const B64_RE = /^[A-Za-z0-9+/]*={0,2}$/
// The image itself, served to a signed-in moderator: never a document.
const ANEXO_CSP = "default-src 'none'; sandbox"
// A legal snapshot is at most 393216 bytes (blocklist.js MAX_SNAPSHOT_BYTES)
// plus at most 4096 change ids (mod-request.js MAX_CHANGE_IDS).
const ACK_BODY_MAX = 524288
// A legal snapshot is at most 1179648 bytes (blocklist.js MAX_SNAPSHOT_BYTES)
// plus at most 4096 change ids of up to 67 JSON bytes each (mod-request.js
// MAX_CHANGE_IDS, 274432 bytes), plus the signed fields: 1.5 MiB leaves
// about 115 KB of room.
const ACK_BODY_MAX = 1572864
// Ack reads have no slot cap of their own (see the header): only the
// service's socket ceiling (server.js MAX_SOCKETS) bounds them, as every
// route other than the anexo.
const ANEXO_READ_MAX_MS = largeBodyDeadlineMs(ANEXO_BODY_MAX)
const ACK_READ_MAX_MS = largeBodyDeadlineMs(ACK_BODY_MAX)
const LARGE_BODY_READ_MAX_MS = Math.max(ANEXO_READ_MAX_MS, ACK_READ_MAX_MS)
const HEX64_RE = /^[0-9a-f]{64}$/
const TOKEN_RE = /^[A-Za-z0-9_-]{43}$/
// Report and change ids (moderation-store.js newId: 16 bytes base64url).
const ID_RE = /^[A-Za-z0-9_-]{1,64}$/

// The read deadline of an anexo or ack body of `length` declared bytes.
function largeBodyDeadlineMs (length) {
return LARGE_BODY_SLACK_MS + Math.ceil(length * 8 / LARGE_BODY_MIN_BITS_PER_MS)
}

const REPORT_KINDS = new Set(['listing'])
const ANUNCIO_KEYS = ['title', 'text', 'priceLabel', 'city', 'uf', 'kind', 'status']
// Google authorization codes: printable ASCII, bounded (as server.js).
Expand Down Expand Up @@ -1239,23 +1258,23 @@ function createModRoutes ({
return readJsonBody(req, max)
}

// The anexo body's declared length, or a refusal before any slot is
// taken: a chunked body (no Content-Length) could only be capped as it
// streams, and a length past the cap answers 413 unread.
function anexoLength (req, res) {
// A large body's declared length, or a refusal before any slot is taken:
// a chunked body (no Content-Length) could only be capped as it streams,
// and a length past `max` answers 413 unread.
function declaredLength (req, res, max) {
const declared = req.headers['content-length']
if (req.headers['transfer-encoding'] !== undefined || typeof declared !== 'string' || !DECIMAL_RE.test(declared)) {
res.setHeader('Connection', 'close')
throw new RouteError('pedido-invalido', 411)
}
const length = Number(declared)
if (length > ANEXO_BODY_MAX) throw new RouteError('pedido-invalido', 413)
if (length > max) throw new RouteError('pedido-invalido', 413)
return length
}

// readJsonBody under the idle cut and the deadline (ANEXO_IDLE_MS): either
// destroys the request, which ends the read and so frees its slot.
function readAnexoBody (req, length) {
// readJsonBody under the idle cut and the deadline (largeBodyDeadlineMs):
// either destroys the request, which ends the read and so frees its slot.
function readLargeBody (req, length, max) {
return new Promise((resolve, reject) => {
let settled = false
let idle = null
Expand All @@ -1274,12 +1293,12 @@ function createModRoutes ({
}
const onData = () => {
clearTimeout(idle)
idle = setTimeout(cut, ANEXO_IDLE_MS)
idle = setTimeout(cut, LARGE_BODY_IDLE_MS)
}
const deadline = setTimeout(cut, ANEXO_READ_SLACK_MS + Math.ceil(length * 8 / ANEXO_MIN_BITS_PER_MS))
idle = setTimeout(cut, ANEXO_IDLE_MS)
const deadline = setTimeout(cut, largeBodyDeadlineMs(length))
idle = setTimeout(cut, LARGE_BODY_IDLE_MS)
req.on('data', onData)
readJsonBody(req, ANEXO_BODY_MAX, null).then((value) => finish(null, value), finish)
readJsonBody(req, max, null).then((value) => finish(null, value), finish)
})
}

Expand All @@ -1303,13 +1322,13 @@ function createModRoutes ({
if (post && p === '/account/report/anexo') {
needModeration()
checkPost(req)
const length = anexoLength(req, res)
const length = declaredLength(req, res, ANEXO_BODY_MAX)
if (anexoInflight >= MAX_ANEXO_INFLIGHT) throw refuse('limite')
anexoInflight++
// The slot is held until the whole report is handled, so the decode,
// bounds check and hash of an image are bounded too, not only the read.
try {
const body = await readAnexoBody(req, length)
const body = await readLargeBody(req, length, ANEXO_BODY_MAX)
return await report(req, res, body, true)
} finally {
anexoInflight--
Expand All @@ -1333,7 +1352,11 @@ function createModRoutes ({
// the moderator signature over a server nonce is the authority).
if (get && p === '/account/mod/api/challenge') return challenge(req, res, url)
if (post && p === '/account/mod/api/pull') return pull(req, res, await postBody(req, undefined, { requireOrigin: false }))
if (post && p === '/account/mod/api/ack') return ack(req, res, await postBody(req, ACK_BODY_MAX, { requireOrigin: false }))
if (post && p === '/account/mod/api/ack') {
checkPost(req, { requireOrigin: false })
const length = declaredLength(req, res, ACK_BODY_MAX)
return ack(req, res, await readLargeBody(req, length, ACK_BODY_MAX))
}

// Panel API. api/me answers 401 without a session even when the panel
// is disabled: deploy/seeder/deploy.sh probes exactly that.
Expand Down Expand Up @@ -1408,11 +1431,14 @@ module.exports = {
REPORT_BODY_MAX,
ANEXO_BODY_MAX,
ANEXO_READ_MAX_MS,
ACK_READ_MAX_MS,
LARGE_BODY_READ_MAX_MS,
MAX_ANEXO_INFLIGHT,
ANEXO_LIST_LABEL,
ANEXO_PROVENANCE,
ANEXO_AUDIO_PROVENANCE,
ACK_BODY_MAX,
largeBodyDeadlineMs,
MAX_MOD_EMAILS,
PANEL_CSP,
parseModEmails,
Expand Down
16 changes: 9 additions & 7 deletions apps/cli/lib/account/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const { isUsername, verifyAccountLink } = require('@varanda/core/lib/account-lin
const { TERMS_VERSION, verifyTerms } = require('@varanda/core/lib/terms')
const { verifyInvite } = require('@varanda/core/lib/invite')
const { loadKeyPairFile, verifyIssuerCert, refuseSymlinkDir } = require('@varanda/core/lib/cert')
const { createModRoutes, ANEXO_READ_MAX_MS } = require('./mod-routes')
const { createModRoutes, LARGE_BODY_READ_MAX_MS } = require('./mod-routes')
const { inviteId, CODE_RE } = require('./invites-store')
const { createPushRoutes } = require('./push-routes')
const { createSeenRoutes } = require('./seen-routes')
Expand Down Expand Up @@ -76,12 +76,13 @@ const MAX_SOCKETS = 64
const DEFAULT_RATE = 20
const DEFAULT_BURST = 100
const HEADERS_TIMEOUT_MS = 4000
// Long enough for the largest report anexo at the slowest rate its own
// deadline allows (mod-routes.js). Every other body is at most a few dozen
// KB and gets BODY_READ_MS from when its route starts reading it, the
// earlier request timeout, so only the anexo route holds a slow sender's
// socket past HEADERS_TIMEOUT_MS + BODY_READ_MS.
const REQUEST_TIMEOUT_MS = HEADERS_TIMEOUT_MS + ANEXO_READ_MAX_MS
// Long enough for the largest report anexo or operator ack at the slowest
// rate their own deadline allows (mod-routes.js LARGE_BODY_READ_MAX_MS, the
// larger of the two maxima). Every other body is at most a few dozen KB and
// gets BODY_READ_MS from when its route starts reading it, the earlier
// request timeout, so only those two routes hold a slow sender's socket
// past HEADERS_TIMEOUT_MS + BODY_READ_MS.
const REQUEST_TIMEOUT_MS = HEADERS_TIMEOUT_MS + LARGE_BODY_READ_MAX_MS
const BODY_READ_MS = 10000
const CHECK_INTERVAL_MS = 1000
const MAX_BODY = 4096
Expand Down Expand Up @@ -1861,6 +1862,7 @@ module.exports = {
MAX_SOCKETS,
DEFAULT_RATE,
DEFAULT_BURST,
HEADERS_TIMEOUT_MS,
REQUEST_TIMEOUT_MS,
BODY_READ_MS,
KEY_FILE,
Expand Down
22 changes: 14 additions & 8 deletions apps/cli/lib/mod-apply.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,16 @@ const { jsonLine } = require('@varanda/core/lib/safe')
const mod = require('./commands/mod')

const REQUEST_TIMEOUT_MS = 10000
// pull answers and ack bodies carry a whole snapshot (up to about 1.5 MiB):
// the service gives an ack body up to about 14.6 s to arrive
// (account/mod-routes.js ACK_READ_MAX_MS), so the whole request gets that
// plus room for the answer and the store write.
const TRANSFER_TIMEOUT_MS = 30000
const BODY_CAP = 524288
// D1: at most MAX_PENDING (1000) changes of ~140 bytes plus one snapshot of
// up to MAX_SNAPSHOT_BYTES (393216) bytes.
const PULL_BODY_CAP = 1048576
// D1: at most MAX_PENDING (1000) changes of at most ~220 bytes (64-character
// ids) plus one snapshot of up to MAX_SNAPSHOT_BYTES (1179648) bytes: 1.5 MiB
// leaves about 170 KB of room.
const PULL_BODY_CAP = 1572864
const MAX_CHANGES = 1000
// --yes (cron) signs at most this many new (human) blocks per run.
const MAX_UNATTENDED_BLOCKS = 100
Expand Down Expand Up @@ -153,9 +159,9 @@ async function readCapped (res, cap) {

// -> { status, value } with value the parsed JSON; throws UNAVAILABLE when
// the server cannot be reached in time, INVALID for anything but bounded JSON.
async function request (fetch, url, { body = null, cap = BODY_CAP } = {}) {
async function request (fetch, url, { body = null, cap = BODY_CAP, timeoutMs = REQUEST_TIMEOUT_MS } = {}) {
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
const timer = setTimeout(() => controller.abort(), timeoutMs)
try {
let res
try {
Expand Down Expand Up @@ -248,7 +254,7 @@ async function pull (ctx) {
const nonce = await challenge(ctx, 'pull')
const signature = sign(ctx, nonce, 'pull', canonicalBody('pull'))
const body = JSON.stringify({ cert: ctx.certificate, nonce, signature })
const { status, value } = await request(ctx.fetch, ctx.server + '/account/mod/api/pull', { body, cap: PULL_BODY_CAP })
const { status, value } = await request(ctx.fetch, ctx.server + '/account/mod/api/pull', { body, cap: PULL_BODY_CAP, timeoutMs: TRANSFER_TIMEOUT_MS })
if (status !== 200) throw refused(value)
const result = checkPull(value, ctx.association)
if (result === null) throw new Error(INVALID)
Expand All @@ -259,7 +265,7 @@ async function ack (ctx, changeIds, snapshot) {
const nonce = await challenge(ctx, 'ack')
const signature = sign(ctx, nonce, 'ack', canonicalBody('ack', { changeIds, snapshot }))
const body = JSON.stringify({ cert: ctx.certificate, nonce, signature, changeIds, snapshot: canonicalSnapshot(snapshot) })
const { status, value } = await request(ctx.fetch, ctx.server + '/account/mod/api/ack', { body })
const { status, value } = await request(ctx.fetch, ctx.server + '/account/mod/api/ack', { body, timeoutMs: TRANSFER_TIMEOUT_MS })
if (status === 409 && isPlainObject(value) && value.error === 'defasado') {
throw new Error('o servidor tem uma lista mais nova; restaure o backup')
}
Expand Down Expand Up @@ -436,4 +442,4 @@ async function signPublishAck (ctx, dir, changeIds, opts, done, edits = {}) {
return done('aplicado', changeIds, snapshot, 'aplicado: seq ' + snapshot.seq + ', ' + snapshot.blocked.length + ' chaves bloqueadas')
}

module.exports = { apply, checkServer, checkMode, REQUEST_TIMEOUT_MS, BODY_CAP, PULL_BODY_CAP, MAX_CHANGES, MAX_UNATTENDED_BLOCKS }
module.exports = { apply, checkServer, checkMode, REQUEST_TIMEOUT_MS, TRANSFER_TIMEOUT_MS, BODY_CAP, PULL_BODY_CAP, MAX_CHANGES, MAX_UNATTENDED_BLOCKS }
Loading
Loading