From a8a410ac1311a143a3f548247bd8b5ceba50c525 Mon Sep 17 00:00:00 2001 From: rodrigopavezi Date: Tue, 17 Nov 2026 00:31:40 -0300 Subject: [PATCH] feat: add the garden methods to the browser node The rpc contract gains garden.set, garden.state, garden.play and garden.help (rpc.md 5.156 to 5.159). None takes a date or free text: the node sets every date. The browser node reads the own balcony from the own diary, joins and leaves the game (leaving tombstones every own garden-state and garden-help first and writes the off flag last, so a leave cut short still reads as on), saves one play session as one garden-state through the shared rules, and writes a help only after its own checks: not self, own game on, the helper follows the owner, one help per balcony per Brasilia day, at most 5 a day. It then reads the owner's flag and state through the seeder pointers and one peek, and fails closed when anything is unverified. Nothing is retried. The core node answers the four methods with the same USAGE refusal as the other on-demand reads. --- docs/rpc.md | 42 +- docs/verification/feat-varandinha-node.md | 63 +++ packages/core/lib/session.js | 16 + packages/core/test/engagement-session.test.js | 19 + packages/rpc/lib/methods.js | 10 + packages/rpc/test/methods.test.js | 54 +- packages/web-member/lib/member-ops.js | 230 ++++++++- packages/web-member/lib/session.js | 143 +++++- packages/web-member/test/garden-e2e.test.js | 206 ++++++++ packages/web-member/test/garden.test.js | 465 ++++++++++++++++++ 10 files changed, 1242 insertions(+), 6 deletions(-) create mode 100644 docs/verification/feat-varandinha-node.md create mode 100644 packages/web-member/test/garden-e2e.test.js create mode 100644 packages/web-member/test/garden.test.js diff --git a/docs/rpc.md b/docs/rpc.md index 6a3fc98e8..f7d12b475 100644 --- a/docs/rpc.md +++ b/docs/rpc.md @@ -150,7 +150,7 @@ The browser node (`packages/web-member/lib/node.js`, loaded by the web app as `v ## 5. Methods -Mutating methods (`MUTATING`, exported as a frozen array; test with `isMutating(method)`): `identity.create`, `cert.add`, `profile.set`, `profile.delete`, `username.add`, `post.create`, `post.reply`, `post.quote`, `post.delete`, `post.share` and `post.unshare` (5.122, 5.123), `like.set`, `repost.set`, `testimonial.write`, `testimonial.show`, `testimonial.decide` (5.100), `testimonial.delete`, `scrap.write`, `scrap.hide`, `scrap.wall` and `scrap.delete` (5.126 to 5.129), `profile.about`, `profile.mood` and `profile.extra.delete` (5.130 to 5.132), `fan.set` and `top.set` (5.133, 5.134), `choice.set` (5.135), `group.choose` (5.137), `moment.putMedia`, `moment.create`, `moment.delete` (5.113), `block.set`, `follow.add`, `follow.remove`, `sync.start`, `sync.stop`, `node.close`, and the IPC-only host controls `identity.install`, `identity.clear`, `identity.reset`, `identity.forget`, `identity.sessionSaved` and `media.uploadFile` (5.50 to 5.56), `page.register` (5.87), `listing.create`, `listing.status`, `listing.delete`, `listing.edit` and `listing.rate` (5.103, 5.104, 5.105, 5.107 and 5.108) and `identity.recoveryBind` (5.94, it rewrites the kv passkey record). All others are reads (`account.sign`, `report.sign`, `appeal.sign`, `terms.sign`, `invite.sign`, `inviteCard.sign`, `push.sign`, `age.sign`, `phone.sign` and `page.sign` sign but write nothing, 5.18, 5.20, 5.99, 5.29, 5.30, 5.101, 5.31, 5.32, 5.115 and 5.84; `page.read` and `page.feed` only read, 5.85 and 5.86; `post.shared` only reads, 5.121; `age.proof` stores a verified attestation in local storage only and is idempotent, 5.83; `phone.proof` stores verified phone attestations in local storage only and is idempotent, 5.116; `recovery.sign` signs but writes nothing, 5.90, and the IPC-only recovery controls `identity.recoveryLookup`, `identity.recoveryOpen` and `identity.recoveryWrap`, 5.91 to 5.93, change no stored state (no diary, no kv record): lookup holds one wrap key in the worklet's memory, open consumes it whatever the outcome (a repeated open fails, 5.92), and wrap only draws a fresh nonce for a blob nobody has stored yet; `seen.sign` signs the seen state, 5.95, and `seen.merge` is an idempotent local store, 5.96; `inviteCard.sign` signs a signup invite card and writes nothing, 5.101, and `inviteCard.verify` is a pure check that needs no identity, 5.102; `listing.mine` only reads local data, 5.106, `listing.consent` signs the deal consent and writes nothing, 5.109, and `listing.ratings` reads and verifies without storing, 5.110; `outbox.seal` and `outbox.open` only seal and open an outbox item in memory and change no stored state, 5.124 and 5.125). +Mutating methods (`MUTATING`, exported as a frozen array; test with `isMutating(method)`): `identity.create`, `cert.add`, `profile.set`, `profile.delete`, `username.add`, `post.create`, `post.reply`, `post.quote`, `post.delete`, `post.share` and `post.unshare` (5.122, 5.123), `like.set`, `repost.set`, `testimonial.write`, `testimonial.show`, `testimonial.decide` (5.100), `testimonial.delete`, `scrap.write`, `scrap.hide`, `scrap.wall` and `scrap.delete` (5.126 to 5.129), `profile.about`, `profile.mood` and `profile.extra.delete` (5.130 to 5.132), `fan.set` and `top.set` (5.133, 5.134), `choice.set` (5.135), `group.choose` (5.137), `moment.putMedia`, `moment.create`, `moment.delete` (5.113), `block.set`, `follow.add`, `follow.remove`, `sync.start`, `sync.stop`, `node.close`, and the IPC-only host controls `identity.install`, `identity.clear`, `identity.reset`, `identity.forget`, `identity.sessionSaved` and `media.uploadFile` (5.50 to 5.56), `page.register` (5.87), `listing.create`, `listing.status`, `listing.delete`, `listing.edit` and `listing.rate` (5.103, 5.104, 5.105, 5.107 and 5.108), `garden.set`, `garden.play` and `garden.help` (5.156, 5.158, 5.159) and `identity.recoveryBind` (5.94, it rewrites the kv passkey record). All others are reads (`account.sign`, `report.sign`, `appeal.sign`, `terms.sign`, `invite.sign`, `inviteCard.sign`, `push.sign`, `age.sign`, `phone.sign` and `page.sign` sign but write nothing, 5.18, 5.20, 5.99, 5.29, 5.30, 5.101, 5.31, 5.32, 5.115 and 5.84; `page.read` and `page.feed` only read, 5.85 and 5.86; `post.shared` only reads, 5.121; `age.proof` stores a verified attestation in local storage only and is idempotent, 5.83; `phone.proof` stores verified phone attestations in local storage only and is idempotent, 5.116; `recovery.sign` signs but writes nothing, 5.90, and the IPC-only recovery controls `identity.recoveryLookup`, `identity.recoveryOpen` and `identity.recoveryWrap`, 5.91 to 5.93, change no stored state (no diary, no kv record): lookup holds one wrap key in the worklet's memory, open consumes it whatever the outcome (a repeated open fails, 5.92), and wrap only draws a fresh nonce for a blob nobody has stored yet; `seen.sign` signs the seen state, 5.95, and `seen.merge` is an idempotent local store, 5.96; `inviteCard.sign` signs a signup invite card and writes nothing, 5.101, and `inviteCard.verify` is a pure check that needs no identity, 5.102; `listing.mine` only reads local data, 5.106, `listing.consent` signs the deal consent and writes nothing, 5.109, and `listing.ratings` reads and verifies without storing, 5.110; `outbox.seal` and `outbox.open` only seal and open an outbox item in memory and change no stored state, 5.124 and 5.125). The IPC-only host controls of the in-app web node (5.50 to 5.56) carry what the browser handle does in-page (section 11). The in-app web node never offers the legacy-follows confirmation (the handle's `follows` API, section 11): its storage is created fresh and therefore has no unsigned follow list, so its host handle reports no legacy follows. @@ -1503,6 +1503,44 @@ Cuts the writers of a lost device of the account, in every group and community, - Browser node: only after a passkey ceremony in this open of the app, not from a kept or resumed session; otherwise `USAGE` `'para conectar de novo, entre com a passkey'`. The host says which with `setKeyPair(keyPair, { fresh: true })` (`packages/web-member/lib/node.js`). The core node allows it: its data dir holds the identity. - Result: `{ id, registered: true, off: false }`. Emits `devices.changed` with `off: false` when the node had said `off: true`. +### 5.156 `garden.set` + +Varandinha (protocol section 2, "Varandinha"; section 5, "Seeder Varandinha index"; the rules are `lib/garden.js`, section 12). The four methods of 5.156 to 5.159 run on the browser node only, which is also the hosted app's in-app web node: the core node (`packages/core/lib/session.js`, the CLI and `varanda-serve`) answers all four with `USAGE` `'leitura sob demanda só na versão web'`, before anything is opened, because the help check needs peeks and the seeder index; a node whose rpc predates this section answers `USAGE` `'método desconhecido'`. No method takes a date or a free-text parameter: the node sets every `at` from its own clock, and any other key -> `USAGE` `'parâmetro desconhecido'`. The three writes (`garden.set`, `garden.play`, `garden.help`) follow the mutating-method rule of section 9: a timeout or connection loss after sending carries `uncertain: true`, the client never resends, and the app re-reads `garden.state` before offering the action again. They need the identity unlocked and catch up with the seeder first, as in section 11. + +- Params: `{ on: boolean }`. Mutating. Result: `{ on }`. +- `on: true` joins the game: it writes a `garden` record with `on: true` in the caller's diary, latest wins (the previous live `garden` block is tombstoned in the same append). When the caller's newest live `garden` flag is already on, it writes nothing and answers the same. +- `on: false` leaves the game: it first tombstones every live `garden-state` and `garden-help` block of the caller's diary, oldest first, and writes the `garden` record with `on: false` last. A leave cut short (a failed append after some blocks landed) keeps and pushes the blocks it did write (`written`) and answers the append's error, an error response (`uncertain: false`): the flag still reads on, so the app offers to leave again, and nothing retries it. A repeated leave re-reads the live blocks and finishes the job; a leave when the flag is already off and no `garden-state` or `garden-help` is live writes nothing. Leaving and joining again, or a leave cut short after its tombstones, starts the day's writer budgets (`savesToday`, `helpsToday`) afresh, since the earlier states and helps are tombstoned; readers still count at most one help per helper per balcony per day (`foldHelps`) over the live blocks. +- Refusals, in this order: a closed session -> `LOCKED` `'sessão encerrada'`; no identity -> `NOT_FOUND` `'identidade não encontrada'`; a locked identity -> `USAGE` `'identidade bloqueada: entre com a passkey'`; then the write gate of section 11. The caller's own diary is never a page: a page diary is written only by the account service under the page key (protocol section 12), never by a member's node, so there is no own page check. + +### 5.157 `garden.state` + +The caller's own balcony as the node reads it from the own diary. Not mutating: it writes nothing and makes no network call. Like `choice.mine`, it needs the identity but not the unlocked key (a locked identity reads too); no identity -> `NOT_FOUND` `'identidade não encontrada'`. Browser node only (core: the same `USAGE` as 5.156). + +- Params: `{}`. Result: `{ on, state, savesToday, helpsToday, given }`. + - `on`: a boolean, the caller's newest live `garden` flag (`false` when there is none). + - `state`: `{ seq, pots, n, at }` of the newest live `garden-state` block (`seq` its block seq, `pots` the six pots, `n` its save ordinal, `at` its canonical ISO), or `null` when there is none. The app draws growth from it under the reader's clock (`potView`), never the writer's. + - `savesToday`: the saves already made in the current Brasília day, against `GARDEN_SAVES_DAILY_MAX` (6). A newest state dated after the current day counts as today's (its `n`); one the node cannot read, or a clock it cannot read, reads as every save spent, never as a fresh budget. + - `helpsToday`: the own live `garden-help` blocks dated from the start of the current Brasília day, against `GARDEN_HELPS_DAILY_MAX` (5); a clock the node cannot read counts every help spent. + - `given`: `[{ seq, to, pot, at }]`, the caller's own live `garden-help` blocks dated within `GARDEN_HELP_WINDOW_MS` (72 h) before the node's clock and at most `GARDEN_MAX_FUTURE_MS` (24 h) after it, newest first (highest `seq` first), at most `GARDEN_HELP_ROWS` (24); `to` the watered balcony's key (hex64), `pot` 0..5, `at` the canonical ISO. + +### 5.158 `garden.play` + +Applies one play session to the caller's balcony and saves it as one `garden-state`. Mutating. Browser node only (core: the same `USAGE` as 5.156). + +- Params: `{ acts }`, an array of 1..`GARDEN_ACTS_MAX` (24) acts checked by `garden.isActs`: `{ op: 'plant', pot, plant }` with `plant` one of the `GARDEN_PLANTS` ids, or `{ op: 'water' | 'harvest' | 'clear', pot }`, `pot` an integer 0..5, each act with exactly those keys. Anything else -> `USAGE` `'parâmetro inválido: acts'`. +- Result: `{ seq, ref, state }`: `seq` and `ref` the newly written `garden-state` block of the caller's diary, `state` the saved state in the shape of 5.157 (`{ seq, pots, n, at }`). +- The node applies the whole batch with the shared rules (`applyActs`) to the newest live state (or six empty pots), under the node's clock, with the caller's own helps (`foldGiven`) and the most generous bound for helps received (`GARDEN_HELP_PER_POT` on each pot: helps received live in other diaries and the state is the writer's own claim). One bad act refuses the whole batch and nothing is written. One play is one save: it appends the tombstone of the previous state and the new state together, whatever the number of acts, with the next save ordinal `n` of the Brasília day (`saveOrdinal`). +- Refusals, after those of 5.156 (closed session, identity, then the write gate of section 11, so a second device of the same passkey plays on the freshest state): the caller's `garden` flag is off -> `USAGE` `'ligue a Varandinha para jogar'`; `GARDEN_SAVES_DAILY_MAX` (6) saves already made today -> `USAGE` `'você já cuidou da varanda o máximo de vezes por hoje'`; an act the rules refuse (planting a full pot, watering an empty pot or one watered too recently, harvesting a pot that is not ripe, clearing an empty pot) -> `USAGE` `'jogada inválida'`. + +### 5.159 `garden.help` + +Waters pot `pot` of another member's balcony: a `garden-help` record in the caller's own diary. Mutating. Browser node only (core: the same `USAGE` as 5.156). + +- Params: `{ to, pot }`, `to` the balcony owner's diary key (lowercase hex64), `pot` an integer 0..5 (`garden.isPotIndex`). Anything else -> `USAGE` `'parâmetro inválido: '` or `'parâmetro desconhecido'`. +- Result: `{ seq, ref }`, the newly written `garden-help` block of the caller's diary. The same append may carry tombstones of the caller's own helps older than `GARDEN_HELP_WINDOW_MS`, before the help. +- The node checks, in this order and before writing. First a closed session -> `LOCKED` `'sessão encerrada'`. On the serial chain: the identity as in 5.156 (no write gate yet); `to` (lowercased) is the caller -> `USAGE` `'não dá para regar a própria varanda'`; the caller has blocked `to` -> `USAGE` `'você bloqueou esta pessoa'`; the caller's own `garden` flag is off -> `USAGE` `'ligue a Varandinha para regar'`; then `helpAllowed` over the caller's follows and own helps: `to` is not followed -> `USAGE` `'você só rega a varanda de quem você segue'`; a help to `to` already dated in the current Brasília day -> `USAGE` `'você já regou esta varanda hoje'`; `GARDEN_HELPS_DAILY_MAX` (5) helps already given today -> `USAGE` `'você já regou o máximo de varandas por hoje'`. Off the chain, under one deadline (twice the peek timeout, at most 12 s): the seeder pointer (`/index/garden/`, protocol section 5) and one `diary.peek` of the owner's blocks 1, 2, the pointed flag and the pointed state, each verified with `validateRecord`: `to` is a page (a `page-roster` in its block 1 or 2) -> `USAGE` `'páginas não têm Varandinha'`; no pointed flag, or a pointed `garden` block whose `on` is not `true` or that is dated more than `GARDEN_MAX_FUTURE_MS` (24 h) after the node's clock -> `USAGE` `'esta pessoa não está na Varandinha'`; no pointed state, or a pointed `garden-state` dated more than `GARDEN_MAX_FUTURE_MS` after the node's clock or whose pot `pot` is empty, planted after the node's clock, or ripe (or unreadable) by `potView` under the node's clock with no boosts -> `USAGE` `'este vaso não tem planta para regar'`. Anything unread or unverified (no seeder answer or a malformed one, an index still indexing, a pointer that is neither `null` nor a seq, block 1 or 2 inside the diary but not read, a pointer to a missing block or to a block of another type, a state pointer below the flag pointer (an honest diary's live state follows its live flag: a leave tombstones every state before the off flag, and joining again writes a new flag), the deadline running out) -> `NOT_FOUND` `'semeador indisponível'` (fail closed: nothing is written). Back on the chain: the identity, `to` being the caller and the block again, then the catch-up with the seeder (section 11), then, inside the read that writes, the identity again (an identity switched since the check -> `USAGE` `'identidade bloqueada: entre com a passkey'`), the flag and `helpAllowed` again (a help sent from another device of the same passkey meanwhile is refused there), and the write. +- The policy is a courtesy check by the writer's own node: every reader counts helps itself with `foldHelps` (follow evidence, one help per helper per owner per day, `GARDEN_HELP_PER_POT` per pot), so a help written against the policy is never counted. + ## 6. Events | Event | `data` (exact keys) | @@ -1635,7 +1673,7 @@ This is the `isUnsafe` set of `packages/core/lib/safe.js` plus the three marks a - The handle's `follows` API (host controls, unlocked only, block 0 required): `follows.legacy()` -> `{ keys }`, the follows this device kept from before `follow` records existed that neither a `follow` record of the own diary nor a verified pending change mentions (sorted, at most `MAX_INVENTORY - 1`; `[]` once decided; an empty set marks the device done); `follows.confirmLegacy(keys)` -> `{ published }`: each key in both `keys` and that set is queued as a signed `on: true` change (appended by the drain under the replay rule of 5.9), every other legacy key leaves this device's list, and the device is marked done. `keys` must be at most `MAX_INVENTORY - 1` lowercase hex64 strings (else `TypeError('chaves inválidas')`); keys outside the set are ignored; errors keep their `code`. The app shows them as the Seguindo card "Pessoas que você seguia neste aparelho" (`docs/app.md`). - Media keys: one media core per DEVICE, signed by a key pair derived from the PRF output and the per-device nonce of kv `'mediaDevice'` (protocol §1 "Web member storage"); the pair is handed in with the identity pair (`setKeyPair(pair, { media })`), lives only in memory and is zero-filled with it. A media core holds at most `MAX_MEDIA_BLOCKS` blocks / 256 MiB; when it is full uploads fail with `'espaço de fotos deste aparelho esgotado'` (no rotation yet). The app calls `media.upload` only when the person presses Publicar (attached photos stay in the page's memory until then); once called, the stored bytes are public and permanent in the core even if a later upload or the post fails, and then stay unreferenced. - Replication of the own media cores: they are opened read-only (lazy storage) and replicated only on the verified seeder link, next to the diary; never announced, never downloaded into, never part of the goals. Push confirmation (the sync event `media-pushed`, diagnostic only, no line): a block counts as held when it is below the seeder peer's advertised contiguous length OR was served to it on this link (Hypercore 10.38.2 has no core-level remote length and the seeder does not re-advertise ranges it downloaded from us); "served" means sent with its proof, not proven stored. Once runs never wait for media; the app keeps a continuous run, which is where the confirmation arrives. Errors carry a `code`: `UNSUPPORTED`, `NO_PRF`, `NOT_SYNCED` (the authenticator data of a new passkey says it is not backup eligible: bound to one device), `CANCELLED`, `EXISTS`, `WEBAUTHN`, `MISMATCH` (the stored diary belongs to another key, checked before the pairs and the PRF reach the node, so a passkey of another identity never opens, and so never replaces, the direct message store of the stored one; `legacy: true` for a store from before the passkeys, whose stored secret the node wipes on its first open, after which the diary stays readable and is never writable; only `reset()` removes it) and `LOCKED` (another ceremony in flight); a `NO_PRF` or `NOT_SYNCED` from a passkey that exists anyway also carries `credentialId` and `userId` (hex), and, when the `register` ceremony of this page load just created that passkey (never a `complete()`, since by then a synced passkey may already be the account on another device; never a sign-in, never a creation restored after a reload, never the stored passkey), `cleaned`: true when the browser accepted the request to drop it (`PublicKeyCredential.signalUnknownCredential`), which means the browser was asked, not that the passkey was deleted. `NONE` (no passkey on the device) is a native-only code (`apps/app`), never raised by the browser handle. These are the handle's own errors, not RPC error codes (section 7). The kv entry `passkeyAttempts` (`{ v: 1, rpId, pending: { credentialId, userId, phone } | null, refused: [{ credentialId, userId, code, cleaned, created }] }`, no secret; `refused` keeps at most 32 entries: the cap evicts the oldest entries other than a `NOT_SYNCED` one with `created` true, and keeps only the newest 32 of those when they alone exceed it, `code` is `NO_PRF`, `NOT_SYNCED`, `SUPERSEDED` for a pending creation replaced by a newer one, `ADD_PENDING` for a recovery passkey creation (`addPasskey` or `finishRecovery`) that answered `{ pending: true }`, written at once because that pending creation lives in memory only (`created` true, `cleaned` false, never signalled for deletion; after a reload it keeps the passkey excluded from later creations and is never offered for `complete()`; a successful `complete()` or `bindPasskey` drops it), or `INSTALL_FAILED` for a new passkey whose PRF came with the creation but whose install failed (`MISMATCH`, `CANCELLED`, a storage error) while an older creation was pending; an entry stored without `created` reads as `created: false`) keeps the pending creation and the refused passkeys across reloads; a record for another rp.id reads as empty, and a stored `credentialId` that is not strict base64url (only `[A-Za-z0-9_-]`, non-empty, length % 4 not 1) is dropped on load. A creation that replaces a pending one supersedes it only once the new passkey is bound: when its install fails the older pending stays, so `complete()` still reaches it. A `{ pending: true }` answer made stale by `lock()`, `signOut()` or `reset()` during its write rejects `CANCELLED` instead, and a pending cleared by `reset()` is never written back. Refused ids are excluded from every later creation but never refused at sign-in, with one exception: a passkey this page created and refused as `NOT_SYNCED` (`created` true) is refused at sign-in too, with `NOT_SYNCED` carrying `credentialId`, `userId` and `cleaned: false`, its PRF output zeroed and nothing installed, while every other passkey, including one refused at sign-in for `NO_PRF`, keeps signing in; such a `NOT_SYNCED` entry is never rewritten to another code by a later failure of the same passkey, and a creation whose authenticator hands back that same passkey (ignoring `excludeCredentials`) is refused the same way, the entry kept. A ceremony's refusal bookkeeping (the entry, its write and the request to drop the passkey) runs before the ceremony lock is released, so a ceremony started meanwhile is refused with `LOCKED`. A successful unlock clears `pending` and drops its own id from `refused`; when it used another passkey than the pending creation, that creation moves to `refused` as `SUPERSEDED` (`created` true, `cleaned` false, no request to drop it) instead of being forgotten; `reset()` keeps the `NOT_SYNCED` entries with `created` true (they describe this browser's password managers, not the account) and clears `pending` and every other refused entry: it writes the entry with only those kept entries (`null` when none) before anything else and rejects with the storage error, changing nothing, when that write fails; a ceremony that began before a `reset()` and fails after it records nothing; `signOut()` keeps it. -- Writes need the key: `cert.add`, `profile.set`, `profile.delete`, `username.add`, `post.create`, `post.reply`, `post.quote`, `post.delete`, `post.share`, `post.unshare`, `like.set`, `repost.set`, `testimonial.write`, `testimonial.show`, `testimonial.delete`, `scrap.write`, `scrap.hide`, `scrap.wall`, `scrap.delete`, `profile.about`, `profile.mood`, `profile.extra.delete`, `fan.set`, `top.set`, `moment.create` and `moment.delete` fail with `USAGE` `'identidade bloqueada: entre com a passkey'` while the identity is locked (and `NOT_FOUND` `'identidade não encontrada'` with no identity); with a key that does not match the stored diary, `USAGE` `'passkey não corresponde ao diário guardado'`; when the catch-up with the seeder cannot confirm the diary is current (no answer within 15 s, an inventory that completed only by timeout, or the client detached meanwhile), `USAGE` `'sincronize com o semeador antes de publicar'` (or `'conexão encerrada'`) and nothing is written. Each of them first catches up with the seeder (`sync.event` line `'sincronizando antes de publicar'`) and then pushes (`'enviando ao semeador'`); both are internal runs that emit the usual `sync.started` / `sync.event` / `sync.stopped` (`once: true`). Other lines the session may emit: `'diário próprio sincronizado ()'`, `'diário próprio atrasado (/)'`, `'certificado recuperado do semeador'`. `identity.create` and `follow.*` are not gated (the browser node's follow drain runs the gate itself, 5.9); `follow.*` still needs the identity unlocked on the browser node. +- Writes need the key: `cert.add`, `profile.set`, `profile.delete`, `username.add`, `post.create`, `post.reply`, `post.quote`, `post.delete`, `post.share`, `post.unshare`, `like.set`, `repost.set`, `testimonial.write`, `testimonial.show`, `testimonial.delete`, `scrap.write`, `scrap.hide`, `scrap.wall`, `scrap.delete`, `profile.about`, `profile.mood`, `profile.extra.delete`, `fan.set`, `top.set`, `moment.create`, `moment.delete`, `garden.set`, `garden.play` and `garden.help` fail with `USAGE` `'identidade bloqueada: entre com a passkey'` while the identity is locked (and `NOT_FOUND` `'identidade não encontrada'` with no identity); with a key that does not match the stored diary, `USAGE` `'passkey não corresponde ao diário guardado'`; when the catch-up with the seeder cannot confirm the diary is current (no answer within 15 s, an inventory that completed only by timeout, or the client detached meanwhile), `USAGE` `'sincronize com o semeador antes de publicar'` (or `'conexão encerrada'`) and nothing is written. Each of them first catches up with the seeder (`sync.event` line `'sincronizando antes de publicar'`) and then pushes (`'enviando ao semeador'`); both are internal runs that emit the usual `sync.started` / `sync.event` / `sync.stopped` (`once: true`). Other lines the session may emit: `'diário próprio sincronizado ()'`, `'diário próprio atrasado (/)'`, `'certificado recuperado do semeador'`. `identity.create` and `follow.*` are not gated (the browser node's follow drain runs the gate itself, 5.9); `follow.*` still needs the identity unlocked on the browser node. - Results never carry a secret: the key pairs (identity and media) exist only inside the session (set by the handle's own `identity` code, zero-filled on lock, sign-out, reset and close), and no RPC result, event or `identity` return value contains them. The only secret at rest is the sealed PRF output of the stored session above (with its wrapping key in the same browser profile). - The WebSocket is `varanda-serve`'s job (T7): it binds loopback only, checks the `Host` and `Origin` headers, requires a token in `session.open` (high-entropy, compared with `tokensEqual`), rejects binary frames, parses with `parseMessage(text, MAX_REQUEST)` and drops a client whose queued outbound bytes exceed `MAX_OUTBOUND`. - `tokensEqual(a, b)` is constant-time over the longer length: no early exit on the first difference or on a length mismatch; a length mismatch or a non-string gives `false`. diff --git a/docs/verification/feat-varandinha-node.md b/docs/verification/feat-varandinha-node.md new file mode 100644 index 000000000..936910164 --- /dev/null +++ b/docs/verification/feat-varandinha-node.md @@ -0,0 +1,63 @@ +# Varandinha, o nó (PR feat/varandinha-node) + +Este PR acrescenta o contrato `garden.*` ao `@varanda/rpc` (os métodos `garden.set`, `garden.state`, `garden.play` e `garden.help` em `packages/rpc/lib/methods.js` e as seções 5.156 a 5.159 de `docs/rpc.md`), os stubs do nó do core (`packages/core/lib/session.js` responde aos quatro com `USAGE` `'leitura sob demanda só na versão web'`), as operações do nó do navegador (`gardenOwn`, `gardenSet`, `gardenLeave`, `gardenPlay`, `gardenHelpCheck` e `gardenHelp` em `packages/web-member/lib/member-ops.js`), os quatro handlers e a checagem do vaso do dono fora da cadeia (`gardenTarget`, que falha fechado) em `packages/web-member/lib/session.js`, e um teste de ponta a ponta com um semeador local (`packages/web-member/test/garden-e2e.test.js`). + +## Handlers do nó do navegador (`packages/web-member/lib/session.js`) + +Rodado no Node 24.22.1, sobre 2fd8e2a2 (a ponta de feat/varandinha-index, o PR de baixo da pilha), com as mudanças deste PR ainda fora de commit: + +- `npx standard packages/web-member/lib/session.js packages/web-member/test/garden-e2e.test.js` + resultado: passou. +- `npm test -w packages/web-member -- test/garden-e2e.test.js` + resultado: passou, 1/1 teste e 51/51 asserções, 1 arquivo, 0 falha. +- `npm test -w packages/web-member -- test/garden.test.js test/visits-e2e.test.js test/scraps.test.js` + resultado: passou, 3 arquivos, 0 falha; `garden.test.js` 20/20 testes e 130/130 asserções, `visits-e2e.test.js` 2/2 e 40/40, `scraps.test.js` 5/5 e 49/49. + +O que `packages/web-member/test/garden-e2e.test.js` cobre (um `Seeder` real atrás de `startSeedWs`, nós do navegador reais sobre armazenamento em memória, DHT local presa a `127.0.0.1` e diretórios temporários): + +- A entra na Varandinha (`garden.set` ligado); entrar de novo não escreve nada. A planta manjericão no vaso 0 numa jogada; `garden.state` devolve o estado salvo e `savesToday` 1. +- B segue A e C; antes de ligar a própria Varandinha a rega é recusada com `'ligue a Varandinha para regar'`; regar a si mesmo, `'não dá para regar a própria varanda'`. D, que liga a Varandinha mas não segue A, recebe `'você só rega a varanda de quem você segue'`. +- Com a sincronização de B rodando (as espiadas saem dela): C, que nunca entrou, `'esta pessoa não está na Varandinha'`; o vaso 3 vazio de A, `'este vaso não tem planta para regar'`. +- Falha fechada: com a resposta do índice `/index/garden/` trocando os ponteiros `on` e `state` (cada um aponta para um bloco de outro tipo), marcada como `indexing`, ou sem resposta, a rega responde `NOT_FOUND` `'semeador indisponível'`. O índice mente pela opção `fetchMedia` do nó, que repassa à rota real do semeador. +- A rega de B no vaso 0 de A dá certo e grava um `garden-help` com `to` e `pot`; a segunda rega à mesma varanda no mesmo dia de Brasília é recusada com `'você já regou esta varanda hoje'`; `garden.state` de B mostra `helpsToday` 1 e a rega em `given`. +- Na hora 3 (o `Date.now` do processo adiantado `GARDEN_WATER_GAP_MS` mais um minuto, como em `dm-moment-e2e.test.js`), A rega o manjericão: `w` 1 e `water` igual ao `at` do novo estado. +- A sai (`garden.set` desligado): `garden.state` com `on` falso, `state` nulo e `given` vazio; sair de novo não escreve nada. B sai e a rega some de `given` e de `helpsToday`. +- Toda recusa confere que o diário de quem chamou ficou do mesmo tamanho. + +Não coberto no teste de ponta a ponta: uma página como `to` (`'páginas não têm Varandinha'`). Registrar uma página exige o serviço de conta, que assina e anexa o diário da página com a chave dela; o teste não sobe esse serviço. A checagem é a mesma de `scrap.write` e `fan.set` (um `page-roster` no bloco 1 ou 2 espiado). + +Conferido que o teste falha sem a checagem: com a chamada a `gardenTarget` tirada de `garden.help`, o arquivo falhou nas recusas de C, do vaso vazio e nos três casos de falha fechada (asserções 27 a 36); com a chamada de volta, passou de novo. + +Conferido à mão que as seções 5.156 a 5.159 de `docs/rpc.md` descrevem a ordem das checagens, a saída sem nada a fazer, a leitura de `garden.state` sem a chave destravada e a resposta de falha fechada do código, e que não há travessão (U+2014) nem meia-risca (U+2013) nas linhas novas. + +## Contrato, stubs e operações (depois da revisão e da sincronização) + +Rodado no Node 24.22.1, sobre 9dd4ad75 (a ponta de feat/varandinha-index, já com a `main` em 063a3590), com as mudanças deste PR ainda fora de commit. As seções do `docs/rpc.md` passaram de 5.152 a 5.155 para 5.156 a 5.159, porque a `main` usou 5.152 a 5.155 para `device.*`. + +- `npx standard packages/rpc/lib/methods.js packages/rpc/test/methods.test.js packages/core/lib/session.js packages/core/test/engagement-session.test.js packages/web-member/lib/member-ops.js packages/web-member/lib/session.js packages/web-member/test/garden.test.js packages/web-member/test/garden-e2e.test.js` + resultado: passou. +- `node packages/rpc/test/methods.test.js` + resultado: passou, 7459/7459 asserções. +- `node packages/core/test/engagement-session.test.js` + resultado: passou, 136/136 asserções (os quatro `garden.*` respondem `USAGE` `'leitura sob demanda só na versão web'` sem escrever bloco; parâmetro a mais, `'parâmetro desconhecido'`). +- `node packages/web-member/test/garden.test.js` + resultado: passou, 22/22 testes e 160/160 asserções. Inclui `gardenTargetSeqs` (a lista da espiada, ou nada para recusar) e `gardenTargetVerdict` (20 casos de espiada montada: página, bloco 1 ou 2 faltando, bandeira desligada, de outro tipo ou datada mais de 24 h à frente, estado ausente, abaixo da bandeira, datado à frente, vaso vazio, plantado depois de agora, maduro). +- `node packages/web-member/test/garden-e2e.test.js` + resultado: passou, 51/51 asserções. +- `node packages/web-member/test/session-devices.test.js` + resultado: passou, 16/16 asserções (o arquivo da `main` que divide `session.js` com este PR). + +## CI completa + +Rodado na raiz, no Node 24.22.1, sobre 9dd4ad75 com as mudanças deste PR, na ordem da CI: + +- `npm ci --ignore-scripts` + resultado: passou. +- `npm run lint` + resultado: passou. +- `npm test -- --affected=origin/main` + resultado: passou, 821 arquivos de teste, 0 falha. +- `npm run demo` + resultado: passou, terminou com "DEMO OK". + +Não rodado: o Node 20 (a CI roda os dois); um navegador de verdade (os testes usam o nó do navegador sobre armazenamento em memória). diff --git a/packages/core/lib/session.js b/packages/core/lib/session.js index 9e8aad5a1..813321ca2 100644 --- a/packages/core/lib/session.js +++ b/packages/core/lib/session.js @@ -1107,6 +1107,22 @@ function createSession ({ return r }), + // Varandinha (docs/rpc.md garden.*): the help check needs peeks of the + // owner's diary and the seeder index the core node does not read; refused + // the same way, nothing written. + 'garden.set': serial(async () => { + throw new UsageError(PEEK_WEB_ONLY) + }), + 'garden.state': serial(async () => { + throw new UsageError(PEEK_WEB_ONLY) + }), + 'garden.play': serial(async () => { + throw new UsageError(PEEK_WEB_ONLY) + }), + 'garden.help': serial(async () => { + throw new UsageError(PEEK_WEB_ONLY) + }), + // Foruns e enquetes (docs/rpc.md): a vote checks the poll post with a // peek the core node does not make; refused, nothing written. 'choice.set': serial(async () => { diff --git a/packages/core/test/engagement-session.test.js b/packages/core/test/engagement-session.test.js index 2d6ea0831..28d712e52 100644 --- a/packages/core/test/engagement-session.test.js +++ b/packages/core/test/engagement-session.test.js @@ -224,6 +224,25 @@ test('the visitas methods are refused on the node session, nothing written', asy t.alike(await failure(m.call('visits.note', { key: 'zz' })), { code: 'USAGE', message: 'parâmetro inválido: key' }) }) +test('the varandinha methods are refused on the node session, nothing written', async (t) => { + const NO = { code: 'USAGE', message: 'leitura sob demanda só na versão web' } + const m = await member(t) + const before = await m.call('log.read') + t.alike(await failure(m.call('garden.set', { on: true })), NO) + t.alike(await failure(m.call('garden.set', { on: false })), NO) + t.alike(await failure(m.call('garden.state', {})), NO) + t.alike(await failure(m.call('garden.play', { acts: [{ op: 'plant', pot: 0, plant: 'manjericao' }] })), NO) + t.alike(await failure(m.call('garden.help', { to: OTHER, pot: 0 })), NO) + t.alike(await m.call('log.read'), before, 'nothing written') + t.alike(m.session.internal, []) + const UNKNOWN = { code: 'USAGE', message: 'parâmetro desconhecido' } + t.alike(await failure(m.call('garden.set', { on: true, extra: 1 })), UNKNOWN) + t.alike(await failure(m.call('garden.help', { to: OTHER, pot: 0, at: '2026-11-16T00:00:00.000Z' })), UNKNOWN) + t.alike(await failure(m.call('garden.set', { on: 'sim' })), { code: 'USAGE', message: 'parâmetro inválido: on' }) + t.alike(await failure(m.call('garden.help', { to: 'zz', pot: 0 })), { code: 'USAGE', message: 'parâmetro inválido: to' }) + t.alike(await failure(m.call('garden.help', { to: OTHER, pot: 6 })), { code: 'USAGE', message: 'parâmetro inválido: pot' }) +}) + test('the enquete methods are refused on the node session, nothing written', async (t) => { const NO = { code: 'USAGE', message: 'leitura sob demanda só na versão web' } const m = await member(t) diff --git a/packages/rpc/lib/methods.js b/packages/rpc/lib/methods.js index 814834a3c..f71423a0c 100644 --- a/packages/rpc/lib/methods.js +++ b/packages/rpc/lib/methods.js @@ -12,6 +12,7 @@ const { isReaction } = require('./reaction') const PX = require('./profile-extra') const { isPoll, isPick } = require('./poll') const { isEvent, copyEvent } = require('./event') +const garden = require('./garden') const HEX64 = /^[0-9a-f]{64}$/ const REF = /^([0-9a-f]{64}):(0|[1-9][0-9]*)$/ @@ -1599,6 +1600,15 @@ const SPECS = { 'visits.list': { fields: none }, 'visits.clear': { fields: none, mutating: true }, 'visits.note': { fields: { key: req(isKey) }, mutating: true }, + // Varandinha, browser node only (docs/rpc.md 5.156 to 5.159). garden.set + // turns the caller's own game on or off; garden.state reads it; garden.play + // applies one batch of acts as one save; garden.help waters pot `pot` of + // the balcony of `to`, a diary key. No date parameter: the node sets every + // `at` from its own clock. + 'garden.set': { fields: { on: req(isBool) }, mutating: true }, + 'garden.state': { fields: none }, + 'garden.play': { fields: { acts: req(garden.isActs) }, mutating: true }, + 'garden.help': { fields: { to: req(isKey), pot: req(garden.isPotIndex) }, mutating: true }, // Páginas (docs/rpc.md 5.84 to 5.87). page.sign signs a page statement or // a page record and appends nothing; the node fills in member, actor and // association, so a caller never chooses the bytes. The exact op of each diff --git a/packages/rpc/test/methods.test.js b/packages/rpc/test/methods.test.js index bc1e87f2a..27f499a26 100644 --- a/packages/rpc/test/methods.test.js +++ b/packages/rpc/test/methods.test.js @@ -20,7 +20,7 @@ test('method list and mutating set', (t) => { t.alike([...METHODS].sort(), [ 'account.sign', 'age.proof', 'age.sign', 'appeal.sign', 'block.list', 'block.set', 'cert.add', 'choice.mine', 'choice.set', 'community.admin', 'community.admit', 'community.ban', 'community.create', 'community.info', 'community.invitePolicy', 'community.join', 'community.leave', 'community.list', 'community.members', 'community.meta', 'community.removeGroup', 'community.requests', 'device.disconnect', 'device.hello', 'device.list', 'device.reconnect', 'diary.peek', 'dm.enable', 'dm.list', 'dm.lookup', 'dm.pageDraft', 'dm.pageForget', 'dm.pageGenerate', 'dm.pageLegacyBlocks', 'dm.pageLegacyChunk', 'dm.pageSecrets', 'dm.pageSend', 'dm.pageShare', 'dm.pull', 'dm.putMedia', 'dm.react', 'dm.reportSign', 'dm.seen', 'dm.send', 'dm.set', 'dm.thread', 'engagement.read', 'fan.set', 'feed.read', 'follow.add', 'follow.list', 'follow.remove', - 'group.admin', 'group.admit', 'group.ban', 'group.choose', 'group.create', 'group.events', 'group.hide', 'group.info', 'group.invitePolicy', 'group.join', 'group.leave', 'group.list', 'group.members', + 'garden.help', 'garden.play', 'garden.set', 'garden.state', 'group.admin', 'group.admit', 'group.ban', 'group.choose', 'group.create', 'group.events', 'group.hide', 'group.info', 'group.invitePolicy', 'group.join', 'group.leave', 'group.list', 'group.members', 'group.meta', 'group.post', 'group.react', 'group.reactors', 'group.read', 'group.rekey', 'group.requests', 'group.seal', 'group.seen', 'group.topics', 'group.voters', 'identity.clear', 'identity.create', 'identity.forget', 'identity.install', 'identity.recoveryBind', 'identity.recoveryLookup', 'identity.recoveryOpen', 'identity.recoveryWrap', 'identity.reset', 'identity.sessionSaved', 'identity.show', 'identity.status', 'invite.sign', 'inviteCard.sign', 'inviteCard.verify', 'like.set', 'listing.consent', 'listing.create', 'listing.delete', 'listing.edit', 'listing.mine', 'listing.rate', 'listing.ratings', 'listing.status', 'log.read', 'media.readFile', 'media.uploadFile', 'moment.create', 'moment.delete', 'moment.lookup', 'moment.putMedia', 'moment.seen', 'moments.read', 'moments.seen', 'node.close', 'node.info', 'notices.list', 'outbox.open', 'outbox.seal', @@ -29,7 +29,7 @@ test('method list and mutating set', (t) => { 'scrap.delete', 'scrap.hide', 'scrap.wall', 'scrap.write', 'seen.merge', 'seen.onceKey', 'seen.sign', 'session.open', 'sync.start', 'sync.status', 'sync.stop', 'terms.sign', 'testimonial.decide', 'testimonial.delete', 'testimonial.pending', 'testimonial.show', 'testimonial.write', 'top.set', 'username.add', 'visits.clear', 'visits.list', 'visits.note', 'visits.set', 'visits.state' ]) t.alike([...MUTATING].sort(), [ - 'block.set', 'cert.add', 'choice.set', 'community.admin', 'community.admit', 'community.ban', 'community.create', 'community.invitePolicy', 'community.join', 'community.leave', 'community.meta', 'community.removeGroup', 'device.disconnect', 'device.hello', 'device.reconnect', 'dm.enable', 'dm.pageForget', 'dm.pageLegacyChunk', 'dm.pageSecrets', 'dm.pageSend', 'dm.putMedia', 'dm.react', 'dm.send', 'dm.set', 'fan.set', 'follow.add', 'follow.remove', 'group.admin', 'group.admit', 'group.ban', + 'block.set', 'cert.add', 'choice.set', 'community.admin', 'community.admit', 'community.ban', 'community.create', 'community.invitePolicy', 'community.join', 'community.leave', 'community.meta', 'community.removeGroup', 'device.disconnect', 'device.hello', 'device.reconnect', 'dm.enable', 'dm.pageForget', 'dm.pageLegacyChunk', 'dm.pageSecrets', 'dm.pageSend', 'dm.putMedia', 'dm.react', 'dm.send', 'dm.set', 'fan.set', 'follow.add', 'follow.remove', 'garden.help', 'garden.play', 'garden.set', 'group.admin', 'group.admit', 'group.ban', 'group.choose', 'group.create', 'group.hide', 'group.invitePolicy', 'group.join', 'group.leave', 'group.meta', 'group.post', 'group.react', 'group.rekey', 'identity.clear', 'identity.create', 'identity.forget', 'identity.install', 'identity.recoveryBind', 'identity.reset', 'identity.sessionSaved', 'like.set', 'listing.create', 'listing.delete', 'listing.edit', 'listing.rate', 'listing.status', 'media.uploadFile', 'moment.create', 'moment.delete', 'moment.putMedia', 'node.close', 'page.register', 'post.create', 'post.delete', 'post.quote', 'post.reply', 'post.share', 'post.unshare', @@ -3177,6 +3177,56 @@ test('visits: limits and the five methods', (t) => { bad(t, 'visits.note', [KEY], 'array params') }) +test('garden: the four methods', (t) => { + const G = require('../lib/garden') + t.is(G.GARDEN_ACTS_MAX, 24) + t.is(G.GARDEN_POTS, 6) + for (const m of ['garden.set', 'garden.play', 'garden.help']) t.ok(isMutating(m), m + ' mutates') + t.absent(isMutating('garden.state'), 'garden.state only reads') + + ok(t, 'garden.set', { on: true }, { on: true }) + ok(t, 'garden.set', { on: false }, { on: false }) + for (const on of [undefined, null, 1, 0, 'true', 'false', {}, []]) bad(t, 'garden.set', { on }, 'on ' + String(on)) + bad(t, 'garden.set', {}, 'missing on') + bad(t, 'garden.set', { on: true, at: '2026-11-16T12:00:00.000Z' }, 'no at param on garden.set') + + ok(t, 'garden.state', {}, {}) + bad(t, 'garden.state', { extra: 1 }, 'extra field') + bad(t, 'garden.state', { on: true }, 'no on param on garden.state') + + const acts = [ + { op: 'plant', pot: 0, plant: 'manjericao' }, + { op: 'water', pot: 0 }, + { op: 'harvest', pot: 0 }, + { op: 'clear', pot: 5 } + ] + ok(t, 'garden.play', { acts }, { acts }) + for (const p of G.GARDEN_PLANTS) ok(t, 'garden.play', { acts: [{ op: 'plant', pot: 1, plant: p.id }] }) + ok(t, 'garden.play', { acts: Array.from({ length: 24 }, () => ({ op: 'water', pot: 2 })) }) + bad(t, 'garden.play', {}, 'missing acts') + bad(t, 'garden.play', { acts: [] }, 'empty acts') + bad(t, 'garden.play', { acts: Array.from({ length: 25 }, () => ({ op: 'water', pot: 2 })) }, '25 acts') + bad(t, 'garden.play', { acts: [{ op: 'dig', pot: 0 }] }, 'unknown op') + bad(t, 'garden.play', { acts: [{ op: 'water', pot: 0, extra: 1 }] }, 'act with an extra key') + bad(t, 'garden.play', { acts: [{ op: 'water', pot: 0, plant: 'tomate' }] }, 'water with a plant key') + bad(t, 'garden.play', { acts: [{ op: 'plant', pot: 0 }] }, 'plant without a plant id') + bad(t, 'garden.play', { acts: [{ op: 'plant', pot: 0, plant: 'rosa' }] }, 'unknown plant id') + bad(t, 'garden.play', { acts: [{ op: 'water', pot: 6 }] }, 'act pot 6') + bad(t, 'garden.play', { acts: [{ op: 'water', pot: 0 }, { op: 'dig', pot: 0 }] }, 'one bad act refuses the batch') + for (const v of [null, 1, 'water', { op: 'water', pot: 0 }]) bad(t, 'garden.play', { acts: v }, 'acts ' + JSON.stringify(v)) + bad(t, 'garden.play', { acts, at: '2026-11-16T12:00:00.000Z' }, 'no at param on garden.play') + t.is(validateParams('garden.play', { acts, at: '2026-11-16T12:00:00.000Z' }).message, 'parâmetro desconhecido') + + ok(t, 'garden.help', { to: KEY, pot: 0 }, { to: KEY, pot: 0 }) + ok(t, 'garden.help', { to: KEY, pot: 5 }, { to: KEY, pot: 5 }) + for (const pot of [6, -1, 1.5, '0', null, NaN, Infinity, true]) bad(t, 'garden.help', { to: KEY, pot }, 'pot ' + String(pot)) + for (const to of [KEY.toUpperCase(), KEY.slice(1), KEY + 'a', 'g'.repeat(64), '', null, 1, [KEY]]) bad(t, 'garden.help', { to, pot: 0 }, 'to ' + JSON.stringify(to)) + bad(t, 'garden.help', { pot: 0 }, 'missing to') + bad(t, 'garden.help', { to: KEY }, 'missing pot') + bad(t, 'garden.help', { to: KEY, pot: 0, at: '2026-11-16T12:00:00.000Z' }, 'no at param on garden.help') + bad(t, 'garden.help', { to: KEY, pot: 0, extra: 1 }, 'extra field') +}) + test('choice.set and choice.mine', (t) => { t.ok(isMutating('choice.set')) t.absent(isMutating('choice.mine')) diff --git a/packages/web-member/lib/member-ops.js b/packages/web-member/lib/member-ops.js index cae204159..9c7f9797d 100644 --- a/packages/web-member/lib/member-ops.js +++ b/packages/web-member/lib/member-ops.js @@ -66,6 +66,9 @@ const { fanRecord, topFriendsRecord, visitsRecord, + gardenRecord, + gardenStateRecord, + gardenHelpRecord, choiceRecord, momentRecord, postShareRecord, @@ -107,7 +110,7 @@ const { sealOffer, commitment } = require('@varanda/core/lib/testimonials') const grp = require('@varanda/core/lib/group') const gc = require('@varanda/core/lib/group-crypto') const { validPrivateItem, copyGroupMedia, PRIVATE_ITEM_KEYS, MAX_GROUP_MEDIA } = require('@varanda/core/lib/group-media') -const { GROUP_LIMIT_DEFAULT, GROUP_MEMBERS_LIMIT_MAX, GROUP_REACTIONS_MAX, GROUP_REACTORS_MAX, GROUP_TOPICS_LIMIT, GROUP_VOTERS_MAX, GROUP_EVENTS_LIMIT, POLL_MAX, COMMUNITY_LIST_MAX, feira, mediaBounds, videoBounds } = require('@varanda/rpc') +const { GROUP_LIMIT_DEFAULT, GROUP_MEMBERS_LIMIT_MAX, GROUP_REACTIONS_MAX, GROUP_REACTORS_MAX, GROUP_TOPICS_LIMIT, GROUP_VOTERS_MAX, GROUP_EVENTS_LIMIT, POLL_MAX, COMMUNITY_LIST_MAX, feira, garden, mediaBounds, videoBounds } = require('@varanda/rpc') const { livePick } = require('@varanda/core/lib/polls') const listing = require('@varanda/core/lib/listing') const { POST_SHARES_PER_DIARY, foldShare } = require('@varanda/core/lib/post-share') @@ -1627,6 +1630,215 @@ async function visitsSet (ctx, { on }) { return publishLatest(ctx, buildRecord(() => visitsRecord({ on: on === true }))) } +// ---- varandinha (docs/rpc.md garden.*) ---- + +const GARDEN_OFF_PLAY = 'ligue a Varandinha para jogar' +const GARDEN_SAVES_FULL = 'você já cuidou da varanda o máximo de vezes por hoje' +const GARDEN_BAD_PLAY = 'jogada inválida' +const GARDEN_HELP_SELF = 'não dá para regar a própria varanda' +const GARDEN_OFF_HELP = 'ligue a Varandinha para regar' +const GARDEN_NOT_FOLLOWING = 'você só rega a varanda de quem você segue' +const GARDEN_SAME_DAY = 'você já regou esta varanda hoje' +const GARDEN_HELPS_FULL = 'você já regou o máximo de varandas por hoje' + +// The own game blocks of the raw entries, read once: the newest live +// `garden` flag copy (null for none), and every live `garden-state` and +// `garden-help` copy as { seq, record }, ascending. A copy that fails +// validRecordCopy is skipped. +function gardenBlocks (raw) { + const deleted = deletedSeqs(raw) + let flag = null + const states = [] + const helps = [] + for (const { seq, record } of raw) { + if (deleted.has(seq)) continue + const copy = validRecordCopy(record, seq) + if (copy === null) continue + if (copy.type === 'garden') flag = copy + else if (copy.type === 'garden-state') states.push({ seq, record: copy }) + else if (copy.type === 'garden-help') helps.push({ seq, record: copy }) + } + return { on: flag !== null && flag.on === true, states, helps } +} + +async function readGarden (diary) { + return gardenBlocks(diary.length === 0 ? [] : await store.readRaw(diary)) +} + +// The own balcony -> { on, state, savesToday, helpsToday, given } (docs/rpc.md +// 5.157). A state dated after today counts as today's (its n); one +// saveOrdinal cannot read, or an unreadable clock, reads as every save +// spent, never as a fresh budget, and an unreadable clock reads every help +// spent. +async function gardenOwn (ctx, now) { + const g = await withIdentity(ctx, ({ diary }) => readGarden(diary)) + const last = g.states.length === 0 ? null : g.states[g.states.length - 1] + const state = last === null ? null : { seq: last.seq, pots: last.record.pots, n: last.record.n, at: last.record.at } + const n = garden.saveOrdinal(last === null ? null : last.record, now) + const today = garden.dayStart(now) + const helps = g.helps.map((h) => ({ seq: h.seq, to: h.record.to, pot: h.record.pot, at: h.record.at, ms: Date.parse(h.record.at) })) + const helpsToday = Number.isNaN(today) ? garden.GARDEN_HELPS_DAILY_MAX : helps.filter((h) => h.ms >= today).length + const given = helps + .filter((h) => h.ms >= now - garden.GARDEN_HELP_WINDOW_MS && h.ms <= now + garden.GARDEN_MAX_FUTURE_MS) + .sort((a, b) => b.seq - a.seq) + .slice(0, garden.GARDEN_HELP_ROWS) + .map(({ seq, to, pot, at }) => ({ seq, to, pot, at })) + return { + on: g.on, + state, + savesToday: n === null ? garden.GARDEN_SAVES_DAILY_MAX : n - 1, + helpsToday, + given + } +} + +// Opts in (publishLatest). The session compares with gardenOwn first and +// calls it only when the flag is not already on. -> { seq, ref }. +async function gardenSet (ctx) { + return publishLatest(ctx, buildRecord(() => gardenRecord({ on: true }))) +} + +// Leaves the game: tombstones every live garden-state and garden-help, oldest +// first, then writes the off flag LAST, so a leave cut short still reads on +// and a repeat re-reads the live blocks and converges. -> { seq, ref } of the +// flag, or null when there was nothing to do (flag not on, nothing live). +async function gardenLeave (ctx) { + const done = await withIdentity(ctx, async ({ diary, ownHex }) => { + const g = await readGarden(diary) + if (!g.on && g.states.length === 0 && g.helps.length === 0) return null + const seqs = [...g.states, ...g.helps].map((e) => e.seq).sort((a, b) => a - b) + if (seqs.length === 0) return { last: null } + const at = nowIso() + const tombs = seqs.map((seq) => buildRecord(() => deleteRecord({ seq, at }))) + const last = await appendChunked(ctx, diary, tombs) + await clearAfterDelete(ctx, diary, ownHex, seqs, tombs) + return { last } + }) + if (done === null) return null + try { + return await publishLatest(ctx, buildRecord(() => gardenRecord({ on: false }))) + } catch (err) { + if (done.last !== null && err !== null && typeof err === 'object' && !Number.isSafeInteger(err.written)) err.written = done.last + throw err + } +} + +// One play session saved as one garden-state (publishLatest: the previous +// state's tombstone and the new state in one append). received is the +// caller's bound on the neighbours' helps; this op never peeks. +// -> { seq, ref, state: { seq, pots, n, at } }. +async function gardenPlay (ctx, { acts, now, received }) { + const { n, pots } = await withIdentity(ctx, async ({ diary, ownHex }) => { + const g = await readGarden(diary) + if (!g.on) throw new UsageError(GARDEN_OFF_PLAY) + const prev = g.states.length === 0 ? null : g.states[g.states.length - 1].record + const n = garden.saveOrdinal(prev, now) + if (n === null) throw new UsageError(GARDEN_SAVES_FULL) + const given = garden.foldGiven({ self: ownHex, pots: prev === null ? null : prev.pots, given: g.helps, now }).perPot + const r = garden.applyActs(prev, acts, now, { received, given }) + if (r === null || typeof r !== 'object' || r.ok !== true) throw new UsageError(GARDEN_BAD_PLAY) + return { n, pots: r.state.pots } + }) + const at = new Date(now).toISOString() + const { seq, ref } = await publishLatest(ctx, buildRecord(() => gardenStateRecord({ pots, n, at }))) + return { seq, ref, state: { seq, pots, n, at } } +} + +function helpRefusal (reason) { + if (reason === 'self') return GARDEN_HELP_SELF + if (reason === 'not-following') return GARDEN_NOT_FOLLOWING + if (reason === 'same-day') return GARDEN_SAME_DAY + if (reason === 'daily') return GARDEN_HELPS_FULL + return GARDEN_BAD_PLAY +} + +// The help checks over one open own diary -> the own game blocks, or a +// UsageError. Follows come from the diary's live `follow` records, not kv +// follows: a reader counts a help only with the helper's follow block, and a +// queued follow op is not in the diary yet. +async function checkHelp (diary, ownHex, { to, writer, now }) { + if (ownHex !== writer) throw new UsageError(store.LOCKED) + if (to === ownHex) throw new UsageError(GARDEN_HELP_SELF) + const g = await readGarden(diary) + if (!g.on) throw new UsageError(GARDEN_OFF_HELP) + const follows = new Set(diary.length === 0 ? [] : followSet(await store.readAll(diary), ownHex)) + const own = g.helps.map((h) => ({ to: h.record.to, at: h.record.at })) + const verdict = garden.helpAllowed({ self: ownHex, to, follows, own, now }) + if (verdict.ok !== true) throw new UsageError(helpRefusal(verdict.reason)) + return g +} + +// gardenHelp's checks alone, writing nothing (the session runs them before +// its peek of the owner). -> undefined, or gardenHelp's UsageError. +async function gardenHelpCheck (ctx, { to, writer, now }) { + await withIdentity(ctx, ({ diary, ownHex }) => checkHelp(diary, ownHex, { to, writer, now })) +} + +const isGardenSeq = (v) => Number.isSafeInteger(v) && v >= 1 + +// The owner blocks a help target check peeks, from the seeder's +// /index/garden/ answer: blocks 1 and 2 (a page roster) and the two +// pointers, ascending. -> seqs, or null when the answer is indexing or +// malformed (the session fails closed). +function gardenTargetSeqs (index) { + if (index === null || typeof index !== 'object' || index.indexing === true) return null + const { on, state } = index + if ((on !== null && !isGardenSeq(on)) || (state !== null && !isGardenSeq(state))) return null + const wanted = new Set([1, 2]) + if (on !== null) wanted.add(on) + if (state !== null) wanted.add(state) + return [...wanted].sort((a, b) => a - b) +} + +// Judges a help target from the index answer and the verified peek of the +// gardenTargetSeqs blocks (`{ entries: [{ seq, record }], missing, length }`). +// -> null (a planted, growing pot of an opted-in member), 'page', 'off', +// 'no-plant' or 'unavailable' (anything the peek did not prove). +function gardenTargetVerdict (index, peek, pot, now) { + const { on, state } = index + const at = (seq) => peek.entries.find((e) => e.seq === seq) + if (peek.entries.some((e) => e.seq <= 2 && e.record.type === 'page-roster')) return 'page' + if ([1, 2].some((q) => q < peek.length && peek.missing.includes(q))) return 'unavailable' + if (on === null) return 'off' + const flag = at(on) + if (flag === undefined || flag.record.type !== 'garden') return 'unavailable' + const ahead = now + garden.GARDEN_MAX_FUTURE_MS + // Readers drop a flag or state dated past MAX_FUTURE (foldBalcony). + if (flag.record.on !== true || !(Date.parse(flag.record.at) <= ahead)) return 'off' + if (state === null) return 'no-plant' + // An honest diary's live state follows its live on flag: a leave + // tombstones every state before the off flag, a rejoin writes a new flag. + if (state < on) return 'unavailable' + const s = at(state) + if (s === undefined || s.record.type !== 'garden-state' || !Array.isArray(s.record.pots)) return 'unavailable' + if (!(Date.parse(s.record.at) <= ahead)) return 'no-plant' + const p = s.record.pots[pot] + if (p === null || p === undefined || !(Date.parse(p.at) <= now)) return 'no-plant' + const view = garden.potView(p, now) + if (view === null || view.ripe) return 'no-plant' + return null +} + +// Waters pot `pot` of `to`'s balcony: one append of the tombstones of the own +// helps older than the window (oldest first, at most APPEND_MAX - 1) and the +// new garden-help last. The pot check against the owner's balcony is the +// session's. -> { seq, ref }. +async function gardenHelp (ctx, { to, pot, writer, now }) { + return withIdentity(ctx, async ({ diary, ownHex }) => { + const g = await checkHelp(diary, ownHex, { to, writer, now }) + const cutoff = now - garden.GARDEN_HELP_WINDOW_MS + const old = g.helps.filter((h) => { + const ms = Date.parse(h.record.at) + return !Number.isFinite(ms) || ms < cutoff + }).slice(0, APPEND_MAX - 1) + const at = new Date(now).toISOString() + const tombs = old.map((h) => buildRecord(() => deleteRecord({ seq: h.seq, at }))) + const seq = await appendChunked(ctx, diary, [...tombs, buildRecord(() => gardenHelpRecord({ to, pot, at }))]) + if (old.length > 0) await clearAfterDelete(ctx, diary, ownHex, old.map((h) => h.seq), tombs) + return { seq, ref: formatRef({ author: ownHex, seq }) } + }) +} + const NOTHING_TO_DELETE = 'nada para apagar' // The seqs of the live (not tombstoned) blocks of `type` in the own diary's @@ -6513,6 +6725,22 @@ module.exports = { ownTopKeys, visitsState, visitsSet, + gardenOwn, + gardenSet, + gardenLeave, + gardenPlay, + gardenHelpCheck, + gardenHelp, + gardenTargetSeqs, + gardenTargetVerdict, + GARDEN_OFF_PLAY, + GARDEN_SAVES_FULL, + GARDEN_BAD_PLAY, + GARDEN_HELP_SELF, + GARDEN_OFF_HELP, + GARDEN_NOT_FOLLOWING, + GARDEN_SAME_DAY, + GARDEN_HELPS_FULL, profileExtraDelete, momentCreate, momentDelete, diff --git a/packages/web-member/lib/session.js b/packages/web-member/lib/session.js index fe9c0bbb1..289db5613 100644 --- a/packages/web-member/lib/session.js +++ b/packages/web-member/lib/session.js @@ -287,7 +287,7 @@ // unlock with a dm-key). reset() removes the local store and the dm kv. const b4a = require('b4a') const crypto = require('hypercore-crypto') -const { RpcError, isSafeMessage, capList, capSyncResult, clipText, MAX_LINE, MAX_ID, PEEK_TIMEOUT_MS, PEEK_SEQS_MAX, TESTIMONIAL_PENDING_MAX, TESTIMONIAL_KEPT_MAX, TESTIMONIAL_DECLINED_MAX, FEED_INCOMPLETE_MAX, mediaBounds, audioBounds, stripAudioMetadata, AUDIO_MS_TOLERANCE, videoBounds, stripVideoMetadata, VIDEO_MS_TOLERANCE } = require('@varanda/rpc') +const { RpcError, isSafeMessage, capList, capSyncResult, clipText, MAX_LINE, MAX_ID, PEEK_TIMEOUT_MS, PEEK_SEQS_MAX, TESTIMONIAL_PENDING_MAX, TESTIMONIAL_KEPT_MAX, TESTIMONIAL_DECLINED_MAX, FEED_INCOMPLETE_MAX, mediaBounds, audioBounds, stripAudioMetadata, AUDIO_MS_TOLERANCE, videoBounds, stripVideoMetadata, VIDEO_MS_TOLERANCE, garden } = require('@varanda/rpc') const { validRecordCopy, validateRecord, @@ -375,6 +375,13 @@ const SCRAP_NOBODY = 'esta pessoa não está recebendo recados' const SCRAP_INDEX_MAX_CHARS = 64 * 1024 const FOLLOW_INDEX_MAX_CHARS = 1024 const VISIT_INDEX_MAX_CHARS = 16 * 1024 +// Varandinha (docs/rpc.md 5.159): the help target's refusals, read off the +// chain from the owner's blocks. The index cap holds the seeder route's +// largest body (apps/cli/lib/seed-ws.js INDEX_MAX_BODY). +const GARDEN_PAGE = 'páginas não têm Varandinha' +const GARDEN_NOT_IN = 'esta pessoa não está na Varandinha' +const GARDEN_NO_PLANT = 'este vaso não tem planta para regar' +const GARDEN_INDEX_MAX_CHARS = 64 * 1024 // visits.set { on: true } without private messages enabled (no dm key): a // switch on could neither queue a ping nor be pinged. Same text as the // app's DMS_OFF_NOTICE (apps/app/src/visits.js). @@ -3475,6 +3482,55 @@ function createBrowserSession ({ if (e === undefined || e.record.type !== 'follow' || e.record.key !== writer || e.record.on !== true) throw new Error(SEEDER_UNAVAILABLE) } + // garden.help's evidence deadline (docs/rpc.md 5.159): scrap.write's. + const gardenEvidenceMs = Math.min(12000, 2 * peekTimeoutMs) + + // Whether pot `pot` of `owner`'s balcony takes a help now, with public + // evidence only, read off the chain under ONE deadline as scrapAdmits: the + // seeder names the owner's newest garden flag and garden-state, each a + // pointer, peeked and checked here with blocks 1 and 2 (a page-roster + // there is a page). Returns when the help may be written; throws a USAGE + // refusal when the verified evidence excludes it, and SEEDER_UNAVAILABLE + // (or the peek's own NOT_FOUND) when it cannot be read or does not verify. + // RESIDUAL: the seeder can point at an older live 'on' flag or an older + // state it still serves (it can withhold any newer block); readers apply + // foldHelps and drop a help that does not count, so a wrong write costs + // one of the helper's daily helps and nothing else. + async function gardenTarget (owner, pot) { + const deadline = Date.now() + gardenEvidenceMs + let timer = null + const late = new Promise((resolve, reject) => { + timer = setTimeout(() => reject(new Error(SEEDER_UNAVAILABLE)), gardenEvidenceMs) + }) + const work = gardenEvidence(owner, pot, deadline) + try { + return await Promise.race([work, late]) + } finally { + clearTimeout(timer) + work.catch(() => {}) + } + } + + async function gardenEvidence (owner, pot, deadline) { + const left = () => { + const ms = deadline - Date.now() + if (ms <= 0) throw new Error(SEEDER_UNAVAILABLE) + return ms + } + const index = await seederIndexJson('/index/garden/' + owner, GARDEN_INDEX_MAX_CHARS, left()) + // A refusal never rests on an index still catching up. + const seqs = member.gardenTargetSeqs(index) + if (seqs === null) throw new Error(SEEDER_UNAVAILABLE) + const r = await peekBefore(owner, seqs, deadline) + // No boosts in the pot check: the generous reading is the reader's. + const verdict = member.gardenTargetVerdict(index, r, pot, Date.now()) + if (verdict === null) return + if (verdict === 'page') throw new UsageError(GARDEN_PAGE) + if (verdict === 'off') throw new UsageError(GARDEN_NOT_IN) + if (verdict === 'no-plant') throw new UsageError(GARDEN_NO_PLANT) + throw new Error(SEEDER_UNAVAILABLE) + } + // Refuses (USAGE `message`) a key whose diary is a page: blocks 1 and 2 // tell a page diary (a page-roster there) from a person's, peeked as the // recados check does. Fails closed: an unread block 1 or 2 inside the @@ -4988,6 +5044,91 @@ function createBrowserSession ({ })({}, ident) }, + // Varandinha (docs/rpc.md 5.156 to 5.159). The game lives in public + // records of the own diary, written like profile.mood and never retried; + // a help is checked like scrap.write: the own checks on the chain, the + // owner's balcony off it (gardenTarget, fail closed), then the checks + // again and the write on the chain, so a help sent from another device + // of the same passkey meanwhile is refused there. + 'garden.set': async ({ on }) => { + if (closed) throw rpcError('LOCKED', CLOSED_MESSAGE) + return serial(async (_, epoch) => { + await requireUnlocked() + await ensureCaughtUp(epoch) + if (on === true) { + const cur = await withCores((c) => member.gardenOwn(c, Date.now())) + if (cur.on !== true) await profileExtraWrite((c) => member.gardenSet(c)) + return { on: true } + } + // A leave that finds nothing to do (null) writes and pushes nothing; + // one cut short counts and pushes the blocks that landed (written). + let r + try { + r = await withStore((c) => member.gardenLeave(c)) + } catch (err) { + if (err !== null && typeof err === 'object' && Number.isSafeInteger(err.written)) { + wrote(err.written) + try { await pushAfterWrite() } catch {} + } + throw err + } + if (r !== null) { + wrote(r.seq) + await pushAfterWrite() + } + return { on: false } + })({}) + }, + + // The own diary alone, as choice.mine: no key needed to read it. + 'garden.state': serial(() => withCores((c) => member.gardenOwn(c, Date.now()))), + + // Caught up first, so a second device of the same passkey plays on the + // freshest state. Helps received are bounded generously (they live in + // other diaries; readers fold them). + 'garden.play': async ({ acts }) => { + if (closed) throw rpcError('LOCKED', CLOSED_MESSAGE) + return serial(async (_, epoch) => { + await requireUnlocked() + await ensureCaughtUp(epoch) + let state = null + const r = await profileExtraWrite(async (c) => { + const out = await member.gardenPlay(c, { acts, now: Date.now(), received: Array(garden.GARDEN_POTS).fill(garden.GARDEN_HELP_PER_POT) }) + state = out.state + return out + }) + return { seq: r.seq, ref: r.ref, state } + })({}) + }, + + 'garden.help': async ({ to, pot }) => { + if (closed) throw rpcError('LOCKED', CLOSED_MESSAGE) + const key = to.toLowerCase() + const refuse = async (own) => { + if (key === own) throw new UsageError(member.GARDEN_HELP_SELF) + if ((await member.memberBlocks(storage)).has(key)) throw new UsageError(DM_BLOCKED) + } + const writer = await serial(async () => { + const own = await requireUnlocked() + await refuse(own) + await withCores((c) => member.gardenHelpCheck(c, { to: key, writer: own, now: Date.now() })) + return own + })({}) + try { + await gardenTarget(key, pot) + } catch (err) { + throw toRpcError(err, reportInternal) + } + return serial(async (_, epoch) => { + await refuse(await requireUnlocked()) + await ensureCaughtUp(epoch) + const r = await withStore((c) => member.gardenHelp(c, { to: key, pot, writer, now: Date.now() })) + wrote(r.seq) + await pushAfterWrite() + return { seq: r.seq, ref: r.ref } + })({}) + }, + // Momentos (docs/rpc.md 5.113): the item must be one this node's // momentPutMedia answered in this unlock; published like post.create. // A published item is never offered for a second moment. diff --git a/packages/web-member/test/garden-e2e.test.js b/packages/web-member/test/garden-e2e.test.js new file mode 100644 index 000000000..c53df6115 --- /dev/null +++ b/packages/web-member/test/garden-e2e.test.js @@ -0,0 +1,206 @@ +'use strict' + +// Varandinha end to end (docs/rpc.md 5.156 to 5.159): the real Seeder behind +// startSeedWs (the WebSocket entry and the /index/garden route) and real +// browser nodes (lib/node.js over in-memory storage) on the local DHT, tmp +// dirs only. The helper's seeder index reads go through a fetchMedia seam +// that forwards to the real route, or makes the answer lie or vanish, to +// show the help check failing closed. Every refusal writes nothing. + +const test = require('brittle') +const fs = require('node:fs') +const path = require('node:path') +const crypto = require('hypercore-crypto') +const { WebSocket } = require('ws') +const { testnet, tmpDir, localSwarmOptions, until } = require('./helpers/net') +const { connectClient, errorOf } = require('./helpers/session') +const { createCert, createSeederCert, generateAssociationKeyPair } = require('@varanda/core/lib/cert') +const { Seeder } = require('@varanda/core/lib/seeder') +const { garden } = require('@varanda/rpc') +const { createBrowserNode } = require('../lib/node') +const { memoryNodeStorage } = require('../lib/node-storage') +const { hex, push } = require('./helpers/dm-e2e') +const { startSeedWs } = require('../../../apps/cli/lib/seed-ws') + +const UNAVAILABLE = ['NOT_FOUND', 'semeador indisponível'] +const HOUR = 3600000 + +function noop () {} + +async function seederStack (t, bootstrap, assoc) { + const dataDir = tmpDir(t, 'varanda-garden-seed-') + Seeder.ensureConfig(dataDir, assoc.hex) + const { publicKey } = Seeder.createKey(dataDir) + const certFile = path.join(tmpDir(t, 'varanda-garden-sc-'), 'seeder-cert.json') + fs.writeFileSync(certFile, JSON.stringify(createSeederCert({ seeder: publicKey }, assoc.kp))) + Seeder.addCert(dataDir, certFile, assoc.hex) + const seeder = new Seeder({ dataDir, associationKey: assoc.hex, ...localSwarmOptions(bootstrap), log: noop }) + t.teardown(() => seeder.close(), { force: true }) + await seeder.start() + const ws = await startSeedWs({ port: 0, seeder }) + t.teardown(() => ws.close(), { force: true }) + return { current: seeder, port: ws.port, url: 'ws://127.0.0.1:' + ws.port + '/seeder' } +} + +// A certified member node, pushed. index.mode steers its seeder index reads +// of /index/garden/: 'real' forwards, 'swap' exchanges the on and state +// pointers, 'indexing' marks the answer as still indexing, 'dead' fails the +// request. +async function memberNode (t, assoc, host) { + const index = { mode: 'real' } + const node = createBrowserNode({ + storage: memoryNodeStorage(), + association: assoc.hex, + seederUrl: host.url, + createSocket: (u) => { + const ws = new WebSocket(u) + ws.on('error', noop) + return ws + }, + syncOptions: { retryMinMs: 100, retryMaxMs: 200 }, + writeGate: false, + fetchMedia: async (url, opts) => { + if (!String(url).includes('/index/garden/') || index.mode === 'real') return fetch(url, opts) + if (index.mode === 'dead') throw new Error('rede indisponível') + const body = await (await fetch(url, opts)).json() + if (index.mode === 'swap') [body.on, body.state] = [body.state, body.on] + if (index.mode === 'indexing') body.indexing = true + return new Response(JSON.stringify(body), { status: 200 }) + } + }) + t.teardown(() => node.close(), { force: true }) + await node.setKeyPair(crypto.keyPair(), { prf: crypto.randomBytes(32) }) + const web = await connectClient(node, { timeoutMs: 60000 }) + const { publicKey } = await web.request('identity.create') + await web.request('cert.add', { cert: createCert({ member: publicKey }, assoc.kp) }) + const n = { node, web, key: publicKey, index } + await push(t, n, host) + return n +} + +async function gardenIndex (host, key) { + try { + const res = await fetch('http://127.0.0.1:' + host.port + '/index/garden/' + key, { cache: 'no-store' }) + if (res.status !== 200) return null + return await res.json() + } catch { + return null + } +} + +// Waits until the seeder's garden index of `n` is caught up and passes `ok`. +async function indexed (host, n, ok) { + await until(async () => { + const body = await gardenIndex(host, n.key) + return body !== null && body.indexing === false && ok(body) + }, { name: 'garden index', timeoutMs: 60000, intervalMs: 300 }) +} + +// The own diary is dense (seq = position): its length from one log.read. +async function lengthOf (n) { + const r = await n.web.request('log.read', {}) + return r.entriesTruncated + r.entries.length + r.invalid.length +} + +// The refusal [code, message] of a call that must write nothing. +async function refusal (t, n, method, params) { + const before = await lengthOf(n) + const err = await errorOf(n.web.request(method, params)) + t.is(await lengthOf(n), before, method + ' wrote nothing') + return [err && err.code, err && err.message] +} + +// Runs fn with Date.now moved `ms` ahead (every node here shares the clock). +async function later (ms, fn) { + const realNow = Date.now + Date.now = () => realNow() + ms + try { + return await fn() + } finally { + Date.now = realNow + } +} + +test('varandinha end to end: opt in, play, help a followed balcony, refusals, fail closed, water at hour 3, leave', async (t) => { + t.timeout(600000) + const { bootstrap } = await testnet(t) + const kp = generateAssociationKeyPair() + const assoc = { kp, hex: hex(kp.publicKey) } + const host = await seederStack(t, bootstrap, assoc) + const A = await memberNode(t, assoc, host) + const B = await memberNode(t, assoc, host) + const C = await memberNode(t, assoc, host) + const D = await memberNode(t, assoc, host) + + // A opts in once and plants manjericão in pot 0. + t.alike(await A.web.request('garden.state', {}), { on: false, state: null, savesToday: 0, helpsToday: 0, given: [] }) + t.alike(await A.web.request('garden.set', { on: true }), { on: true }) + const afterOn = await lengthOf(A) + t.alike(await A.web.request('garden.set', { on: true }), { on: true }, 'already on') + t.is(await lengthOf(A), afterOn, 'a second opt in writes nothing') + const planted = await A.web.request('garden.play', { acts: [{ op: 'plant', pot: 0, plant: 'manjericao' }] }) + t.is(planted.ref, A.key + ':' + planted.seq) + t.is(planted.state.seq, planted.seq) + t.is(planted.state.n, 1) + t.is(planted.state.pots[0].plant, 'manjericao') + t.alike(planted.state.pots.slice(1), [null, null, null, null, null]) + const own = await A.web.request('garden.state', {}) + t.is(own.on, true) + t.alike(own.state, planted.state, 'the saved state') + t.is(own.savesToday, 1) + await push(t, A, host) + await indexed(host, A, (b) => b.state === planted.seq && b.on !== null) + await indexed(host, C, (b) => b.on === null) + + // B follows A and C (drained into B's diary by the next request). + await B.web.request('follow.add', { key: A.key }) + await B.web.request('follow.add', { key: C.key }) + t.ok((await B.web.request('log.read', {})).entries.filter((e) => e.record.type === 'follow').length === 2, 'both follows in B\'s diary') + + // Refused on the chain, before any index read. + t.alike(await refusal(t, B, 'garden.help', { to: A.key, pot: 0 }), ['USAGE', 'ligue a Varandinha para regar'], 'own flag off') + t.alike(await refusal(t, B, 'garden.help', { to: B.key, pot: 0 }), ['USAGE', 'não dá para regar a própria varanda'], 'self') + t.alike(await B.web.request('garden.set', { on: true }), { on: true }) + t.alike(await D.web.request('garden.set', { on: true }), { on: true }) + t.alike(await refusal(t, D, 'garden.help', { to: A.key, pot: 0 }), ['USAGE', 'você só rega a varanda de quem você segue'], 'D does not follow A') + + // The owner's balcony, read off the chain through B's running sync. + await B.web.request('sync.start', {}) + t.alike(await refusal(t, B, 'garden.help', { to: C.key, pot: 0 }), ['USAGE', 'esta pessoa não está na Varandinha'], 'C never opted in') + t.alike(await refusal(t, B, 'garden.help', { to: A.key, pot: 3 }), ['USAGE', 'este vaso não tem planta para regar'], 'an empty pot') + + // Fail closed: a lying or missing index answer writes nothing. + for (const mode of ['swap', 'indexing', 'dead']) { + B.index.mode = mode + t.alike(await refusal(t, B, 'garden.help', { to: A.key, pot: 0 }), UNAVAILABLE, 'index ' + mode) + } + B.index.mode = 'real' + + const helped = await B.web.request('garden.help', { to: A.key, pot: 0 }) + t.is(helped.ref, B.key + ':' + helped.seq) + const written = (await B.web.request('log.read', {})).entries.find((e) => e.seq === helped.seq) + t.alike([written.record.type, written.record.to, written.record.pot], ['garden-help', A.key, 0]) + t.alike(await refusal(t, B, 'garden.help', { to: A.key, pot: 0 }), ['USAGE', 'você já regou esta varanda hoje'], 'the same balcony the same day') + const mine = await B.web.request('garden.state', {}) + t.is(mine.helpsToday, 1) + t.alike(mine.given, [{ seq: helped.seq, to: A.key, pot: 0, at: written.record.at }]) + + // Hour 3: the manjericão takes water (the node clock moved ahead). + const watered = await later(garden.GARDEN_WATER_GAP_MS + 60000, () => A.web.request('garden.play', { acts: [{ op: 'water', pot: 0 }] })) + t.is(watered.state.pots[0].w, 1, 'watered once') + t.is(watered.state.pots[0].water, watered.state.at) + t.ok(Date.parse(watered.state.at) - Date.parse(planted.state.at) >= 3 * HOUR) + + // Leaving tombstones the states and helps and writes the off flag last; + // a second leave writes nothing. + t.alike(await A.web.request('garden.set', { on: false }), { on: false }) + const left = await A.web.request('garden.state', {}) + t.alike([left.on, left.state, left.given], [false, null, []]) + const afterLeave = await lengthOf(A) + t.alike(await A.web.request('garden.set', { on: false }), { on: false }) + t.is(await lengthOf(A), afterLeave, 'a second leave writes nothing') + + t.alike(await B.web.request('garden.set', { on: false }), { on: false }) + const gone = await B.web.request('garden.state', {}) + t.alike([gone.on, gone.helpsToday, gone.given], [false, 0, []], 'the helper\'s help is withdrawn with the leave') +}) diff --git a/packages/web-member/test/garden.test.js b/packages/web-member/test/garden.test.js new file mode 100644 index 000000000..bab7881bc --- /dev/null +++ b/packages/web-member/test/garden.test.js @@ -0,0 +1,465 @@ +// The Varandinha writes and reads of the browser node (docs/rpc.md garden.*) +// called straight on member-ops, on memory storage with no seeder and no +// network: the own state, the opt in, a leave (tombstones first, the off +// flag last), one play session as one saved state and one help to a +// followed balcony, with every refusal writing nothing. Every clock is a +// fixed `now`. +const test = require('brittle') +const b4a = require('b4a') +const crypto = require('hypercore-crypto') +const { createCert, generateAssociationKeyPair } = require('@varanda/core/lib/cert') +const { validateRecord, gardenRecord, gardenStateRecord, gardenHelpRecord, followRecord } = require('@varanda/core/lib/records') +const { deletedSeqs } = require('@varanda/core/lib/deletion') +const { garden } = require('@varanda/rpc') +const { memoryNodeStorage } = require('../lib/node-storage') +const store = require('../lib/node-store') +const member = require('../lib/member-ops') + +const HOUR = 3600000 +// 12:00 in Brasília (UTC-3); the Brasília day starts at 03:00Z. +const NOW = Date.UTC(2026, 10, 10, 15, 0, 0) +const DAY_END = Date.UTC(2026, 10, 11, 3, 0, 0) +const iso = (ms) => new Date(ms).toISOString() + +function hex (buf) { + return b4a.toString(buf, 'hex') +} + +function someKey () { + return hex(crypto.randomBytes(32)) +} + +async function prepared (records = []) { + const kp = generateAssociationKeyPair() + const keyPair = crypto.keyPair() + const storage = memoryNodeStorage() + const ctx = { storage, association: hex(kp.publicKey), keyPair } + const { publicKey } = await member.idCreate(ctx) + await member.certAdd(ctx, createCert({ member: publicKey }, kp)) + await appendRaw(ctx, records) + return { ctx, key: publicKey } +} + +async function appendRaw (ctx, records) { + for (let i = 0; i < records.length; i += 8) { + await member.withIdentity(ctx, ({ diary }) => store.appendRecords(diary, records.slice(i, i + 8))) + } +} + +async function rawOf (ctx) { + return member.withIdentity(ctx, ({ diary }) => store.readRaw(diary)) +} + +async function lengthOf (ctx) { + return (await rawOf(ctx)).length +} + +function liveOf (raw, type) { + const gone = deletedSeqs(raw) + return raw.filter((e) => !gone.has(e.seq) && e.record !== null && e.record.type === type).map((e) => e.seq) +} + +// Counts the records of every append (single or batch) and throws on the +// failAt-th batch append (from 1), 0 for never. +function spyAppends (t, failAt = 0) { + const one = store.appendRecord + const many = store.appendRecords + const sizes = [] + let batches = 0 + store.appendRecord = async (diary, record, limits) => { + sizes.push(1) + return one(diary, record, limits) + } + store.appendRecords = async (diary, records, limits) => { + sizes.push(records.length) + if (++batches === failAt) throw new Error('falha simulada') + return many(diary, records, limits) + } + t.teardown(() => { + store.appendRecord = one + store.appendRecords = many + }) + return sizes +} + +async function refusal (p) { + try { + await p + } catch (err) { + return err.message + } + return null +} + +const onFlag = (ms = NOW - 10 * HOUR) => gardenRecord({ on: true, at: iso(ms) }) +const help = (to, ms, pot = 0) => gardenHelpRecord({ to, pot, at: iso(ms) }) +const follow = (key, ms = NOW - 20 * HOUR) => followRecord({ key, on: true, at: iso(ms) }) +const plant = (pot, id = 'manjericao') => ({ op: 'plant', pot, plant: id }) + +// ---- gardenOwn ---- + +test('gardenOwn: a fresh diary, after the opt in and after a play', async (t) => { + const { ctx } = await prepared() + t.alike(await member.gardenOwn(ctx, NOW), { on: false, state: null, savesToday: 0, helpsToday: 0, given: [] }) + await member.gardenSet(ctx) + t.alike(await member.gardenOwn(ctx, NOW), { on: true, state: null, savesToday: 0, helpsToday: 0, given: [] }) + const r = await member.gardenPlay(ctx, { acts: [plant(0)], now: NOW, received: [] }) + const own = await member.gardenOwn(ctx, NOW) + t.is(own.on, true) + t.alike(own.state, r.state, 'the state as written') + t.is(own.state.n, 1) + t.is(own.savesToday, 1) +}) + +test('gardenOwn: savesToday resets at 03:00Z, n on the same Brasília day', async (t) => { + const { ctx } = await prepared([onFlag()]) + await member.gardenPlay(ctx, { acts: [plant(0)], now: DAY_END - 2 * HOUR, received: [] }) + await member.gardenPlay(ctx, { acts: [plant(1)], now: DAY_END - 1, received: [] }) + t.is((await member.gardenOwn(ctx, DAY_END - 1)).savesToday, 2, 'same day: n') + const next = await member.gardenOwn(ctx, DAY_END) + t.is(next.savesToday, 0, 'a new Brasília day') + t.is(next.state.n, 2, 'the state is still reported') + const r = await member.gardenPlay(ctx, { acts: [plant(2)], now: DAY_END, received: [] }) + t.is(r.state.n, 1, 'the first save of the new day') +}) + +test('gardenOwn: a future-dated state counts as today (its n)', async (t) => { + const pots = [null, null, null, null, null, null] + const { ctx } = await prepared([onFlag(), gardenStateRecord({ pots, n: 1, at: iso(NOW + 30 * HOUR) })]) + t.is((await member.gardenOwn(ctx, NOW)).savesToday, 1, 'counts as today') + const { ctx: ctx2 } = await prepared([onFlag(), gardenStateRecord({ pots, n: 6, at: iso(NOW + 30 * HOUR) })]) + t.is((await member.gardenOwn(ctx2, NOW)).savesToday, garden.GARDEN_SAVES_DAILY_MAX) +}) + +test('gardenOwn: helpsToday and given (window cut, newest seq first)', async (t) => { + const a = someKey() + const b = someKey() + const c = someKey() + const { ctx } = await prepared([ + onFlag(), + help(a, NOW - 73 * HOUR), + help(b, NOW - 71 * HOUR, 2), + help(c, NOW - HOUR, 5), + help(a, NOW + 2 * HOUR, 1) + ]) + const raw = await rawOf(ctx) + const seqs = liveOf(raw, 'garden-help') + const own = await member.gardenOwn(ctx, NOW) + t.is(own.helpsToday, 2, 'today and the future-dated one') + t.alike(own.given, [ + { seq: seqs[3], to: a, pot: 1, at: iso(NOW + 2 * HOUR) }, + { seq: seqs[2], to: c, pot: 5, at: iso(NOW - HOUR) }, + { seq: seqs[1], to: b, pot: 2, at: iso(NOW - 71 * HOUR) } + ]) +}) + +test('gardenOwn: given holds at most GARDEN_HELP_ROWS rows', async (t) => { + const records = [onFlag()] + for (let i = 0; i < garden.GARDEN_HELP_ROWS + 3; i++) records.push(help(someKey(), NOW - 30 * HOUR + i * 60000)) + const { ctx } = await prepared(records) + const own = await member.gardenOwn(ctx, NOW) + t.is(own.given.length, garden.GARDEN_HELP_ROWS) + t.ok(own.given[0].seq > own.given[1].seq, 'newest first') +}) + +// ---- gardenSet ---- + +test('gardenSet twice: the earlier flag tombstoned, one live flag', async (t) => { + const { ctx, key: me } = await prepared() + const first = await member.gardenSet(ctx) + const second = await member.gardenSet(ctx) + const raw = await rawOf(ctx) + t.alike(liveOf(raw, 'garden'), [second.seq]) + t.ok(deletedSeqs(raw).has(first.seq), 'the earlier flag is tombstoned') + t.is(second.ref, me + ':' + second.seq) +}) + +// ---- gardenPlay ---- + +test('gardenPlay: refused while the flag is off', async (t) => { + const { ctx } = await prepared() + const before = await lengthOf(ctx) + t.is(await refusal(member.gardenPlay(ctx, { acts: [plant(0)], now: NOW, received: [] })), member.GARDEN_OFF_PLAY) + await appendRaw(ctx, [gardenRecord({ on: false, at: iso(NOW - HOUR) })]) + const mid = await lengthOf(ctx) + t.is(await refusal(member.gardenPlay(ctx, { acts: [plant(0)], now: NOW, received: [] })), member.GARDEN_OFF_PLAY) + t.is(mid, before + 1) + t.is(await lengthOf(ctx), mid, 'nothing written') +}) + +test('gardenPlay: one session is one append, 1 block then 2 (tombstone + state)', async (t) => { + const { ctx } = await prepared([onFlag()]) + const sizes = spyAppends(t) + const r1 = await member.gardenPlay(ctx, { acts: [plant(0), plant(1, 'tomate'), plant(2, 'alecrim')], now: NOW, received: [] }) + t.alike(sizes, [1], 'the first state alone') + const r2 = await member.gardenPlay(ctx, { acts: [plant(3), plant(4), { op: 'clear', pot: 0 }], now: NOW + 60000, received: [] }) + t.alike(sizes, [1, 2], 'the previous state tombstone and the new state') + const raw = await rawOf(ctx) + t.alike(liveOf(raw, 'garden-state'), [r2.seq]) + t.ok(deletedSeqs(raw).has(r1.seq)) + t.is(r2.state.seq, r2.seq) + t.is(r2.state.n, 2) + t.is(r2.state.at, iso(NOW + 60000)) + t.is(r2.state.pots[0], null, 'cleared') + t.is(r2.state.pots[3].plant, 'manjericao') + t.is(validateRecord(raw[r2.seq].record, r2.seq), null, 'valid at its seq') + t.alike(raw[r2.seq].record.pots, r2.state.pots, 'state as written') +}) + +test('gardenPlay: one bad act refuses the whole batch, nothing written', async (t) => { + const { ctx } = await prepared([onFlag()]) + await member.gardenPlay(ctx, { acts: [plant(0)], now: NOW, received: [] }) + const before = await lengthOf(ctx) + t.is(await refusal(member.gardenPlay(ctx, { acts: [plant(1), plant(0)], now: NOW + 1000, received: [] })), member.GARDEN_BAD_PLAY, 'a full pot') + t.is(await refusal(member.gardenPlay(ctx, { acts: [plant(1), { op: 'water', pot: 0 }], now: NOW + 1000, received: [] })), member.GARDEN_BAD_PLAY, 'watered too recently') + t.is(await refusal(member.gardenPlay(ctx, { acts: [{ op: 'nope', pot: 1 }], now: NOW + 1000, received: [] })), member.GARDEN_BAD_PLAY, 'an unknown act') + t.is(await refusal(member.gardenPlay(ctx, { acts: 'x', now: NOW + 1000, received: [] })), member.GARDEN_BAD_PLAY, 'no list') + t.is(await lengthOf(ctx), before, 'nothing written') + t.is((await member.gardenOwn(ctx, NOW + 1000)).state.pots[1], null, 'pot 1 still empty') +}) + +test('gardenPlay: the 7th save of a Brasília day is refused', async (t) => { + const { ctx } = await prepared([onFlag()]) + for (let i = 0; i < garden.GARDEN_SAVES_DAILY_MAX; i++) { + const r = await member.gardenPlay(ctx, { acts: [plant(i)], now: NOW + i * 60000, received: [] }) + t.is(r.state.n, i + 1) + } + const before = await lengthOf(ctx) + t.is(await refusal(member.gardenPlay(ctx, { acts: [{ op: 'clear', pot: 0 }], now: NOW + HOUR, received: [] })), member.GARDEN_SAVES_FULL) + t.is(await lengthOf(ctx), before, 'nothing written') + t.is((await member.gardenOwn(ctx, NOW + HOUR)).savesToday, garden.GARDEN_SAVES_DAILY_MAX) +}) + +test('gardenPlay: planted at hour 0, watered at hour 3, harvested under the received bound', async (t) => { + const { ctx } = await prepared([onFlag()]) + await member.gardenPlay(ctx, { acts: [plant(0)], now: NOW, received: [] }) + const acts = [{ op: 'water', pot: 0 }, { op: 'harvest', pot: 0 }] + const before = await lengthOf(ctx) + t.is(await refusal(member.gardenPlay(ctx, { acts, now: NOW + 3 * HOUR, received: [] })), member.GARDEN_BAD_PLAY, 'not ripe without neighbours') + t.is(await lengthOf(ctx), before) + const received = Array(6).fill(garden.GARDEN_HELP_PER_POT) + const water = await member.gardenPlay(ctx, { acts: [{ op: 'water', pot: 0 }], now: NOW + 3 * HOUR, received }) + t.is(water.state.pots[0].w, 1, 'watered') + const raw = await rawOf(ctx) + t.is(validateRecord(raw[water.seq].record, water.seq), null, 'valid at its seq') + const harvest = await member.gardenPlay(ctx, { acts: [{ op: 'harvest', pot: 0 }], now: NOW + 3 * HOUR + 1000, received }) + t.is(harvest.state.pots[0], null, 'harvested') +}) + +// ---- gardenHelp and gardenHelpCheck ---- + +// Asserts both the check and the write refuse with `message`, writing nothing. +async function refusedBoth (t, ctx, args, message, label) { + const before = await lengthOf(ctx) + t.is(await refusal(member.gardenHelpCheck(ctx, args)), message, 'check: ' + label) + t.is(await refusal(member.gardenHelp(ctx, args)), message, 'help: ' + label) + t.is(await lengthOf(ctx), before, 'nothing written: ' + label) +} + +test('gardenHelp: self, writer mismatch and own flag off are refused', async (t) => { + const a = someKey() + const { ctx, key: me } = await prepared([follow(a)]) + await refusedBoth(t, ctx, { to: me, pot: 0, writer: me, now: NOW }, member.GARDEN_HELP_SELF, 'self') + await refusedBoth(t, ctx, { to: a, pot: 0, writer: someKey(), now: NOW }, store.LOCKED, 'writer mismatch') + await refusedBoth(t, ctx, { to: a, pot: 0, writer: me, now: NOW }, member.GARDEN_OFF_HELP, 'flag off') + await appendRaw(ctx, [gardenRecord({ on: false, at: iso(NOW - HOUR) })]) + await refusedBoth(t, ctx, { to: a, pot: 0, writer: me, now: NOW }, member.GARDEN_OFF_HELP, 'flag written off') +}) + +test('gardenHelp: only a followed balcony (a live follow block, not a queued op)', async (t) => { + const a = someKey() + const { ctx, key: me } = await prepared([onFlag()]) + const args = { to: a, pot: 3, writer: me, now: NOW } + await refusedBoth(t, ctx, args, member.GARDEN_NOT_FOLLOWING, 'no follow') + await member.followAdd(ctx, a) + t.ok((await store.readFollows(ctx.storage)).includes(a), 'kv follows has it') + await refusedBoth(t, ctx, args, member.GARDEN_NOT_FOLLOWING, 'queued follow only') + await appendRaw(ctx, [follow(a)]) + const before = await lengthOf(ctx) + t.is(await member.gardenHelpCheck(ctx, args), undefined, 'the check passes') + t.is(await lengthOf(ctx), before, 'the check wrote nothing') + const r = await member.gardenHelp(ctx, args) + const raw = await rawOf(ctx) + t.is(r.seq, before, 'one block') + t.is(r.ref, me + ':' + r.seq) + t.alike(raw[r.seq].record, { type: 'garden-help', to: a, pot: 3, at: iso(NOW) }) + t.is(validateRecord(raw[r.seq].record, r.seq), null, 'valid at its seq') +}) + +test('gardenHelp: once per balcony per Brasília day, at most five balconies', async (t) => { + const keys = Array.from({ length: 6 }, someKey) + const { ctx, key: me } = await prepared([onFlag(), ...keys.map((k) => follow(k))]) + await member.gardenHelp(ctx, { to: keys[0], pot: 0, writer: me, now: NOW }) + await refusedBoth(t, ctx, { to: keys[0], pot: 1, writer: me, now: NOW + HOUR }, member.GARDEN_SAME_DAY, 'same day') + for (let i = 1; i < 5; i++) await member.gardenHelp(ctx, { to: keys[i], pot: 0, writer: me, now: NOW + i * 60000 }) + t.is((await member.gardenOwn(ctx, NOW + HOUR)).helpsToday, 5) + await refusedBoth(t, ctx, { to: keys[5], pot: 0, writer: me, now: NOW + HOUR }, member.GARDEN_HELPS_FULL, 'a 6th balcony') + const next = await member.gardenHelp(ctx, { to: keys[0], pot: 0, writer: me, now: DAY_END }) + t.ok(next.seq > 0, 'a new Brasília day frees the budget') +}) + +test('gardenHelp: helps older than the window are tombstoned in the same append', async (t) => { + const a = someKey() + const b = someKey() + const old = Array.from({ length: 9 }, (_, i) => help(someKey(), NOW - 80 * HOUR + i * 60000)) + const { ctx, key: me } = await prepared([onFlag(), follow(a), follow(b), ...old, help(a, NOW - 10 * HOUR)]) + const raw0 = await rawOf(ctx) + const oldSeqs = liveOf(raw0, 'garden-help').slice(0, 9) + const recent = liveOf(raw0, 'garden-help')[9] + const sizes = spyAppends(t) + const r1 = await member.gardenHelp(ctx, { to: b, pot: 0, writer: me, now: NOW }) + t.alike(sizes, [8], 'one append: 7 tombstones and the help') + let raw = await rawOf(ctx) + const gone = deletedSeqs(raw) + t.alike(oldSeqs.filter((s) => gone.has(s)), oldSeqs.slice(0, 7), 'the oldest seven') + t.is(r1.seq, raw0.length + 7, 'the help is last') + t.is(raw[r1.seq].record.type, 'garden-help') + t.ok(!gone.has(recent), 'a help inside the window stays') + await member.gardenHelp(ctx, { to: a, pot: 0, writer: me, now: DAY_END + HOUR }) + t.alike(sizes, [8, 3], 'the two left, then the help') + raw = await rawOf(ctx) + t.alike(liveOf(raw, 'garden-help').filter((s) => oldSeqs.includes(s)), [], 'every old help gone') + t.ok(liveOf(raw, 'garden-help').includes(recent)) +}) + +// ---- gardenLeave ---- + +test('gardenLeave: tombstones every state and help, the off flag last', async (t) => { + const a = someKey() + const { ctx, key: me } = await prepared([follow(a)]) + await member.gardenSet(ctx) + await member.gardenPlay(ctx, { acts: [plant(0)], now: NOW, received: [] }) + await member.gardenHelp(ctx, { to: a, pot: 0, writer: me, now: NOW }) + await appendRaw(ctx, [help(someKey(), NOW - 2 * HOUR)]) + const r = await member.gardenLeave(ctx) + const raw = await rawOf(ctx) + t.is(r.seq, raw.length - 1, 'the flag is the last block') + t.is(r.ref, me + ':' + r.seq) + t.is(raw[r.seq].record.type, 'garden') + t.is(raw[r.seq].record.on, false) + t.alike(liveOf(raw, 'garden-state'), []) + t.alike(liveOf(raw, 'garden-help'), []) + t.alike(liveOf(raw, 'garden'), [r.seq]) + t.alike(await member.gardenOwn(ctx, NOW), { on: false, state: null, savesToday: 0, helpsToday: 0, given: [] }) + const before = raw.length + t.is(await member.gardenLeave(ctx), null, 'a second leave writes nothing') + t.is(await lengthOf(ctx), before) +}) + +test('gardenLeave: never opted in answers null', async (t) => { + const { ctx } = await prepared() + const before = await lengthOf(ctx) + t.is(await member.gardenLeave(ctx), null) + t.is(await lengthOf(ctx), before) +}) + +test('gardenLeave: cut short keeps the flag on, a repeat finishes', async (t) => { + const helps = Array.from({ length: 20 }, (_, i) => help(someKey(), NOW - 20 * HOUR + i * 60000)) + const { ctx } = await prepared([onFlag(), ...helps]) + const before = await lengthOf(ctx) + const sizes = spyAppends(t, 2) + let err = null + try { + await member.gardenLeave(ctx) + } catch (e) { + err = e + } + t.ok(err, 'fails') + t.is(err.written, before + 7, 'the first chunk landed') + t.alike(sizes, [8, 8]) + t.is((await member.gardenOwn(ctx, NOW)).on, true, 'still reads on') + t.is(liveOf(await rawOf(ctx), 'garden-help').length, 12) + const r = await member.gardenLeave(ctx) + t.alike(sizes, [8, 8, 8, 4, 2], 'the rest, then the flag with its tombstone') + const raw = await rawOf(ctx) + t.is(r.seq, raw.length - 1) + t.alike(liveOf(raw, 'garden-help'), []) + t.alike(liveOf(raw, 'garden-state'), []) + t.is((await member.gardenOwn(ctx, NOW)).on, false) +}) + +test('gardenLeave: a failed final flag carries the last tombstone as written', async (t) => { + const { ctx } = await prepared([onFlag(), help(someKey(), NOW - HOUR)]) + const before = await lengthOf(ctx) + const sizes = spyAppends(t, 1) + let err = null + try { + await member.gardenLeave(ctx) + } catch (e) { + err = e + } + t.alike(sizes, [1, 2], 'the tombstone, then the failed flag append') + t.ok(err, 'fails') + t.is(err.written, before, 'the tombstone landed') + t.is((await member.gardenOwn(ctx, NOW)).on, true, 'still reads on') +}) + +// ---- no text ---- + +test('no Varandinha record carries a text field', async (t) => { + const a = someKey() + const { ctx, key: me } = await prepared([follow(a), help(someKey(), NOW - 80 * HOUR)]) + const one = store.appendRecord + const many = store.appendRecords + const written = [] + store.appendRecord = (diary, record, limits) => { + written.push(record) + return one(diary, record, limits) + } + store.appendRecords = (diary, records, limits) => { + written.push(...records) + return many(diary, records, limits) + } + t.teardown(() => { + store.appendRecord = one + store.appendRecords = many + }) + await member.gardenSet(ctx) + await member.gardenPlay(ctx, { acts: [plant(0), plant(1)], now: NOW, received: [] }) + await member.gardenHelp(ctx, { to: a, pot: 1, writer: me, now: NOW }) + await member.gardenLeave(ctx) + t.alike([...new Set(written.map((r) => r.type))].sort(), ['delete', 'garden', 'garden-help', 'garden-state']) + for (const r of written) t.absent('text' in r, r.type + ' has no text') +}) + +test('gardenTargetSeqs: the peek list, or null to fail closed', (t) => { + t.alike(member.gardenTargetSeqs({ on: null, state: null }), [1, 2]) + t.alike(member.gardenTargetSeqs({ on: 9, state: 5 }), [1, 2, 5, 9], 'ascending') + t.alike(member.gardenTargetSeqs({ on: 2, state: 2 }), [1, 2], 'deduplicated') + for (const index of [null, 'x', 7, { on: 3, state: 4, indexing: true }, { on: 0, state: null }, { on: 1.5, state: null }, { on: null, state: '4' }, { on: 3 }]) { + t.is(member.gardenTargetSeqs(index), null, JSON.stringify(index)) + } +}) + +test('gardenTargetVerdict: every evidence path', (t) => { + const ON = 3 + const STATE = 5 + const flag = (over = {}) => ({ seq: ON, record: { type: 'garden', on: true, at: iso(NOW - HOUR), ...over } }) + const pot = (plant, ms) => ({ plant, at: iso(ms), water: iso(ms), w: 0 }) + const pots = [pot('tomate', NOW - 2 * HOUR), null, pot('manjericao', NOW - 7 * HOUR), null, null, null] + const state = (over = {}) => ({ seq: STATE, record: { type: 'garden-state', pots, n: 1, at: iso(NOW - HOUR), ...over } }) + const person = [{ seq: 1, record: { type: 'profile' } }, { seq: 2, record: { type: 'follow' } }] + const peek = (entries, missing = [], length = 10) => ({ entries: [...person, ...entries], missing, length }) + const index = { on: ON, state: STATE } + const verdict = (ix, r, p = 0, now = NOW) => member.gardenTargetVerdict(ix, r, p, now) + + t.is(verdict(index, peek([flag(), state()])), null, 'a growing pot of an opted-in member') + t.is(verdict(index, { entries: [{ seq: 1, record: { type: 'page-roster' } }, flag(), state()], missing: [], length: 10 }), 'page') + t.is(verdict(index, { entries: [person[0], flag(), state()], missing: [2], length: 10 }), 'unavailable', 'block 2 unread') + t.is(verdict(index, { entries: [person[0], flag(), state()], missing: [2], length: 2 }), null, 'block 2 past the end') + t.is(verdict({ on: null, state: null }, peek([])), 'off', 'no flag pointer') + t.is(verdict(index, peek([state()], [ON])), 'unavailable', 'flag pointer to a missing block') + t.is(verdict(index, peek([{ seq: ON, record: { type: 'mood' } }, state()])), 'unavailable', 'flag pointer to another type') + t.is(verdict(index, peek([flag({ on: false }), state()])), 'off', 'flag off') + t.is(verdict(index, peek([flag({ at: iso(NOW + 25 * HOUR) }), state()])), 'off', 'flag dated past MAX_FUTURE') + t.is(verdict(index, peek([flag({ at: iso(NOW + 23 * HOUR) }), state()])), null, 'flag inside MAX_FUTURE') + t.is(verdict({ on: ON, state: null }, peek([flag()])), 'no-plant', 'no state pointer') + t.is(verdict({ on: ON, state: 2 }, peek([flag()])), 'unavailable', 'stale state below the flag') + t.is(verdict(index, peek([flag()], [STATE])), 'unavailable', 'state pointer to a missing block') + t.is(verdict(index, peek([flag(), { seq: STATE, record: { type: 'garden', on: true } }])), 'unavailable', 'state pointer to another type') + t.is(verdict(index, peek([flag(), state({ pots: 'x' })])), 'unavailable', 'state without pots') + t.is(verdict(index, peek([flag(), state({ at: iso(NOW + 25 * HOUR) })])), 'no-plant', 'state dated past MAX_FUTURE') + t.is(verdict(index, peek([flag(), state()]), 1), 'no-plant', 'empty pot') + t.is(verdict(index, peek([flag(), state()]), 2), 'no-plant', 'ripe pot') + t.is(verdict(index, peek([flag(), state({ pots: [pot('tomate', NOW + HOUR), null, null, null, null, null], at: iso(NOW + HOUR) })])), 'no-plant', 'planted after the clock') +})