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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -671,7 +671,7 @@ Criar a primeira página é uma migração de mão única do diretório de conta

Os aceites dos Termos de Uso e da Política de Privacidade ficam num arquivo à parte no mesmo volume, `terms.json` (modo `0600`): para cada chave de membro, a versão aceita, a data (do relógio do serviço), o nonce e a assinatura que provaram o aceite; nunca o e-mail. Só um membro já vinculado registra aceite (`POST /account/terms/start` e `/account/terms/finish`, com uma prova da chave do diário) e lê de volta se o serviço guarda a versão atual (`POST /account/terms/held/start` e `/account/terms/held/finish`, com a prova `summary` da chave do diário; uma leitura por membro, no máximo 30 a cada 10 minutos). `GET /account/status` não traz a versão aceita. Inclua `terms.json` no backup do volume `account-data`, junto do diretório de contas. Restaurar uma cópia mais antiga perde os aceites feitos depois dela, e os aparelhos que já sincronizaram o aceite não o reenviam. `account export` traz em cada linha o campo `terms`, a lista `[{ "version", "acceptedAt" }]` dos aceites daquele membro (`[]` sem aceite; nunca o nonce nem a assinatura), e sai com `terms.json inválido` (código 1) se o arquivo estiver corrompido; `account status` mostra `aceites dos termos: <n>` ou `aceites dos termos: indisponível (terms.json inválido)`. Com o arquivo inválido o serviço continua no ar, registra `terms indisponivel` e responde "indisponível" (HTTP 503) só nessas rotas. Uma versão anterior a esta ignora o `terms.json` e responde 404 nas duas rotas: voltar a ela não perde os aceites gravados, que reaparecem quando esta versão volta.

As passkeys extras e o código de recuperação de cada membro (Ajustes › Passkeys e recuperação) ficam noutro arquivo à parte no mesmo volume, `recovery.json` (modo `0600`): por identificador derivado, a chave do membro, o tipo (`passkey` ou `code`), a data e a raiz embrulhada, um texto cifrado que o serviço não consegue abrir. As rotas são `POST /account/recovery/start`, `/put`, `/remove`, `/list` (com uma prova da chave do diário, só para membro vinculado) e `/fetch` (o identificador vai só no corpo do POST). São até 4 passkeys extras e 1 código por membro (`limite-recuperacao`, HTTP 409). O `/start` não guarda nada (o nonce leva a validade e uma assinatura do próprio serviço) e não tem cota por membro, então ninguém bloqueia outro membro pedindo nonces em nome dele; o nonce só é gasto depois de uma prova válida. Remover ou trocar uma entrada só impede novas entradas com ela: quem já entrou com aquela passkey ou aquele código continua com acesso, porque a chave da conta não pode ser trocada, e o único caminho seguro depois de um vazamento é criar uma conta nova. Inclua `recovery.json` no backup do volume `account-data`; se ele se perder, cada membro entra com a passkey original ou num aparelho ainda conectado e cadastra as entradas de novo. Com o arquivo corrompido o serviço continua no ar, registra `recovery indisponivel`, nunca regrava o arquivo e responde "indisponível" (HTTP 503) só nas rotas `/account/recovery/*`. O arquivo não entra em `account export` nem em `account status`, e os registros do serviço nunca trazem o identificador, o texto cifrado nem a chave. Detalhes em `docs/protocol.md` ("Files and replicas").
As passkeys extras e o código de recuperação de cada membro (Ajustes › Passkeys e recuperação) ficam noutro arquivo à parte no mesmo volume, `recovery.json` (modo `0600`): por identificador derivado, a chave do membro, o tipo (`passkey` ou `code`), a data e a raiz embrulhada, um texto cifrado que o serviço não consegue abrir. As rotas são `POST /account/recovery/start`, `/put`, `/remove`, `/list` (com uma prova da chave do diário, só para membro vinculado) e `/fetch` (o identificador vai só no corpo do POST). São até 4 passkeys extras e 1 código por membro (`limite-recuperacao`, HTTP 409). O `/start` não guarda nada (o nonce leva a validade e uma assinatura do próprio serviço) e não tem cota por membro, então ninguém bloqueia outro membro pedindo nonces em nome dele; o nonce só é gasto depois de uma prova válida. Remover ou trocar uma entrada só impede novas entradas com ela: quem já entrou com aquela passkey ou aquele código continua com acesso, porque a chave da conta não pode ser trocada, e o único caminho seguro depois de um vazamento é criar uma conta nova. Inclua `recovery.json` no backup do volume `account-data`; copiar com o serviço no ar não tem problema, porque o arquivo é sempre trocado inteiro de uma vez. Para restaurar, com o serviço parado, ponha de volta só a cópia mais nova: ela não tem as entradas cadastradas depois da cópia e volta a ter as removidas depois dela, então avise os membros para conferirem Ajustes › Passkeys e recuperação. Sem cópia, suba o serviço sem o arquivo: cada membro entra com a passkey original ou num aparelho ainda conectado e cadastra as entradas de novo. A primeira gravação que muda o arquivo o deixa na versão 2, que uma versão mais antiga do serviço não lê: se voltar para ela, as rotas `/account/recovery/*` respondem 503 até a versão nova voltar. Com o arquivo corrompido o serviço continua no ar, registra `recovery indisponivel`, nunca regrava o arquivo e responde "indisponível" (HTTP 503) só nas rotas `/account/recovery/*`. O arquivo não entra em `account export` nem em `account status`, e os registros do serviço nunca trazem o identificador, o texto cifrado nem a chave. Detalhes em `docs/protocol.md` ("Files and replicas").

Se houver um `directory.journal.*` antes de voltar (um diário órfão), suba esta versão de novo, espere mais de 40 segundos para que a limpeza de órfãos o remova, pare-a com a parada limpa e confira de novo. O `deploy.sh` desfaz o deploy sozinho recriando o contêiner `account` com um fechamento por SIGTERM, que deixa a versão 1 só se esse fechamento der certo; se o contêiner `account` estava parado ou reiniciando naquele momento, o diretório continua na versão 2 e a imagem anterior o recusa até que os passos manuais acima sejam seguidos.

Expand Down
44 changes: 44 additions & 0 deletions apps/app/test/passkeyPrfAndroid.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
'use strict'

// The Android passkey module (modules/passkey-prf/android) pins Credential
// Manager. Releases before 1.5.0 lack the passkey cleanup the app relies on,
// and a range or a variable would let a build pick one. The file is read as
// text.
const fs = require('node:fs')
const path = require('node:path')
const test = require('brittle')

const GRADLE = path.join(__dirname, '..', 'modules/passkey-prf/android/build.gradle')
const MIN = [1, 5, 0]
const ARTIFACTS = ['androidx.credentials:credentials', 'androidx.credentials:credentials-play-services-auth']

const uncommented = (gradle) => gradle.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '')

function atLeast (version, min) {
const parts = version.split('.').map(Number)
for (let i = 0; i < min.length; i++) {
if (parts[i] !== min[i]) return parts[i] > min[i]
}
return true
}

test('atLeast compares versions numerically', (t) => {
t.ok(atLeast('1.5.0', MIN))
t.ok(atLeast('1.10.0', MIN), 'not a string compare')
t.ok(atLeast('2.0.0', MIN))
t.absent(atLeast('1.4.9', MIN))
t.absent(atLeast('0.9.0', MIN))
})

test('both Credential Manager dependencies are pinned to an exact version at or above 1.5.0', (t) => {
const gradle = uncommented(fs.readFileSync(GRADLE, 'utf8'))
for (const artifact of ARTIFACTS) {
const lines = [...gradle.matchAll(/^\s*implementation\s+(['"])([^'"]*)\1\s*$/gm)]
.map((m) => m[2])
.filter((coord) => coord.startsWith(artifact + ':'))
t.is(lines.length, 1, artifact + ' is declared once, as a plain string')
const version = lines.length === 1 ? lines[0].slice(artifact.length + 1) : ''
t.ok(/^\d+\.\d+\.\d+$/.test(version), artifact + ' has an exact version: ' + version)
t.ok(atLeast(version, MIN), artifact + ' is at least ' + MIN.join('.') + ': ' + version)
}
})
102 changes: 86 additions & 16 deletions apps/cli/lib/account/recovery-store.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,19 @@
// nothing from this file is logged or put in an error: a lookupId finds a
// blob, a blob is the member's wrapped root.
//
// The file is { v: 2, seq, entries, removed, floors }: entries maps lookupId
// to its row, removed maps lookupId to its tombstone and floors maps a member
// key to a gen (both below). A version 1 file (the same without floors) is
// still read; the next write that changes anything writes version 2, and
// nothing is rewritten only to change the version. An older build of the
// service refuses a version 2 file as malformed and never rewrites it, so
// after a rollback /account/recovery/* answers 503 until the newer build
// returns.
//
// Opening never creates, mkdirs or chmods anything (a missing file means no
// entry yet; the first put writes it), and a readOnly store never writes at
// all. Validation is total: a file this module would not have written (bad
// JSON, unknown keys, a bad id, row or tombstone, an id both live and
// JSON, unknown keys, a bad id, row, tombstone or floor, an id both live and
// removed) is never rewritten, and every method then throws
// { code: 'indisponivel' } until an operator repairs it. Errors carry only a
// token in `code`; bad argument shapes throw TypeError with a fixed message.
Expand Down Expand Up @@ -50,11 +59,35 @@
// (one just written, or one whose removedAt is ahead of this clock) nor the
// member's newest tombstone, so a member may briefly hold more than the cap;
// the TTL is far longer than that window, so it never drops a fresh one.
// Residual: a copy of the file older than a pruned tombstone may still
// resurrect that row. Accepted, since a stale writer's rename lands within
// one lock period (30 s) and is healed within one heal interval, far inside
// STALE_WINDOW_MS; a holder whose clock runs more than the TTL behind may
// also see its fresh tombstones pruned by another holder.
//
// Each pruned tombstone, by the TTL or by the cap, raises its member's floor
// (`floors`) to its gen; floors only go up, a merge takes the max per
// member, and a floor never passes seq. When this holder merges the file
// into its memory, a row only the file holds is dropped when its gen is at
// or under memory's floor for that member: memory had the row, removed it
// and pruned the tombstone. So a copy on disk older than memory that still
// holds a removed row (a stale writer's rename) cannot bring it back through
// heal(), a read after an uncertain write or the merge before a write,
// however long ago the tombstone went. The file's floor never drops a row
// memory holds: the service takes the lock before it opens the store and
// fails the store for good when it loses the lock (../commands/account.js),
// so memory is never behind the file on their shared history, and a file
// whose floor passes a row in memory comes from another history (a copy put
// back after the service started from an older copy or from no file), whose
// floors say nothing about memory's rows. A row put later takes a gen above
// every floor, since put() merges first. A floor keeps the member key after
// the member's last tombstone is pruned, Excluir conta included. Tombstones
// pruned by a version 1 build left no floor.
//
// Residual: a merge needs two copies. A copy put back while no holder runs
// is read as it is: it lacks every row written after it and holds again the
// rows removed after it, with nothing left to bury them. A copy from another
// history put back while a holder runs is a union apart from memory's floor:
// its rows removed in that history may come back, and those at or under
// memory's floor for their member go. A holder whose clock runs behind
// another's by more than STALE_WINDOW_MS (or the TTL) may see its fresh
// tombstones pruned by the cap (or the TTL) on that other holder; the rows
// they buried stay buried under the floor.
//
// Reads (list, fetch) after an uncertain write (a failed write, or guard()
// refusing after the rename) first re-read the file and adopt the merge, or
Expand All @@ -78,7 +111,7 @@ const { writeJsonAtomic } = require('@varanda/core/lib/store')
const { isLowerHex, isCanonicalIso, isPlainObject, refuseSymlinkDir } = require('@varanda/core/lib/cert')

const FILE = 'recovery.json'
const VERSION = 1
const VERSION = 2
const MAX_PASSKEYS = 4
const TOMBSTONE_MAX_PER_MEMBER = 32
const TOMBSTONE_TTL_MS = 30 * 24 * 3600 * 1000
Expand All @@ -87,7 +120,10 @@ const KINDS = ['passkey', 'code']
const BLOB_KEYS = ['v', 'kind', 'nonce', 'ciphertext']
const ENTRY_KEYS = ['member', 'kind', 'nonce', 'ciphertext', 'createdAt', 'gen']
const TOMB_KEYS = ['member', 'removedAt', 'gen']
const FILE_KEYS = ['v', 'seq', 'entries', 'removed']
const FILE_KEYS = ['v', 'seq', 'entries', 'removed', 'floors']
// Version 1 had no floors; it is still read, and the next write that changes
// anything is version 2.
const FILE_KEYS_V1 = ['v', 'seq', 'entries', 'removed']
// 24-byte secretbox nonce; 66-byte plaintext + 16-byte MAC.
const NONCE_BYTES = 24
const CIPHERTEXT_BYTES = 82
Expand Down Expand Up @@ -166,13 +202,16 @@ function invalidFile () {
}

function emptyState () {
return { v: VERSION, seq: 0, entries: Object.create(null), removed: Object.create(null) }
return { v: VERSION, seq: 0, entries: Object.create(null), removed: Object.create(null), floors: Object.create(null) }
}

function fromJson (obj) {
if (!isPlainObject(obj) || !exactKeys(obj, FILE_KEYS) || obj.v !== VERSION) throw invalidFile()
if (!isPlainObject(obj)) throw invalidFile()
const v1 = obj.v === 1 && exactKeys(obj, FILE_KEYS_V1)
if (!v1 && (obj.v !== VERSION || !exactKeys(obj, FILE_KEYS))) throw invalidFile()
if (!Number.isSafeInteger(obj.seq) || obj.seq < 0) throw invalidFile()
if (!isPlainObject(obj.entries) || !isPlainObject(obj.removed)) throw invalidFile()
if (!v1 && !isPlainObject(obj.floors)) throw invalidFile()
// No per-member row ceiling here: a merge of two holders' copies may pass
// MAX_PASSKEYS, and a load-time ceiling would make this store refuse a file
// it wrote itself.
Expand All @@ -186,6 +225,12 @@ function fromJson (obj) {
if (!validId(id) || !validTomb(r) || r.gen > obj.seq || has(state.entries, id)) throw invalidFile()
state.removed[id] = copyTomb(r)
}
if (!v1) {
for (const [member, gen] of Object.entries(obj.floors)) {
if (!validMember(member) || !validGen(gen) || gen > obj.seq) throw invalidFile()
state.floors[member] = gen
}
}
return state
}

Expand Down Expand Up @@ -226,13 +271,25 @@ function toJson (state) {
for (const id of Object.keys(state.entries).sort()) entries[id] = copyEntry(state.entries[id])
const removed = {}
for (const id of Object.keys(state.removed).sort()) removed[id] = copyTomb(state.removed[id])
return { v: VERSION, seq: state.seq, entries, removed }
const floors = {}
for (const m of Object.keys(state.floors).sort()) floors[m] = state.floors[m]
return { v: VERSION, seq: state.seq, entries, removed, floors }
}

function canonical (state) {
return JSON.stringify(toJson(state))
}

function floorOf (state, member) {
return has(state.floors, member) ? state.floors[member] : 0
}

// A pruned tombstone leaves its gen behind as the member's floor, so a copy
// that still holds the row it buried cannot bring it back (merge()).
function raiseFloor (state, member, gen) {
if (gen > floorOf(state, member)) state.floors[member] = gen
}

function genOf (state, id) {
if (!state) return 0
if (has(state.entries, id)) return state.entries[id].gen
Expand Down Expand Up @@ -273,8 +330,9 @@ function nextGen (state) {
// then tombstones older than the TTL go, then each
// member keeps its TOMBSTONE_MAX_PER_MEMBER highest-gen tombstones; that cap
// never drops a tombstone younger than STALE_WINDOW_MS or the member's
// newest one. put(), remove() and merge() all end here, so every copy this
// holder writes agrees on what is kept.
// newest one. Each pruned tombstone raises its member's floor. put(), remove()
// and merge() all end here, so every copy this holder writes agrees on what
// is kept.
function normalize (state, nowMs) {
const codes = new Map()
for (const [id, e] of Object.entries(state.entries)) {
Expand Down Expand Up @@ -307,30 +365,42 @@ function normalize (state, nowMs) {
for (const r of list) {
if (Date.parse(r.removedAt) < cutoff) {
delete state.removed[r.id]
raiseFloor(state, r.member, r.gen)
kept--
}
}
for (const r of list) {
if (kept <= TOMBSTONE_MAX_PER_MEMBER) break
if (!has(state.removed, r.id) || r === newest || Date.parse(r.removedAt) >= young) continue
delete state.removed[r.id]
raiseFloor(state, r.member, r.gen)
kept--
}
}
return state
}

// Per lookupId the record (row or tombstone) with the higher gen; ties keep
// memory.
// memory. A row only the disk holds is dropped when its gen is at or under
// memory's floor for its member: memory removed it and pruned the tombstone.
// Never the other way (see the top of the file), and a copy's own floor never
// drops its rows, since a member may keep an older row it never removed
// under it. Floors merge as max.
function merge (mem, disk, nowMs) {
const out = emptyState()
out.seq = Math.max(mem.seq, disk ? disk.seq : 0)
for (const src of disk ? [mem, disk] : [mem]) {
for (const [member, gen] of Object.entries(src.floors)) raiseFloor(out, member, gen)
}
const ids = new Set([...Object.keys(mem.entries), ...Object.keys(mem.removed)])
if (disk) for (const id of [...Object.keys(disk.entries), ...Object.keys(disk.removed)]) ids.add(id)
for (const id of ids) {
const src = disk && genOf(disk, id) > genOf(mem, id) ? disk : mem
if (has(src.entries, id)) out.entries[id] = copyEntry(src.entries[id])
else out.removed[id] = copyTomb(src.removed[id])
if (has(src.entries, id)) {
const e = src.entries[id]
if (src === disk && genOf(mem, id) === 0 && e.gen <= floorOf(mem, e.member)) continue
out.entries[id] = copyEntry(e)
} else out.removed[id] = copyTomb(src.removed[id])
}
return normalize(out, nowMs)
}
Expand Down
Loading
Loading