diff --git a/README.md b/README.md index 129fa18..98c036d 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ That answers with a relay at a memorable name, open to anyone for 14 days. Claim - **A community.** Members, invite links, an invite tree, moderators with a log of what they did, a signed roster and one NIP-29 group per relay, so group-aware clients show it as a place. - **A site.** Notes and articles as pages with link previews, an Atom feed, and a card with a QR of the group address. NIP-5A also serves root, named and snapshot websites from signed manifests on isolated hostnames, with verified files, optional mirroring and sign-in that follows the relay's read rule. - **Encrypted group transport.** Opt-in Marmot KeyPackages and opaque MLS group messages, with account admission and storage caps for ephemeral authors. Clients manage encryption and group membership. -- **A Git host.** Opt-in GRASP-01 Smart HTTP, backed by [ntig](https://github.com/FelineStateMachine/ntig). Signed NIP-34 state authorizes branch and tag changes; events wait for their Git objects before publication. Hosting has [explicit storage and transaction limits](docs/22-grasp-01-git-hosting.md#git-http). +- **A Git host.** Opt-in GRASP-01 Smart HTTP, backed by [ntig](https://github.com/FelineStateMachine/ntig). Signed NIP-34 state authorizes branch and tag changes; events wait for their Git objects before publication. Hosting has [explicit storage and transaction limits](docs/22-grasp-01-git-hosting.md#git-http), and the owner can request a bounded read-only inventory without authorizing deletion. - **A file host.** Blossom and NIP-96 on the same bucket, with mirroring, pre-flight checks and file reports. - **A console.** Nine tabs on the relay's own page, signed by a browser extension or a remote signer app on a phone. Presets set up an outbox, an inbox, a private relay, a chat, a search replica, a media host or a quiet relay with every costly feature off, in one click. The template collection also includes static sites, public or member-published Marmot transport and Git repositories. - **A file.** Everything the console sets, as one document with a schema: check it offline, see what applying would change, apply it, pull it back. Keep your relay in your repository. The presets are the same files, in `relay-templates/`. @@ -46,7 +46,7 @@ Site hosting and mirroring are on by default; Marmot and GRASP are off until ena **For scripts and agents** -- [Scripts and agents](docs/13-scripts-and-agents.md): a relay end to end with a key and curl, every management method, and the relay as a configuration file. +- [Scripts and agents](docs/13-scripts-and-agents.md): a relay end to end with a key and curl, every management method including Git storage inventory, and the relay as a configuration file. - [HTTP reference](docs/14-http-reference.md): every path, method, auth and answer. **For developers** @@ -55,7 +55,7 @@ Site hosting and mirroring are on by default; Marmot and GRASP are off until ena - [Hosting bind.ws](docs/11-hosting-bindws.md): run your own on your own domain, and watch it through logs, traces and metrics. - [Hosting without Cloudflare](docs/16-hosting-without-cloudflare.md): the same Worker on celld, with your own bucket and proxy, and what "supported" promises. - [Develop and extend](docs/12-develop-extend.md): layout, tests, adding methods and NIPs, the console, the templates. -- [Costs and margins](docs/15-costs-and-margins.md): tenant meters, host accounting gaps, margin scenarios and the proposed maintenance budget contract. +- [Costs and margins](docs/15-costs-and-margins.md): application budgets, retained storage, inventory interpretation and deployment margins. ### Draft NIPs diff --git a/docs/10-architecture.md b/docs/10-architecture.md index ba70c86..05ca90f 100644 --- a/docs/10-architecture.md +++ b/docs/10-architecture.md @@ -163,6 +163,33 @@ accepted state as its authorization boundary and passes Git objects through the object-store seam. It stays separate from the NIP-5A site door, so a site hostname cannot reach relay events or repository data. +`repository-access.ts` gives one live Durable Object operation the repository +authority token across awaits. Git HTTP, owner controls, alarms, event +ingestion and direct lease, adoption and teardown paths use the same admission +seam; nested work owned by the active token proceeds, while another live +operation receives a retry response. Async context carries the token, so the +fence replaces separate Git and control flags without becoming a durable lock. +Management reads and verifies the request before taking ownership, so an +incomplete unauthenticated body cannot hold the relay's admission token. +It does not coordinate a crashed instance, another R2 client or another object +using the prefix, and it never authorizes garbage collection. + +`git-storage.ts` implements the owner-only `gitstorage` management method. It +walks one accepted repository's physical R2 objects within explicit budgets, +compares them with the live dependency inventory and reports physical, live, +unreferenced and unknown objects by class alongside SQL reservations and their +difference from listed bytes. An incomplete, over-budget or changed-root walk +returns an error and no partial report. The manual scan has a 60-second +per-instance cooldown and does not delete or reclaim storage. + +[Tangled knots](https://docs.tangled.org/knot-self-hosting-guide) provide +useful prior art: AT Protocol identity sits above a filesystem Git host with +repository maintenance. Bindws instead publishes immutable objects through +an R2 root. The storage layout and recovery contract determine which old +objects can be reclaimed; decentralized identity does not require retaining +every superseded manifest. A collection protocol still needs to protect old +readers, unpublished writes and retained transaction receipts. + ## Views `src/views.ts` is a registry of folds. Each view names a trigger, an audience and a fold that returns tags and content; hourly views add a fingerprint so nothing is republished when the inputs did not move. The record is a kind 30078 signed by the identity key on the same strictly increasing clock as the group state, `d` = `bind.ws/view/`, stored and broadcast through `emit` like the roster, taken down when the view is switched off, empty, or no longer public. The rows a run wrote are measured around the fold from the store's write counter and kept as the last 60 runs, which the console and the digest read. diff --git a/docs/13-scripts-and-agents.md b/docs/13-scripts-and-agents.md index 1862c8e..2ee67ac 100644 --- a/docs/13-scripts-and-agents.md +++ b/docs/13-scripts-and-agents.md @@ -67,6 +67,7 @@ await rpc("claim"); // { result: { owner, claimed: true, c await rpc("applypreset", "outbox"); // one call sets writes, reads, kinds and keep-for await rpc("backfill", ["wss://relay.damus.io", "wss://nos.lol"]); console.log(await rpc("listjobs")); +console.log(await rpc("gitstorage", "", "my-project")); ``` The bridge takes the same header. `POST /events` answers `{ event_id, accepted, message }`; `POST /query` answers a list of events; `POST /count` answers `{ count }`. The bridge is rate limited per address at four times the per-connection allowance and answers `429` past it. @@ -137,6 +138,7 @@ The bridge takes the same header. `POST /events` answers `{ event_id, accepted, **Storage** - `storagestats`: bytes by kind, files, retention. +- `gitstorage owner identifier`: an owner-only inventory of one accepted GRASP repository. The result compares bounded physical R2 listing with live Git dependencies and reports physical, live, unreferenced and unknown objects by class, SQL reservations and the byte difference. It never deletes data. - `deleteblob sha256`. - `listdumps`, `dumpnow`, `deletedump name`. @@ -164,6 +166,10 @@ The bridge takes the same header. `POST /events` answers `{ event_id, accepted, - `deleterelay name`: the relay's own name, typed, is the confirmation. +`gitstorage` is a diagnostic read, not a billing ledger or a deletion grant. +Its operation counts do not add a tenant charge, and its 60-second cooldown is +per live Durable Object instance, so eviction or restart resets it. + ## The configuration file `exportconfig` is a document, and a document can live in a repository. The format is `bind.ws/relay-config/2`: `policy`, `members`, `bans`, `addresses`, `banned_events`, `kinds` and `retention`, each a section, and a section the file leaves out is left alone when it is applied, so a file may carry the rules and nothing about people. The schema is at `https://bind.ws/relay-config.schema.json`; put it in `$schema` and the editor checks the file as you type. JSONC is fine: comments and trailing commas. diff --git a/docs/14-http-reference.md b/docs/14-http-reference.md index 11093d7..3539f2e 100644 --- a/docs/14-http-reference.md +++ b/docs/14-http-reference.md @@ -25,7 +25,7 @@ Any request with `Accept: application/nostr+json` answers the NIP-11 document, w |---|---|---|---|---| | `/` | GET | none | the console, one page for visitors and owner alike | 200 | | `/` | GET with `Accept: application/nostr+json` | none | NIP-11: rules, limits, retention, `self`, `lease` while leased, `succession_pending` while warning | 200 | -| `/` | POST, `content-type: application/nostr+json+rpc` | NIP-98 | NIP-86 management, `{ result }` or `{ error }` | 200; 400 invalid; 401 bad signature; 403 not allowed; 409 conflict | +| `/` | POST, `content-type: application/nostr+json+rpc` | NIP-98 | NIP-86 management, `{ result }` or `{ error }` | 200; 400 invalid; 401 bad signature; 403 not allowed; 409 conflict; 429 active relay operation | | `/people` | GET | none | `{ public, self, host, people }`, the members when the directory is public | 200 | | `/terms` | GET | none | the join terms as a page | 200; 404 none set | | `/signer.js` | GET | none | the NIP-46 client bundle, cached a week | 200 | @@ -97,6 +97,22 @@ unmatched refs are hidden and scheduled for deletion, but immutable Git objects remain in retained storage. The 128-transaction ceiling can prevent physical cleanup; it does not make those bytes free. +The owner can inspect one accepted repository through the NIP-86 +`gitstorage` method at the relay root. It performs a bounded, read-only walk +of the physical R2 prefix and compares it with the live Git dependency set. +The result reports physical, live, unreferenced and unknown objects by class, +SQL reservations and `reservationMinusListedBytes`, together with operation +counts for diagnostics, limits and capture time. These counts are not tenant +billing meters. Unreferenced does not authorize deletion: +there is no collector or automatic storage reclamation. A complete report is +required, so a changed root or any inventory budget exhaustion returns an +error instead of partial data. The method has a 60-second per-instance +cooldown; a Durable Object restart or eviction resets that cooldown. + +| Method | Parameters | Auth | Answers | Status | +|---|---|---|---|---| +| `gitstorage` | repository owner hex pubkey, identifier | NIP-98, owner with the storage action | bounded physical and live inventory, reservations and limits | 200; 400 invalid parameters; 403 inactive, fuel or role; 404 feature or repository unavailable; 413 inventory limit; 429 cooldown or another repository operation; 503 storage unavailable | + ## Custom domains These NIP-86 methods are owner-only and use the relay's normal NIP-98 RPC diff --git a/docs/15-costs-and-margins.md b/docs/15-costs-and-margins.md index 24f42e3..1cb239f 100644 --- a/docs/15-costs-and-margins.md +++ b/docs/15-costs-and-margins.md @@ -5,348 +5,163 @@ audience: developer # Costs and margins -What a relay costs the host, what fuel charges for it, and how to keep the two apart as the bitcoin price moves. The numbers come from one script: +How applications budget a tenant's relay usage, interpret fuel meters and +control storage growth. Fuel prices the relay's measured resources; hosting +expenses determine the service's margins. The two serve different purposes. +[Understanding fuel](02-understanding-fuel.md) covers allowances and top-ups +for relay owners. -``` -npm run margin # today's price -npm run margin -- --btc 60000 # a price you pick -npm run margin -- --relays 5000 # the deployment at that size -``` - -It prints markdown and exits with code 1 when any priced line is under the target margin. A GitHub Actions workflow runs it every Monday, puts the tables in the run summary and opens or refreshes one issue when a line is under target. - -## The model - -Fuel prices four resource lines: SQLite event storage, R2 media storage, -Durable Object duration and rows written. Each fuel price is a sats figure in -`wrangler.jsonc`. Each Cloudflare price is a dollar figure on their pricing -pages, copied into the script with the date it was checked. The bitcoin price -joins the two. - -The four lines are the tenant-facing budget, not a complete provider invoice. -The relay records stored event bytes, stored media bytes, its awake-time -counter and rows written by its SQLite work. GRASP objects share the media -storage allowance with Blossom files and dumps; NIP-5A mirroring does the same. -Marmot events share event storage and ordinary row accounting. Site proxy and -Git request bytes are visible traffic with no fuel price, and tenant usage does -not gain a separate feature surcharge. - -Some provider costs remain outside the four tenant-priced lines. R2 operations, KV reads and -writes, and platform requests can be billed by operation even when the relay -only exposes bytes. The row meter drains cursors recorded by `Store.x`; direct SQL bookkeeping -in GRASP, site queues and other modules bypasses it. The awake-time meter -uses entrypoint gaps capped at ten seconds, so a long Git or remote-fetch -operation is not measured as an exact request duration. -Those costs belong in the host's deployment review and margin target; they do -not silently change the four meters shown to a relay owner. - -For a line with cost `c` dollars per unit and price `p` sats per unit at `B` dollars per bitcoin, revenue per unit is `p / 1e8 * B` and margin is `1 - c / revenue`. The script defaults to a 33% margin on revenue, which prices a line at about 1.493x cost. The floor is 20%. Under the target the weekly run flags it; under the floor, review pricing. +## Budget from the relay's meters -Because prices are in sats and costs in dollars, margins move with the exchange rate on their own. A rising bitcoin widens them. A falling one narrows them, and the script prints, for each line, the bitcoin price under which the target no longer holds and the price under which the floor breaks. +`GET /fuel` returns current usage, allowances, rates and balance without +authentication. The Health tab shows the same information. Applications read +these values from the relay instead of hard-coding the public service's +prices, since another deployment can set different rates and allowances. -## The lines, checked Sept. 3, 2026 - -At $81,500 per bitcoin: - -| Line | Cloudflare | Fuel | Margin | Target holds above | -|---|---|---|---|---| -| Events stored | $0.20 per GB-month | 400 sats | 39% | $74,600 | -| Files stored | $0.015 per GB-month | 30 sats | 39% | $74,600 | -| Time awake | $0.0058 per hour | 11 sats | 36% | $78,200 | -| Rows written | $1.00 per million | 2,000 sats | 39% | $74,600 | - -Time awake is an hour of a Durable Object held in memory at 128 MB, which Cloudflare bills as 460.8 GB-seconds. Hibernating objects incur no duration charge, but retained storage and alarm work can still cost the host. - -## The free tier - -At the dated rates above, a relay that spends its whole allowance costs the host about $0.86 a month. Time awake is most of it. Storage is nearly free at these sizes. The rows allowance was a million until Sept. 2026, which made it $1.00 of a $1.61 tier; it came down to 250,000, about 15 times what a personal relay writes, because rows are the one line Cloudflare charges real money per unit. - -| Allowance | Amount | Cost | +| Fuel line | Usage and allowance fields | What the meter includes | |---|---|---| -| Events stored | 100 MB | $0.02 | -| Files stored | 1 GB | $0.015 | -| Time awake | 100 hours | $0.58 | -| Rows written | 250,000 | $0.25 | - -Few relays get near the allowance. At the dated rates above, a typical personal relay, 20 MB of events, 100 MB of files, eight hours awake and 100,000 rows a month, costs about 15 cents once the plan's included quotas are used up, and those quotas cover the first few dozen relays outright. - -## The deployment - -The script projects a fleet from two illustrative shapes, a typical relay and a heavy one that passes its allowances and pays fuel, at a chosen share of heavy relays. These are assumptions, not measured customer workloads or a validated provider bill. The fleet projection includes platform requests, rows read and R2 operations as host costs even though these have no separate tenant price. Worker CPU, logs, traces, Analytics Engine, site-index KV operations, custom-hostname fees, payment fees and support still need deployment measurements or separate budgets. - -The free tier is a cost the paid relays and the host share. Unpriced operations consume part of the margin on paid usage. A target on four priced lines alone does not establish a fleet margin after free users and shared costs. - -The bounded GRASP implementation adds a relay-wide ceiling of 320 MiB for -retained Git objects, with 4 MiB packs, 16 MiB packed history and bounded -transaction, ref and object counts. This is a safety limit and shares the -existing media allowance; it is not a new free tier. Retained bytes can remain -billable after expired metadata is hidden when immutable Git history or a -cleanup transaction still keeps them. - -The current [R2 pricing](https://developers.cloudflare.com/r2/pricing/), -[Durable Object pricing](https://developers.cloudflare.com/durable-objects/platform/pricing/) -and [KV pricing](https://developers.cloudflare.com/kv/platform/pricing/) -distinguish storage, execution and operation charges. The historical fleet -shapes below the script's pricing tables are not measured site or Git workloads. -Use deployment telemetry before treating their projected margin as coverage -for these features. - -## Weekly - -The workflow is `.github/workflows/margin.yml`. Read the summary. When a line is flagged: - -1. Run the script locally to see the suggested prices for the target at today's rate. -2. Change the `SATS_PER_*` values in `wrangler.jsonc`. The comment above them records the rate they were set at; update it. -3. Deploy. Fuel meters are unchanged; only the price of what is over the allowance moves, from the next charge. - -Prices go up when bitcoin falls. When it rises, do nothing until a line has sat above twice the target for a month, then bring it down. Relay owners see prices on the front page and on their Fuel section, so every change is visible the moment it deploys. The table above was checked on Sept. 3, 2026; rerun `npm run margin` and verify current provider pricing before using it for a new forecast. - -## Accounting coverage, checked Sept. 4, 2026 - -The following inventory describes the host with ntig 0.2.1 and unmigrated -format-1 repositories. Installing the library does not migrate roots. Observing an -expense does not authorize a new customer charge. `/fuel` and the Health tab -expose aggregate tenant meters, not every operation the host pays for. - -| Dimension | Existing source and persistence | Coverage limit | +| Events stored | `eventBytes`, `freeEventBytes` | Allocated SQLite storage, including relay metadata as well as events | +| Files stored | `mediaBytes`, `freeMediaBytes` | Uploaded files, dumps, imports, mirrored site files and reserved Git storage | +| Time awake | `activeMs`, `freeActiveMs` | An estimate from relay entrypoints, including client requests, jobs and alarms | +| Rows written | `rowsWritten`, `freeRowsWritten` | Writes counted by the relay's event store | + +`rates` gives storage prices in sats per GB-month, awake time in sats per +hour and writes in sats per million rows. Balance and credited or charged +amounts use millisatoshis: `balanceMsats / 1000` is the balance in sats. +Storage above its allowance is charged daily, pro rata. Awake time and rows +use the usage accumulated in `month` against their monthly allowances. + +`bytesIn`, `bytesOut` and `rowsRead` are diagnostics with no fuel price. +A request can still increase awake time or stored data even when its traffic +is unpriced. Sites, Marmot and Git share the existing allowances; enabling a +feature creates neither a separate allowance nor a request surcharge. + +The meters describe application accounting, not a complete provider bill. +Awake time is estimated from entrypoint gaps capped at ten seconds, rather +than timing each job to completion. Direct SQL bookkeeping outside the event +store is not included in the row meter. Usage is flushed in batches, so it is +not a durable record of every request. Applications use the reported balance +and `outOfFuel` for admission status rather than reconstructing charges from +traffic, event counts or wall-clock timings. + +## How features consume the budget + +| Workload | Resource use | Application choice | |---|---|---| -| Usage and credits | [Fuel](../src/fuel.ts), monthly SQLite usage and unique receipt IDs | Counters become durable only after a flush; receipts prevent duplicate credit | -| SQLite storage | `Relay.eventBytes`, the database's allocated size | Includes tables beyond events; daily charging uses the current size, not a continuous storage integral | -| R2 storage | `Relay.mediaBytes`, blobs + dumps + imports + `grasp_objects` | Shared allowance; retained history and conservative reservations can outlive visible refs | -| Awake time | `Relay.touch`, in-memory ten-second entrypoint gaps | No handler completion timing; long async work, idle gaps and restart estimates differ from provider duration | -| SQL rows | [Store](../src/store.ts), cursors from `Store.x`, then `Relay.tally` | Direct SQL in settings, GRASP, sites, media and other modules bypasses the meter; DO key-value and alarm work is not covered | -| Traffic | `Relay.meterBytes` and socket counters, then monthly usage | No fuel price; socket string lengths and attempted/produced HTTP bytes are not exact delivered wire bytes | -| Requests | [Worker routing](../src/index.ts), HTTP, RPC, sockets and alarms | No durable per-tenant request ledger; application REQ counters are not platform request counts | -| R2 operations | [Git object wrapper](../src/grasp.ts), [Blossom](../src/blossom.ts), [site mirrors](../src/site-mirror.ts) and dumps | No durable per-tenant Class A/B ledger; observer callbacks are best-effort evidence | -| Jobs and alarms | [Jobs](../src/jobs.ts) and `Relay.alarm` | Required cleanup, mirrors and retries consume host work; no optional maintenance budget exists | -| KV and external services | [Host routing](../src/edge.ts), [site index](../src/sites.ts), notifications and provider fetches | No tenant operation meter for reads, writes, misses, retries or external fees | -| Observability | `Relay.flushUsage`, console deltas and optional Analytics Engine | Logs, traces and analytics are expense and diagnosis sources, not the durable fuel ledger | - -[Relay](../src/relay.ts) batches usage in memory. A restart can lose an -unflushed batch. `flushUsage` resets counters before `Fuel.record`; a failed -record can therefore lose that batch too. Its final `Store.drain` discards -pending cursors, so a direct flush without `tally` can omit rows. Usage is -assigned to the month of the flush rather than split across the work's month -boundary. These are accounting gaps, not grounds for reconstructing charges -against old tenant balances. - -Git reserves the larger retained object size in SQLite before PUT. Success -reconciles the size; a definite CAS loss uses HEAD to reconcile it. An -exception leaves the reservation because the write may have succeeded. No -automatic reconciliation queue or orphan collector exists. Counting PUT -bytes again as stored bytes would double-charge existing media accounting. -Future temporary packs also need reservations while both copies exist. - -For an explicitly migrated format-2 repository, ref advertisements read two -R2 objects, the root and manifest. This saves legacy history and pack reads -on that path; full loads and Git transfers still read all stored packs. -Each new commit also retains a manifest and receipt-index path nodes beside -its record and optional pack. Ref-only workloads can pass 128 transactions, -but their metadata and reservation rows continue to grow. All of these keys -use the same pre-PUT storage reservation. CAS-loser objects remain accounted -for, and an ambiguous PUT can leave a reservation larger than physical -storage. Neither receipt lookup nor checkpointing reclaims old bytes. -Operation counts are host costs, not a new tenant charge; lower read costs -alone do not establish a margin after metadata writes and retained storage. - -Git HTTP requests reuse up to 2 MiB and 512 entries of immutable payload in a -session that ends with the request. Repeated validation and promotion can -reuse those bytes, while mutable roots and all writes still reach R2 and -its accounting adapter. New requests start fresh, oversized objects bypass -the cache, and Git validation still runs. Lower R2 read counts do not imply -lower CPU cost or a complete request-memory bound. Bulk initial checkpoint -construction avoids writing intermediate receipt-index nodes; it removes -no stored data and does not start migration automatically. - -The isolated checkpoint fixture separates physical storage from the objects -referenced by the current format. Both workloads use one 214-byte Git pack, -260 transactions and an explicit checkpoint after transaction 128. One keeps -updating the same ref to the same commit; the other retains 259 new tags. -These are local measurements with ntig 0.2.1, not production usage or a -per-repository minimum. - -| Retained Git payload | One fixed ref | Growing tags | -|---|---:|---:| -| Pack | 214 bytes | 214 bytes | -| Current root and manifest | 430 bytes | 16,888 bytes | -| All 260 retry records and current receipt index | 136,165 bytes | 126,982 bytes | -| Current-format total | 136,809 bytes | 144,084 bytes | -| Superseded manifests | 42,900 bytes | 1,671,120 bytes | -| Superseded receipt-index nodes | 332,722 bytes | 332,722 bytes | -| Physical objects and reserved bytes | 512,431 bytes | 2,147,926 bytes | - -The ledger equals the paginated R2 inventory for every key and size in these -quiet fixtures: there is no reservation slack. Each untouched fixture -has no Git R2 keys; its first commit uses 631 bytes in three keys. SQLite -allocation, provider operations and execution are separate quantities. -The larger growing-tag total comes mainly from retained copies of earlier -ref maps. Its current manifest is only 16,783 bytes. Fixed-ref transaction -records are larger because their updates include an old object ID. - -All historical retry records remain required by the current retention -contract. Current-format membership includes every pack in the manifest; -it does not establish that every object inside those packs is reachable -from today's refs. Superseded metadata is outside the latest root's -dependency set, but older readers and in-flight publishers can still need -it. This inventory supplies no online deletion authority. No collector or -storage saving is deployed, and these bytes still count toward tenant file -usage. Coordinated metadata collection is the larger target in this fixture; -changing receipt retention would change retry semantics. - -`npm test -- test/object/grasp-checkpoint.test.ts --reporter=verbose --disableConsoleIntercept` -reproduces the inventory, current-format traversal, all historical receipt -lookups and unchanged root checks. The measurements apply to healthy, -quiescent fixtures; ambiguous writes can still leave reservation slack. - -`graspBusy`, `graspControls` and the job round's `working` flag fence work -within a live instance. Async handlers can interleave across awaits. Those -flags are admission controls, not persisted crash recovery or authority to -delete data. Repository CAS and persisted authority remain necessary. - -The coordination tests pause actual Git HTTP and alarm requests at an R2 -root read. Competing Git requests return 429 without reading R2. While HTTP -holds `graspBusy`, signed event writes and HTTP management are refused and -an alarm defers its storage work. While an alarm holds `graspControls`, a -signed repository-state event still enters purgatory. This is intentional -evidence of a narrower admission fence, not proof of exclusive maintenance. -That event changes SQL authority without an R2 operation in the paused -fixture; it does not demonstrate an existing Git publication or data-loss bug. -Both successful and failed R2 reads release their flags. Consuming the -completed HTTP response performs no more R2 reads in this fixture. - -| Entry point | Existing coordination | Limit before collection | -|---|---|---| -| Git advertisement, fetch and push | `grasp` sets `graspBusy` before its first await and rejects either occupied flag | Live-instance admission only; no persisted reader lease | -| Accepted state and promotion | Run inside the HTTP fence or alarm controls; promotion rechecks candidates after reads | An immutable read session caches bytes but acquires no lock | -| Non-GET HTTP management | `Relay.fetch` holds `graspControls` while the route runs and refuses `graspBusy` | Other controls and event writes can still interleave | -| Signed events, imports and pulls | `acceptAny` or `writeGate` refuses `graspBusy` | `graspControls` alone does not refuse event writes | -| Alarm, PR expiry and pending promotion | Alarm defers during `graspBusy`, otherwise holds `graspControls` | Alarm entry does not refuse an already active control operation | -| Whole-relay deletion | Management or lease-expiry alarm calls `teardown` | Teardown has no internal lock and deletes the whole slug prefix; it is not a metadata collector | -| Direct repository helper calls | Production callers are the HTTP handler and `graspTick` | `gitRepository` and `checkpoint()` acquire no host fence themselves; test calls bypass admission | - -The current HTTP handler constructs its response bytes before the read -session closes. A future streaming path would need to preserve coordination -until its last storage read. None of these in-memory flags coordinates an -independent R2 client, another object ID sharing a prefix, or recovery after -the owning instance is replaced. CAS protects root publication, but does not -prevent deletion of an object that a reader or unpublished writer still -needs. Removing a repository announcement also leaves its WAL and quota -rows behind; visibility is not a storage-liveness test. - -Before metadata collection, a complete inventory needs explicit object, -byte and operation budgets and must refuse an incomplete mark. The host -also needs a proven ownership and recovery protocol covering active -readers, unpublished writes, administrative deletion and maintenance. -Budget exhaustion, missing or corrupt dependencies and changed roots must -prevent a deletion decision. Stable before/after roots alone are insufficient: -a reader may hold an older root, or a publisher may have uploaded objects -without publishing its new root yet. This remains a collection blocker; -the tests introduce no collector or runtime coordination change. - -`npm test -- test/object/grasp-coordination.test.ts` reproduces the paused -HTTP/alarm checks. The checkpoint inventory above remains an isolated, -quiescent fixture rather than an online maintenance API. - -Provider request accounting separates HTTP/RPC/alarm invocations from -incoming WebSocket messages, which have a 20:1 billing ratio. Socket frames -do not become Worker requests. DO duration counts overlapping work once per -object; idle objects eligible for hibernation have no duration charge. -DO key-value operations and alarm writes also consume SQLite rows. Included -allocations and billing-unit rounding apply at account level. -See [Durable Object pricing](https://developers.cloudflare.com/durable-objects/platform/pricing/). +| Events and Marmot messages | Event storage and database writes; encrypted envelopes still occupy space | Restrict admitted writers and set retention for kinds that do not need permanent history | +| Blossom files, dumps and imports | File storage alongside database metadata | Bound uploads and remove stored copies that are no longer needed | +| Sites | Manifests occupy event storage; mirrored files occupy file storage; remote fetches and mirrors wake the relay | Reuse unchanged files and choose whether the relay mirrors remote content | +| Git | Packs, transaction receipts and retained metadata occupy file storage; clone, fetch and push wake the relay | Budget for repository history and ref updates, not just the checked-out files | +| Pulls, backfills and scheduled dumps | Jobs wake the relay and can add events, rows and files without a connected client | Use once-only jobs for one-time transfers and remove recurring jobs that no longer serve the application | + +[Relay templates](../relay-templates/README.md) provide starting policies. +[Data and names](04-data-and-names.md) describes retention, dumps and jobs. +Feature limits still apply below the fuel allowance: a positive balance does +not increase a maximum upload size, Git transaction limit or repository cap. +The limits and admission rules are in +[GRASP-01 Git hosting](22-grasp-01-git-hosting.md) and +[HTTP reference](14-http-reference.md). + +## Account for retained Git storage + +Git storage has no fixed reservation per repository. It grows with packs, +transaction receipts and metadata, including ref-only updates. Removing a +branch, hiding an announcement or expiring a PR does not remove its immutable +history. Retained objects continue to count toward file usage and the relay's +Git storage cap. There is no automatic Git garbage collector. + +A reservation records bytes before an object write. A confirmed result +reconciles the size; an uncertain result keeps the reservation because the +write may have succeeded. The reservation total can therefore exceed the +physical objects currently listed. It is not a second charge on top of those +objects. Repository format upgrades also retain history; they are not a way +to reclaim storage. + +The relay owner can inspect one hosted repository with the `gitstorage` +management method. It takes the repository owner's hex public key and the +repository identifier. The repository owner can differ from the relay owner. +[Scripts and agents](13-scripts-and-agents.md) describes signing the call; +[HTTP reference](14-http-reference.md) defines its responses. + +| Report field | Interpretation | +|---|---| +| `inventory.listed` | Physical objects found in the repository's storage namespace | +| `inventory.live` | Objects referenced by the captured storage root, including retained receipts and packs; not a reachability check of every Git object inside a pack | +| `inventory.unreferenced` | Recognized objects outside that root's dependency set; older readers or unpublished writes can still need them | +| `inventory.unknown` | Listed keys the inventory cannot classify | +| `reservations` | The repository's quota reservations, included in file usage | + +`reservationMinusListedBytes` compares the reservation and physical byte +totals. A difference is a diagnostic, not proof that particular reservations +can be removed. Neither `live` nor `unreferenced` grants deletion authority. +The report changes no stored objects, reservations or fuel rates. + +Inventory is a manual diagnostic, not a health poll. It reads storage and +holds the relay's admission owner while it runs, so competing Git requests +and mutations receive a retry response. Server limits bound reads and listing +work; an incomplete scan returns an error instead of partial totals. The +60-second cooldown limits repeated scans in a live instance and resets when +that instance restarts. It is not a recommended polling interval. + +`operations` and `inventory.observed` describe the scan's requests and read +bytes. They help explain the work a scan performs, but are not tenant billing +meters or a complete hosting cost. Existing activity and storage accounting +still applies; there is no separate inventory fee. + +## Handle limits without multiplying work + +A client checks the response reason before retrying. A transient admission +refusal can clear; a storage or repository limit requires a change in the +workload or available budget. + +| Condition | Client behavior | +|---|---| +| `outOfFuel` | Show the relay's allowance and balance; stop repeated writes until the budget permits them | +| Busy relay or rate limit (`429`) | Honor `Retry-After` or the response's `retryAfter` when supplied, and back off | +| Upload or repository limit | Keep the rejected operation visible to the user; a top-up does not raise a hard limit | +| Incomplete inventory | Keep the last complete report labelled with its capture time; an error does not mean zero usage or free storage | -R2 Standard includes pooled storage and operation allowances. Beyond them, -storage is $0.015/GB-month, Class A operations $4.50/million and Class B -$0.36/million, with billing-unit rounding. Free egress does not remove those -operation costs. See [R2 pricing](https://developers.cloudflare.com/r2/pricing/). -[Workers pricing](https://developers.cloudflare.com/workers/platform/pricing/), -[KV pricing](https://developers.cloudflare.com/kv/platform/pricing/) and -[Cloudflare for SaaS plans](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/plans/) -cover other host expenses. These sources were checked on Sept. 4, 2026. +Fuel exhaustion does not delete data. Ordinary reads remain available under +the read policy, but Git requests and remote site fetches also require fuel. +Already stored site files remain readable under their access rules. Client +interfaces distinguish these cases instead of treating every refusal as a +network error. -## A 40% margin scenario +## Margins for deployments -This is a planning target; the deployed rates, allowances and weekly default -remain unchanged. A 40% gross margin means `price = cost / 0.60`, or about -1.667x cost. Multiplying cost by 1.40 produces only a 28.57% margin. +For developers hosting the service, `npm run margin` compares configured fuel +rates with provider costs. It reads `wrangler.jsonc`, uses the provider rates +recorded in the script and either fetches a bitcoin price or accepts an +explicit scenario: ``` -npm run margin -- --btc 60000 --target 0.40 -npm run margin -- --btc 80000 --target 0.40 -npm run margin -- --btc 100000 --target 0.40 +npm run margin +npm run margin -- --btc 60000 +npm run margin -- --btc 60000 --target 0.40 --relays 5000 ``` -These are Sept. 4 planning scenarios, not bitcoin spot quotes. At the -current sats rates, before free users and other expenses: - -| BTC scenario | Events, files and rows margin | Awake margin | -|---|---|---| -| $60,000 | 16.67% | 12.73% | -| $80,000 | 37.50% | 34.55% | -| $100,000 | 50.00% | 47.64% | - -The 40% threshold is about $83,333/BTC for events, files and rows, and -$87,273/BTC for awake time at $0.00576 per provider hour. The script already -uses gross margin; its existing 33% default was never a 40% markup formula. - -For a whole deployment, the planning condition is -`revenue >= (provider bill + shared operating costs + subsidy) / 0.60`. -The subsidy is only free-user cost not already included in the provider bill; -counting it twice overstates expense. Provider allocations are pooled once, -including other services on the account, rather than granted anew per relay. - -An illustrative personal relay consumes about $0.152 of the four resource -lines at marginal list rates: 20 MB events, 100 MB files, eight provider hours -and 100,000 written rows. A relay consuming all current allowances reaches -about $0.861 before other costs and account rounding. Actual duration and row -usage must come from provider evidence because the tenant meters are partial. - -Storage-light workloads can still be expensive. One million Class A and ten -million Class B operations beyond the pooled allocation cost $8.10 even if -they repeatedly access only a few kilobytes. Across 100 such relays that is -$810 before duration, requests or rows; storage revenue alone cannot cover it. -A fleet forecast therefore needs active tenant share, utilization, operation -mix, cache misses, retries and concentration in its busiest tenants, alongside -FX and payment-fee sensitivity. The script's two shapes do not establish this -distribution. - -## What can be bundled - -These are proposed operating boundaries, not new allowances or charges. - -| Work | Proposed treatment | -|---|---| -| Bounded metadata and health reads during ordinary use | Bundled with request and abuse caps; no separate tiny surcharge | -| Service-caused retries and ambiguous-write reconciliation | Host operating budget; record attempts and expense without charging a second logical operation | -| Existing retained data | Existing storage meter, including reserved and temporary bytes; no second Git storage charge | -| Free tenants | Explicit monthly fleet subsidy budget with utilization and heavy-tail review | -| High-volume scans, repeated cold clones and uncached site fetches | Bounded work and request quotas; operation-heavy use cannot be treated as unlimited because bytes are unpriced | -| Optional optimization | Tenant-visible budget and deferral; extra wake-ups require opt-in | - -## Proposed maintenance contract - -ntig 0.2.1 has no resumable optimization runner. No maintenance job, budget -setting, wake schedule, format migration or garbage collection is enabled by -this contract. Existing ref cleanup, retention and alarms keep their current -roles. An eventual integration has these boundaries: - -| Stage | Host and backend contract | -|---|---| -| Eligibility | Cheap stored statistics identify pack/read amplification, reclaimable bytes or a limit approaching; no daily full scan or unconditional repack | -| Admission | Optional work starts only while the tenant is already active by default; foreground requests take priority before each bounded step | -| Reservation | A durable job ID and UTC budget month reserve bounded work, operation counts and temporary retained bytes before execution | -| Execution | A resumable cursor, bounded I/O and a cooperative deadline limit each step; a timer alone cannot preempt arbitrary work safely | -| Completion | Persist outcome and actual expense once per step; stable attempt IDs separate retries from completed logical work | -| Recovery | A crash or ambiguous write keeps its reservation until reconciliation; CAS and persisted authority protect state across restarts | -| Scheduling | Extra wakes require opt-in, a monthly budget and an allowed window; later window, manual run and pause are separate choices | -| Exhaustion | Optional work defers; a write that cannot safely fit a hard limit fails clearly without discarding protected data | -| Retention | Optimization never authorizes deleting retained history; reachability, readers and retention rules need a separate proof | - -Host expense accounting stays separate from tenant charge calculation. A -future duration observer measures the union of registered work intervals, -including long steps, without claiming it is the provider's entire active -lifetime. Its validation covers overlap, mid-step flush, month boundaries, -crash before and after persistence, retries, reservation exhaustion and -foreground arrival. The host contract also needs tests for ambiguous PUT, -temporary copies, authority changes and paused scheduling before it runs -against customer data. +The explicit bitcoin prices are scenario inputs, not quotes. For cost `c` +dollars per unit, price `p` sats per unit and bitcoin price `B` dollars, +revenue is `p * B / 100000000` and gross margin is `1 - c / revenue`. +A target margin `m` requires `price = cost / (1 - m)` in the same currency. +The script defaults to a 33% target and a 20% floor. It exits with code 1 when +a priced line falls below target; the weekly workflow records the result and +opens or refreshes an issue. + +Per-line margins do not establish a deployment margin. Provider allowances +are shared across the account, while tenants receive the relay allowances. +Free usage, R2 operations, platform requests, CPU, KV, observability and payment +costs also consume the service's revenue. A small stored dataset can generate +many reads or writes. The script's fleet shapes are illustrative assumptions; +actual workload mix and provider usage determine whether revenue covers the +deployment. + +Provider prices and included allocations are documented under +[Workers pricing](https://developers.cloudflare.com/workers/platform/pricing/), +[Durable Object pricing](https://developers.cloudflare.com/durable-objects/platform/pricing/), +[R2 pricing](https://developers.cloudflare.com/r2/pricing/) and +[KV pricing](https://developers.cloudflare.com/kv/platform/pricing/). +[Hosting bind.ws](11-hosting-bindws.md) describes deployment configuration. +Running the margin script changes no tenant rates; a rate change requires a +configuration change and deployment, and appears in the relay's `/fuel` +response. diff --git a/docs/22-grasp-01-git-hosting.md b/docs/22-grasp-01-git-hosting.md index 870c222..56c19fc 100644 --- a/docs/22-grasp-01-git-hosting.md +++ b/docs/22-grasp-01-git-hosting.md @@ -103,6 +103,8 @@ the broader archive or sync behavior of later GRASP documents. Your relay's **Connect** section includes a copyable `git clone` example with its own hostname, the repository owner's npub and repository name. +It also links to [GitWorkshop](https://gitworkshop.dev/) with a copyable relay +URL. Both Git connections stay hidden when Git hosting is unavailable. The Git door is unauthenticated when the relay's reads are open. It serves Git Smart HTTP at the repository path and returns a repository page or a 404 @@ -130,7 +132,7 @@ The hard limits are: | Format 1 | 128 transactions | legacy WAL replay | | Format 2 | 128 unique packs, 2 MiB manifest | explicitly migrated repository metadata | -ntig 0.2.1 reads both formats, but installing it leaves existing roots alone +ntig 0.3.0 reads both formats, but installing it leaves existing roots alone and new repositories still use format 1. Bindws exposes no checkpoint action or scheduled migration. The backend's explicit `checkpoint()` upgrade is one-way: every reader and writer must support format 2 before an isolated @@ -158,6 +160,20 @@ rechecks authority. The session closes on return or error. This bounds the cache, not total request memory, and does not skip Git validation or pending promotion. +The owner can request `gitstorage ` through +the management API to compare physical Git objects with quota reservations. +The report breaks storage down by object class and distinguishes current-root +references, unreferenced objects and unknown keys. Unreferenced bytes are not +safe-to-delete bytes: readers and unpublished writes can still need them. +The scan does not change roots, reservations or stored objects. + +Scans run manually with fixed read limits and a 60-second cooldown per live +relay instance. A restart resets that cooldown. A limit, corrupt dependency or +changed root returns an error rather than a partial report. Git requests, +event writes and configuration changes receive a retry response while a scan +owns the relay. See [HTTP reference](14-http-reference.md) for the method and +[Costs and margins](15-costs-and-margins.md) for its host costs and limits. + ## Information document and limits When GRASP is on and reads are open, NIP-11 includes: diff --git a/package-lock.json b/package-lock.json index 701cb31..c0b78f2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,7 @@ "dependencies": { "@noble/hashes": "^2.4.0", "nostr-tools": "^2.25.1", - "ntig": "file:vendor/ntig-0.2.1.tgz" + "ntig": "file:vendor/ntig-0.3.0.tgz" }, "devDependencies": { "@cloudflare/vitest-pool-workers": "^0.22.0", @@ -2852,9 +2852,9 @@ "license": "MIT" }, "node_modules/ntig": { - "version": "0.2.1", - "resolved": "file:vendor/ntig-0.2.1.tgz", - "integrity": "sha512-PcXiSReGSJJ87q0Nb71DQnzzd5RB+8YNkmYDE2XEWQQxblwuWJHx8cD0M0ser460sxPC4PPMKrkbIrZHKySFeA==", + "version": "0.3.0", + "resolved": "file:vendor/ntig-0.3.0.tgz", + "integrity": "sha512-lO3Y+sv+pTL1q/k8KJK9iRB7rNu1MUe9jGaUeAjTzxQu7f64XWjbEQqXlePe3Ivvlrb2lnkXDdQxUFgP5z2P0g==", "license": "MIT", "dependencies": { "@scure/base": "2.4.0", diff --git a/package.json b/package.json index b99d777..157973a 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "dependencies": { "@noble/hashes": "^2.4.0", "nostr-tools": "^2.25.1", - "ntig": "file:vendor/ntig-0.2.1.tgz" + "ntig": "file:vendor/ntig-0.3.0.tgz" }, "devDependencies": { "@cloudflare/vitest-pool-workers": "^0.22.0", diff --git a/src/console/console.js b/src/console/console.js index 9e46a28..b65e714 100644 --- a/src/console/console.js +++ b/src/console/console.js @@ -227,6 +227,7 @@ const clone = "git clone '" + location.origin + "//.git'"; $("#git-clone").textContent = clone; $("#git-copy").dataset.copytext = clone; + renderApps(); } async function loadFuel() { @@ -1025,6 +1026,11 @@ row("Nostur", "iPhone, Mac", profileNote + " Then Settings, Relays.", [nprofile && app("Open in app", "nostr:" + nprofile), copy("Copy relay URL", wsURL)]), ]], ]; + if (info?.supported_grasps?.includes("GRASP-01")) groups.push([ + "Git repositories", "Use this relay with a Git client.", [ + row("GitWorkshop", "web", "Browse and collaborate on Git repositories.", [link("Open", "https://gitworkshop.dev/"), copy("Copy relay URL", wsURL)]), + ], + ]); el.innerHTML = groups.map(([h, note, rows]) => '

' + h + '

' + note + '

' + rows.join("") + "
").join(""); $("#apps-ws").textContent = wsURL; const tile = (label, text) => '
' + label + 'QR code: ' + esc(label) + '
'; diff --git a/src/gates.ts b/src/gates.ts index d4f471e..39f9017 100644 --- a/src/gates.ts +++ b/src/gates.ts @@ -17,7 +17,7 @@ import { marmotPrincipal, marmotShape } from "./marmot.ts"; // writeGate is what every write must pass, whoever sends it: shape, bans, the // relay's state, fuel, and the one-group rule. "" lets it through. export function writeGate(relay: Relay, e: Event, conn: ConnState | null, t: number): string { - if (relay.graspBusy) return "restricted: Git transaction in progress; retry the event"; + if (relay.repositoryAccess.blocked) return "restricted: relay operation in progress; retry the event"; const graspError = graspGate(relay, e, conn?.host ?? ""); if (graspError) return graspError; const siteError = checkSite(e); diff --git a/src/gen/console.ts b/src/gen/console.ts index 7564c0c..af10f43 100644 --- a/src/gen/console.ts +++ b/src/gen/console.ts @@ -1,4 +1,4 @@ // Generated by scripts/build/build-console.mjs from src/console. Do not edit; run npm run build:console. export const CONSOLE_HTML = "
\n
\n
\"\"
\n
\"\"

\n
\n
\n \n \n \n \n \n \n
\n
\n\n
\n

Nobody owns this relay yet.

\n

Claim it and it's yours: you decide who can post, who can read, and what stays. One signature with a nostr browser extension; no account, no email, no card.

\n
\n
\n\n
\n

A temporary relay, for now.

\n

Anyone can read and write here until . Then everything on it is deleted and the name is freed. Claim it and it stays, events and files included: one signature with a nostr browser extension. Or claim a new name and pull this one into it from its Storage tab.

\n
\n
\n\n
\n

Connect a remote signer.

\n

Your key stays in a signer app such as Amber or nsec.app; this page asks it to sign. On a phone, open the link and approve there. On a computer, paste the bunker:// URL the app gives you.

\n \n
\n \"QR\n

\n
\n\n
\n
\n

\n

\n
\n
About, for clients
\n
Connect\n
\n
nostr relay
\n
Blossom media
\n
names
\n
HTTP bridge, NIP-98
POST /events, /query, /count
\n
\n
\n

Git repositories, ntig

\n
\n

Use ordinary Git to clone a repository hosted here.

\n
Clone a repository
\n

Replace <npub> with the repository owner's npub, yours for your own repository, and <repo> with its repository name, such as my-project.

\n

To host your own, use a Nostr Git client to publish your repository and signed branch state to this relay before pushing to the same remote. Git hosting guide.

\n
\n
\n
\n

Open it in an app

\n

Relay apps open this relay as a place. Feed apps do not: they find the owner here through a profile link that carries this relay as the hint, and learn the relay from that. Either way, add under the app's relay settings to post here.

\n
\n
\n
\n
\n
\n\n
\n

People

\n

Hidden from visitors. Only you see this list.

\n
\n
\n\n
\n

Fuel

\n

Free allowance first; past it, usage burns sats. Anyone can zap a top-up.

\n
\n
Events stored
\n
Files stored
\n
Awake this month
\n
Rows written this month
\n
\n

\n
sats
\n
\n

Pay from any lightning wallet. The receipt lands on this relay and credits it automatically.

\n \n \n
\n
\n\n
\n

Your invites

\n

The owner lets members bring people in. Each link admits one person and lasts three days.

\n
\n
    \n
    \n\n\n
    \n \n\n
    \n

    People

    \n

    The member list is published as a signed roster; a name makes someone .

    \n
    \n
    \n
    WhoNameNoteLimitsJoined
    \n
    \n
    \n
    \n
    \n

    Invites

    \n
    \n
      \n
      members invitehops deep,each
      \n
      \n
      \n

      Joining

      \n
      \n
      \n \n \n
      \n
      \n
      \n
      \n
      \n
      \n
      \n\n
      \n

      Moderation

      \n

      Reports never show in the feed. Banning also deletes the reported thing.

      \n
      \n

      Reports

      \n
      hide an event oncedifferent people report it; 0 never
      \n
      TimeTypeAboutReason
      \n
      \n
      \n

      Log

      \n

      Every change made here or by a moderation event, newest first, the last 5,000.

      \n
      TimeWhoActionTargetDetail
      \n \n
      \n
      \n
      \n

      Bans

      \n
      \n
        \n
          \n
          \n
          \n

          Blocked addresses

          \n
          \n
            \n
            \n
            \n
            \n

            Recent events

            \n

            Delete removes one thing. Ban also refuses it forever. Search covers notes, articles and profiles.

            \n
            \n
            TimeKindAuthorContent
            \n
            \n
            \n
            \n

            Pinned

            \n

            Group clients show these at the top. Up to 20, in this order.

            \n
            \n
              \n
              \n
              \n\n
              \n

              Rules

              \n

              Bans apply regardless of these.

              \n
              \n

              Presets

              \n

              One click sets writes, reads, kinds and keep-for together. Limits, identity and people stay.

              \n
              \n
              Replica presets keep a standing pull of their kinds from this relay.
              \n

              \n
              \n
              \n
              \n

              Writes

              \n \n \n \n \n
              \n

              Reads

              \n \n \n \n
              \n
              \n
              \n \n \n
              \n
              \n \n \n \n \n \n \n \n \n
              \n
              \n
              \n
              \n

              Kinds

              \n

              An empty allow list means every kind. Blocks always win.

              \n
              \n

              Allowed:

              \n

              Blocked:

              \n
              \n
              \n

              Features

              \n

              Each is a door or a cost. Off leaves the NIP-11 list, answers 404 at its door and is refused at the socket.

              \n
              \n
              \n
              \n

              Blocked words

              \n

              Content containing one is refused. You and your moderators are exempt. An entry written /like this/ is a regular expression.

              \n
              \n
              \n
              \n\n
              \n

              Identity

              \n
              \n

              Profile

              \n
              \n \n \n \n \n \n
              \n

              For directories

              \n
              \n \n \n \n \n \n
              \n
              \n
              \n
              \n

              Your own domain

              \n

              Your hostname serves this relay or one of its sites once its CNAME resolves and its certificate is issued.

              \n
              \n
              \n

              \n
              \n
              \n

              Your relay lists

              \n

              Clients find your relays through these lists. Add this relay to each so they use it. What is already listed stays.

              \n
              \n
              \n
              \n

              Share

              \n

              A card for links and profiles, and the group address that group-aware clients open. Both are public and refresh every five minutes.

              \n
              \n \"relay\n
              \n \"QR\n \n
              \n
              \n
              \n
              \n
              \n\n
              \n

              Data

              \n

              Keep-for rules run once a day. Purges happen now and cannot be undone.

              \n
              \n
              \n
              \n

              By kind

              \n
              KindCountSizeOldestKeep for
              \n
              \n
              \n

              Files

              \n
              TimeFileSizeUploader
              \n
              \n
              \n

              Sites

              \n

              Published NIP-5A manifests and the hostnames where they are served.

              \n
              AuthorNameURLFilesSizeExpiry
              \n
              \n
              \n

              Dumps

              \n

              Every event as one JSONL file on a schedule, kept for a few runs and counted as files. Downloads need your signature.

              \n
              \n
                \n
                \n
                \n

                Import a file

                \n

                A JSONL of events, one per line, such as a dump or a strfry export, or a JSON array. Up to 64 MB. Signatures are checked; bans and kind rules apply; the write rule does not. Progress shows under Jobs.

                \n
                \n
                \n
                \n\n
                \n

                Sync

                \n

                Events in and out, one round at a time, while the relay sleeps between rounds. Jobs spend awake time, which fuel counts.

                \n
                \n

                Jobs

                \n

                Work the relay does on its own, one round at a time. A pull copies what another relay has and this one lacks. Fetch my history pulls your own events from the relays in your relay list. Rebroadcast sends what is here to other relays. Bans and kind rules apply to what arrives.

                \n
                JobRelaysFilterScheduleResult
                \n
                \n
                \n
                \n
                \n \n \n \n \n
                \n
                \n
                \n
                \n
                \n

                Fork this relay

                \n

                A new name, temporary until claimed, filled from this relay. Yours to split a name by job, or somebody else's to hand them a community with its history. One fork an hour.

                \n
                \n
                \n \n \n \n \n \n
                \n
                \n
                \n

                \n
                \n
                \n
                \n\n
                \n

                Views

                \n

                Records the relay computes and signs, for clients and for anyone. Each run costs the rows it writes.

                \n
                \n
                \n
                \n
                \n\n
                \n

                Health

                \n
                \n
                –since last event
                \n
                –connected nowwebsockets open
                \n
                –fuel
                \n
                used for, last 30 days
                \n
                \n
                \n
                \n

                Zaps received

                \n
                WhenFromSats
                \n
                \n
                \n

                Notifications

                \n

                The relay writes you a private message (NIP-17) with its own key. It lands here, in your inbox on your own relay, and on your DM relays when this relay holds your kind 10050.

                \n
                \n
                \n \n \n \n \n \n
                \n
                \n
                \n
                \n
                \n\n
                \n

                Owner

                \n

                The relay's key, events, files and fuel stay put through everything here except delete.

                \n
                \n

                Configuration

                \n

                Rules, identity, members, bans, address blocks and kind rules as a file. Importing replaces those lists; it never touches events, files, or the owner.

                \n
                \n
                \n
                \n

                Transfer ownership

                \n

                Hands the relay to a member. You stay on as a moderator. The relay's key, events, files and fuel do not change. There is no undo.

                \n
                \n
                \n
                \n

                If I lose my key

                \n

                Name a member as your heir. If you do not sign in here for the time you pick, the relay writes to you once a week for a month, then hands itself to the heir and keeps you on as a moderator. Any signed action on the relay resets the clock.

                \n
                \n
                \n \n \n
                \n
                \n
                \n

                \n
                \n
                \n

                Delete this relay

                \n

                Deletes every event, file, member, invite and setting, closes every connection, and returns the name to unclaimed for anyone to take. There is no undo.

                \n \n
                \n
                \n
                \n\n \n
                \n"; export const CONSOLE_CSS = "main { max-width: 64rem; }\n.mast { display: grid; grid-template-columns: 1fr auto; gap: 1.5rem 2rem; align-items: end; margin-bottom: 2rem; }\n.mast .wordmark { grid-column: 1 / -1; justify-self: center; margin-bottom: .5rem; }\n.mast .right { display: grid; gap: .7rem; justify-items: end; text-align: right; }\n.urlrow, .owner { display: inline-flex; align-items: center; gap: .4rem; color: var(--ink-2); }\n.owner b { color: var(--ink); } .owner em { font-style: normal; color: var(--forest); }\n.urlrow .ib, .owner .ib { width: 26px; height: 26px; margin-left: .2rem; box-shadow: 1px 1px 0 var(--ink); } .urlrow .ib svg, .owner .ib svg { width: 13px; height: 13px; }\n.care { display: flex; gap: .9rem; flex-wrap: wrap; }\n.care .g { display: grid; justify-items: center; gap: .3rem; width: 5.4rem; }\n.care .g i { display: grid; place-items: center; width: 44px; height: 44px; border: 2px solid var(--ink); border-radius: 10px; background: var(--paper); box-shadow: 2px 2px 0 var(--ink); position: relative; }\n.care .g i svg { width: 22px; height: 22px; fill: none; stroke: currentColor; stroke-width: 2.4; stroke-linecap: round; stroke-linejoin: round; }\n.care .g.off i::after { content: \"\"; position: absolute; width: 3px; height: 40px; background: var(--ink); transform: rotate(45deg); border-radius: 2px; box-shadow: 0 0 0 2px var(--paper); }\n.care .g small { font: 500 10px/1.2 var(--mono); text-transform: uppercase; letter-spacing: .04em; color: var(--ink-2); text-align: center; }\n#unclaimed { background: var(--butter); }\n.doors { display: grid; grid-template-columns: repeat(4, 1fr); gap: .8rem; } @media (max-width: 52rem) { .doors { grid-template-columns: 1fr 1fr; } } @media (max-width: 30rem) { .doors { grid-template-columns: 1fr; } }\n.door { display: grid; grid-template-rows: auto 1fr; align-content: start; gap: .35rem; padding: .8rem .9rem; border: 2px solid var(--ink); border-radius: 12px; background: var(--paper); box-shadow: 3px 3px 0 var(--ink); min-width: 0; }\n.apps { display: grid; gap: 1.4rem; margin-top: 1rem; } .appgroup h4 { margin: 0 0 .2rem; font-size: 1rem; } .appgroup > .note { margin-top: 0; }\n.appgrid { display: grid; grid-template-columns: repeat(3, 1fr); gap: .8rem; } @media (max-width: 52rem) { .appgrid { grid-template-columns: 1fr 1fr; } } @media (max-width: 30rem) { .appgrid { grid-template-columns: 1fr; } }\n.app { display: grid; align-content: start; gap: .4rem; padding: .8rem .9rem; border: 2px solid var(--ink); border-radius: 12px; background: var(--paper); box-shadow: 3px 3px 0 var(--ink); min-width: 0; }\n.app-head { display: flex; align-items: baseline; gap: .5rem; flex-wrap: wrap; } .app-head b { font-size: 15px; } .app-head small { color: var(--ink-3); } .app p { margin: 0; font-size: 13px; color: var(--ink-2); }\n.app-acts { display: flex; flex-wrap: wrap; gap: .4rem; margin-top: .2rem; } .app-acts .btn { padding: .3rem .7rem; font-size: 13px; }\n.phones { display: grid; grid-template-columns: repeat(auto-fit, minmax(11rem, max-content)); gap: .8rem; margin-top: 1rem; } .phones img { display: block; width: 150px; height: 150px; } .phones .door { justify-items: start; }\n.door small { font: 700 11px var(--sans); text-transform: uppercase; letter-spacing: .06em; color: var(--ink-2); }\n.door .v { display: grid; grid-template-columns: 1fr auto; align-items: start; gap: .5rem; font: 500 13px/1.45 var(--mono); } .door .v span { min-width: 0; overflow-wrap: anywhere; }\n.door .ib { width: 24px; height: 24px; box-shadow: 1px 1px 0 var(--ink); flex: 0 0 auto; } .door .ib svg { width: 12px; height: 12px; }\n#peoplesec { background: var(--peach); }\n.dir { display: flex; flex-wrap: wrap; gap: .5rem; }\n.who { display: inline-flex; align-items: center; gap: .1rem; padding: .3rem .7rem .3rem .4rem; border: 2px solid var(--ink); border-radius: 999px; background: var(--paper); box-shadow: 2px 2px 0 var(--ink); font-size: 14px; }\n.who .role { font: 700 10px var(--mono); text-transform: uppercase; letter-spacing: .05em; color: var(--forest); margin-left: .4rem; }\n.who.me { background: var(--sun); }\n#fuelsec { background: var(--mint); }\n.gauges { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }\n.gauge small { display: block; font-weight: 600; font-size: 13px; }\n.gauge .bar { position: relative; height: 22px; border: 2px solid var(--ink); border-radius: 999px; margin: .5rem 0 .35rem; overflow: hidden; padding: 3px; background: var(--paper) linear-gradient(90deg, transparent calc(25% - 1px), var(--line) calc(25% - 1px) 25%, transparent 25% calc(50% - 1px), var(--line) calc(50% - 1px) 50%, transparent 50% calc(75% - 1px), var(--line) calc(75% - 1px) 75%, transparent 75%); }\n.gauge .bar b { position: absolute; right: .6rem; top: 0; bottom: 0; display: flex; align-items: center; font: 600 11px var(--mono); color: var(--ink-3); pointer-events: none; }\n.gauge .bar i { display: block; height: 100%; width: 0; min-width: 14px; border-radius: 999px; background: repeating-linear-gradient(-45deg, var(--forest) 0 8px, var(--forest-2) 8px 16px); transition: width .4s; }\n.gauge .bar i.warm { background: repeating-linear-gradient(-45deg, #d9a52a 0 8px, var(--sun) 8px 16px); }\n.gauge .bar i.over { background: repeating-linear-gradient(-45deg, var(--red) 0 8px, #d4614c 8px 16px); }\n.gauge span { font-size: 13px; color: var(--ink-3); }\n.balance { margin: 1.2rem 0 0; color: var(--ink-2); } .balance b { color: var(--ink); font-weight: 700; }\n.sats { display: inline-flex; align-items: center; width: auto; } .sats input { font: 15px var(--sans); width: 6rem; text-align: right; border: 0; outline: none; padding: 0; background: transparent; color: var(--ink); } .sats span { color: var(--ink-3); padding-left: .4rem; }\n.topup { display: flex; align-items: center; gap: .6rem; flex-wrap: wrap; margin-top: .8rem; }\n.invoice { margin-top: 1rem; border: 2px dashed var(--ink); border-radius: 12px; padding: .9rem 1rem; background: var(--paper); }\n.invoice p { margin: 0 0 .6rem; color: var(--ink-2); font-size: 14px; } .invoice .state { font-size: 13px; color: var(--forest); }\n.invoice textarea { margin-top: .7rem; min-height: 3.4rem; font-family: var(--mono); font-size: 11.5px; color: var(--ink-3); }\ndetails.disclosure summary { cursor: pointer; font: 400 1.6rem/1 var(--display); list-style: none; display: flex; align-items: center; gap: .5rem; }\ndetails.disclosure summary::-webkit-details-marker { display: none; }\n.folds details + details, .folds #frontsec:not(.hidden) + details { border-top: 2px solid var(--line); margin-top: 1.2rem; padding-top: 1.2rem; } .folds #frontsec .metarow { margin-bottom: 0; } .folds .doors { margin-top: 1rem; } .folds > details > .block:first-of-type { margin-top: 1.4rem; }\ndetails.disclosure summary::before { content: \"+\"; font: 700 1.4rem var(--mono); width: 1.4rem; } details.disclosure[open] summary::before { content: \"–\"; }\n.about { display: grid; grid-template-columns: repeat(auto-fill, minmax(11rem, 1fr)); gap: .6rem 1.2rem; margin-top: 1rem; font-size: 14px; }\n.about small { display: block; color: var(--ink-3); font-size: 12px; } .about div > div { overflow-wrap: anywhere; }\n.console { margin-top: 3rem; }\n.tabs { display: flex; gap: .45rem; flex-wrap: nowrap; align-items: flex-end; margin: 0 0 -2px 1rem; padding: 2px 3rem 2px 0; overflow-x: auto; overflow-y: hidden; scrollbar-width: none; }\n.tabs.fade-r { -webkit-mask-image: linear-gradient(90deg, #000 calc(100% - 2.5rem), transparent); mask-image: linear-gradient(90deg, #000 calc(100% - 2.5rem), transparent); }\n.tabs.fade-l { -webkit-mask-image: linear-gradient(90deg, transparent, #000 2.5rem); mask-image: linear-gradient(90deg, transparent, #000 2.5rem); }\n.tabs.fade-l.fade-r { -webkit-mask-image: linear-gradient(90deg, transparent, #000 2.5rem, #000 calc(100% - 2.5rem), transparent); mask-image: linear-gradient(90deg, transparent, #000 2.5rem, #000 calc(100% - 2.5rem), transparent); } .tabs::-webkit-scrollbar { display: none; } .tabs a { flex: 0 0 auto; white-space: nowrap; }\n.tabs a { font: 600 14px var(--sans); padding: .55rem 1rem; border: 2px solid var(--ink); border-bottom: 0; border-radius: 12px 12px 0 0; background: var(--head); color: var(--ink-2); text-decoration: none; margin-bottom: -2px; position: relative; z-index: 1; }\n.tabs a.on { color: var(--ink); z-index: 3; padding-top: .7rem; } .tabs a.on:nth-child(4n+1) { background: var(--sun); } .tabs a.on:nth-child(4n+2) { background: var(--peach); } .tabs a.on:nth-child(4n+3) { background: var(--sky); } .tabs a.on:nth-child(4n+4) { background: var(--mint); }\n.count { display: inline-grid; place-items: center; min-width: 1.5em; height: 1.5em; padding: 0 .4em; margin-left: .45rem; border: 1.5px solid var(--ink); border-radius: 999px; background: var(--sun); color: var(--ink); font: 700 11px/1 var(--mono); vertical-align: middle; box-shadow: 1px 1px 0 var(--ink); } .count:empty { display: none; } h2 .count { font-size: 12px; vertical-align: .45em; }\n.panel { display: none; margin: 0; border-radius: 0 18px 18px 18px; position: relative; z-index: 2; }\n.panel.on { display: block; }\n.panel h2 { font-size: 2rem; }\n.block { margin-top: 1.8rem; }\n.two { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; } .two > * { min-width: 0; }\n.actions { display: flex; justify-content: flex-end; margin-top: 1.1rem; } .actions.left { justify-content: flex-start; }\n.addrow { display: flex; gap: .5rem; align-items: center; margin-bottom: .9rem; } .addrow input { flex: 1; min-width: 0; } .addrow label { display: inline-flex; align-items: center; gap: .35rem; flex: 0 0 auto; white-space: nowrap; font-size: 14px; color: var(--ink-2); cursor: pointer; } .addrow label input { flex: none; width: auto; margin: 0; accent-color: var(--forest); } .addrow .ib { width: 38px; height: 38px; flex: 0 0 auto; border-radius: 10px; }\n.choices { display: grid; gap: .5rem; }\n.choices label { display: grid; grid-template-columns: auto 1fr; gap: 0 .7rem; cursor: pointer; padding: .7rem .8rem; border: 2px solid var(--line-2); border-radius: 12px; background: var(--paper); }\n.choices label:has(:checked) { border-color: var(--ink); box-shadow: 3px 3px 0 var(--ink); }\n.choices input { grid-row: span 2; margin: .2rem 0 0; accent-color: var(--forest); }\n.choices b { font-weight: 600; } .choices small { color: var(--ink-2); font-size: 13px; }\n.limits { display: grid; grid-template-columns: 1fr 1fr; gap: .6rem 1.5rem; margin-top: 1.3rem; }\n.limits label { display: grid; grid-template-columns: 1fr auto; align-items: center; gap: .6rem; } .limits label small { color: var(--ink-3); }\n.form { display: grid; grid-template-columns: 1fr 1fr; gap: .9rem 1.5rem; } .form label { display: grid; gap: .3rem; font-weight: 600; font-size: 14px; } .form .wide { grid-column: 1 / -1; }\n.danger-zone { border: 2px solid var(--red); border-radius: 12px; padding: 1rem 1.1rem; background: var(--red-soft); } .danger-zone h3 { color: var(--red); } .form label.switch { display: flex; flex-direction: row; align-items: center; gap: .6rem; font-weight: 600; font-size: 14px; } .switch input { accent-color: var(--forest); width: 18px; height: 18px; }\ntable { width: 100%; border-collapse: collapse; }\nth { text-align: left; font-size: 12px; font-weight: 600; color: var(--ink-3); padding: .4rem .5rem; border-bottom: 2px solid var(--ink); white-space: nowrap; }\ntd { padding: .5rem .5rem; vertical-align: middle; border-bottom: 1px solid var(--line); }\ntbody tr:nth-child(even) td { background: rgba(255,255,255,.55); }\nth.r, td.r { text-align: right; white-space: nowrap; } td.mono, td.dim { white-space: nowrap; } .events td.c:empty::before { content: \"(no content)\"; color: var(--ink-3); }\ntd .ib { width: 26px; height: 26px; box-shadow: 1px 1px 0 var(--ink); } td .ib svg { width: 13px; height: 13px; }\ntd input.txt { padding: .25rem .5rem; font-size: 14px; } td select.role { width: auto; min-width: 7rem; padding: .25rem .4rem; font-size: 13px; } .people-table input.name { width: 7rem; } .people-table input.note { width: 9.5rem; }\n.kind { font-family: var(--mono); font-size: 12px; background: var(--sun); border: 1.5px solid var(--ink); padding: 0 .5rem; border-radius: 999px; font-weight: 500; white-space: nowrap; }\n.events td.c { max-width: 0; width: 100%; overflow-x: auto; white-space: nowrap; scrollbar-width: thin; -webkit-mask-image: linear-gradient(90deg, #000 calc(100% - 2rem), transparent); mask-image: linear-gradient(90deg, #000 calc(100% - 2rem), transparent); }\n.people-table td.name { width: 12rem; }\n.ev { display: inline-grid; place-items: center; width: 20px; height: 20px; border-radius: 4px; vertical-align: -5px; margin-right: .45rem; font: 500 9px var(--mono); background: var(--line); color: var(--ink-2); font-style: normal; }\n.plain { list-style: none; margin: 0; padding: 0; } .plain li { display: grid; grid-template-columns: auto 1fr auto; align-items: center; gap: .5rem; padding: .5rem 0; border-bottom: 2px dotted var(--line-2); } .plain li > span { min-width: 0; overflow-wrap: anywhere; } .plain li:last-child { border-bottom: 0; } .plain li.empty { grid-template-columns: 1fr; color: var(--ink-3); }\n.kindline { margin: .4rem 0; color: var(--ink-2); display: flex; flex-wrap: wrap; align-items: center; gap: .35rem; }\n.tag { display: inline-flex; align-items: center; gap: .2rem; font-family: var(--mono); font-size: 13px; padding: .05rem .2rem .05rem .55rem; border: 2px solid var(--ink); border-radius: 999px; background: var(--paper); box-shadow: 1px 1px 0 var(--ink); }\n.tag.plain { padding-right: .55rem; box-shadow: none; border-color: var(--line-2); color: var(--ink-3); } .tag.blk { color: var(--red); }\n.tag .ib { width: 18px; height: 18px; border-width: 1.5px; box-shadow: none; margin-left: .2rem; } .tag .ib svg { width: 9px; height: 9px; }\n.counters { display: grid; grid-template-columns: repeat(4, 1fr); gap: 1.2rem; margin-bottom: 1.6rem; }\n.counter { display: grid; justify-items: center; align-content: center; gap: .15rem; min-height: 7.2rem; text-align: center; padding: 1rem .8rem; border: 2px solid var(--ink); border-radius: 16px; box-shadow: 4px 4px 0 var(--ink); background: var(--paper); }\n.counter:nth-child(1) { background: var(--sun); } .counter:nth-child(2) { background: var(--peach); } .counter:nth-child(3) { background: var(--sky); } .counter:nth-child(4) { background: var(--mint); }\n.counter .big { font: 400 2.6rem/1 var(--display); white-space: nowrap; } .counter small { display: block; margin-top: .35rem; font: 700 12px var(--sans); text-transform: uppercase; letter-spacing: .08em; } .counter .sub { font-size: 12px; color: var(--ink-2); }\n.kbar { display: flex; width: 100%; height: 22px; border: 2px solid var(--ink); border-radius: 999px; overflow: hidden; background: var(--paper); margin-bottom: .35rem; } .kbar i { display: block; height: 100%; border-right: 2px solid var(--ink); } .kbar i:last-child { border-right: 0; }\n.k1 { background: var(--ink); } .k2 { background: var(--forest); } .k3 { background: var(--id-3); } .k4 { background: var(--id-2); } .k5 { background: var(--line-2); }\n.legend { display: flex; flex-wrap: wrap; justify-content: center; gap: .1rem .6rem; font-family: var(--mono); font-size: 10.5px; text-transform: uppercase; } .legend i { display: inline-block; width: 9px; height: 9px; border: 1.5px solid var(--ink); border-radius: 2px; margin-right: .3rem; vertical-align: -1px; }\n.usage { display: grid; grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr)); gap: .8rem; } .usage div { padding: .7rem .9rem; border: 2px solid var(--ink); border-radius: 12px; background: var(--paper); } .usage small { display: block; color: var(--ink-3); font-size: 12px; } .usage b { font: 400 1.5rem/1.2 var(--display); }\n@media (max-width: 52rem) { .two, .gauges, .limits, .form, .counters { grid-template-columns: 1fr !important; } .addrow { flex-wrap: wrap; } .mast { grid-template-columns: 1fr; } .mast .right { justify-items: start; text-align: left; } }\n@media (max-width: 40rem) { .events:not(#kinds):not(#jobs) th:first-child, .events:not(#kinds):not(#jobs) td:first-child { display: none; } }\n\n.slegend { justify-content: flex-start; margin: 0 0 1.2rem; }\n#s-totals { margin-bottom: .4rem; }\ntd.keep { white-space: nowrap; } td.keep input { width: 5.5rem; display: inline-block; margin-right: .3rem; } td.keep input::placeholder { color: var(--ink-3); }\n#kinds tr.any td:first-child { font-weight: 600; }\n#kinds td:first-child .kind { display: inline-block; min-width: 5.2em; text-align: center; margin-right: .35rem; }\n/* Tables keep their columns and scroll inside the card on narrow screens instead of pushing the page sideways. */\n.scroll { overflow-x: auto; max-width: 100%; scrollbar-width: thin; } .scroll table { min-width: 100%; }\nsection, .card { overflow-x: clip; }\n.kind.sys { background: var(--mint); border-color: var(--forest); color: var(--forest); }\ntd.keep.sys { color: var(--ink-3); font-size: 13px; white-space: normal; }\n\n#console.mod .tabs a:not([data-tab=people]):not([data-tab=moderation]) { display: none; } #console.mod #thresholdform { display: none; }\n#members select.role { width: auto; padding: .1rem .3rem; font-size: 12px; margin-left: .3rem; }\n.wire-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: .5rem 1.2rem; padding: .8rem 0; border-bottom: 1px solid var(--line); align-items: start; } .wire-row:first-child { border-top: 2px solid var(--ink); }\n.wire-main { min-width: 0; } .wire-side { display: grid; justify-items: end; gap: .45rem; max-width: 26rem; }\n.wire-acts { display: flex; gap: .4rem; white-space: nowrap; } .wire-acts .btn { padding: .35rem .75rem; font-size: 13px; }\n.wire-meta { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: .35rem .5rem; align-items: center; font-size: 13px; color: var(--ink-2); text-align: right; } .wire-meta:empty { display: none; }\n.pill { display: inline-block; padding: .1rem .6rem; border: 1.5px solid var(--ink); border-radius: 999px; font: 600 12px var(--sans); color: var(--ink); background: var(--paper); } .pill.on { background: var(--mint); } .pill.off { color: var(--ink-3); } .pill.bad { color: var(--red); }\n.chip { display: inline-block; padding: .05rem .45rem; border: 1px solid var(--forest); border-radius: 6px; font: 12px var(--mono); color: var(--forest); } .chip.bad { border-color: var(--red); color: var(--red); }\n.share { display: grid; grid-template-columns: minmax(0, 3fr) minmax(14rem, 2fr); gap: 1.4rem; align-items: start; } .share #cardimg { width: 100%; height: auto; display: block; }\n.share-side { display: grid; gap: .8rem; justify-items: start; } .naddr { display: block; font-size: 12px; line-height: 1.5; word-break: break-all; color: var(--ink-2); }\n@media (max-width: 52rem) { .share { grid-template-columns: 1fr; } .wire-side { display: contents; } .wire-acts { justify-self: end; } .wire-meta { grid-column: 1 / -1; justify-content: flex-start; text-align: left; } }\n#presets .btn { margin: 0 .4rem .4rem 0; }\n.panel form h3.gap { margin-top: 1.4rem; }\n.key { position: relative; display: inline-block; font-family: var(--mono); } .key::before { content: attr(data-short); } .key .full { position: absolute; left: 0; top: 0; width: 1px; height: 1px; overflow: hidden; opacity: 0; white-space: nowrap; }\n.mast .banner { grid-column: 1 / -1; width: 100%; aspect-ratio: 4 / 1; overflow: hidden; border: 2px solid var(--ink); border-radius: 18px; box-shadow: 4px 4px 0 var(--ink); background: var(--paper); margin-bottom: .5rem; } .mast .banner img { width: 100%; height: 100%; object-fit: cover; display: block; }\n.mast .wordmark { display: flex; align-items: center; gap: 1rem; } .mast .icon { width: 64px; height: 64px; border-radius: 50%; border: 2px solid var(--ink); box-shadow: 3px 3px 0 var(--ink); background: var(--paper); object-fit: cover; }\n.metarow { display: flex; flex-wrap: wrap; gap: .4rem .6rem; align-items: center; margin: -.4rem 0 1rem; font-size: 13px; color: var(--ink-2); }\n.metarow .tag { display: inline-block; padding: .1rem .6rem; border: 1.5px solid var(--ink); border-radius: 999px; font: 600 12px var(--sans); color: var(--ink); background: var(--sun); }\n.metarow .sep { color: var(--ink-3); } .metarow a { color: var(--forest); text-decoration: none; border-bottom: 1.5px solid var(--forest); } .metarow a:hover { border-bottom-width: 2px; }\n.about a { color: var(--forest); text-decoration: none; border-bottom: 1.5px solid var(--forest); }\n.wire-acts label { display: inline-flex; align-items: center; gap: .35rem; font-size: 14px; color: var(--ink-2); cursor: pointer; } .wire-acts label input { margin: 0; accent-color: var(--forest); } .wire-row.dim .wire-main { color: var(--ink-3); }\n"; -export const CONSOLE_JS = "(async () => {\n const $ = (s) => document.querySelector(s);\n const $$ = (s) => document.querySelectorAll(s);\n const host = location.host;\n const wsURL = (location.protocol === \"https:\" ? \"wss://\" : \"ws://\") + host;\n const rpcURL = location.origin + \"/\";\n let info = null, me = null, owner = \"\", policy = null, fuel = null, people = null, myRole = \"\";\n\n const toast = (msg) => { const t = $(\"#toast\"); t.textContent = msg; t.classList.add(\"show\"); clearTimeout(t._t); t._t = setTimeout(() => t.classList.remove(\"show\"), 2600); };\n // guard wraps a handler: disables the button, shows errors as toasts. Defined first, since handlers below use it.\n const guard = (fn) => async (ev) => { ev.preventDefault(); const b = ev.submitter || ev.target; if (b) b.disabled = true; try { await fn(ev); } catch (e) { toast(e.message); } finally { if (b) b.disabled = false; } };\n const short = (hex) => hex ? hex.slice(0, 8) + \"…\" + hex.slice(-4) : \"\";\n // key shows a key short but keeps the whole of it in the DOM: selecting, double-clicking or clicking it copies the full hex.\n const key = (hex) => hex ? '' + hex + '' : '';\n const hue = (hex) => (parseInt(hex.slice(0, 2), 16) * 360 / 256).toFixed(0) + \"deg\";\n const av = (hex) => '';\n const fmtBytes = (n) => n < 1e6 ? (n / 1e3).toFixed(0) + \" KB\" : n < 1e9 ? (n / 1e6).toFixed(1) + \" MB\" : (n / 1e9).toFixed(2) + \" GB\";\n const fmtHours = (ms) => ms < 3600e3 ? Math.round(ms / 60e3) + \" min\" : (ms / 3600e3).toFixed(ms < 36e6 ? 1 : 0) + \" h\";\n const fuelOver = () => !!fuel && (fuel.eventBytes > fuel.freeEventBytes || fuel.mediaBytes > fuel.freeMediaBytes || fuel.activeMs > fuel.freeActiveMs || fuel.rowsWritten > fuel.freeRowsWritten);\n const fmtTime = (t) => t ? new Date(t * 1000).toLocaleString(undefined, { month: \"short\", day: \"numeric\", hour: \"2-digit\", minute: \"2-digit\" }) : \"–\";\n const fmtDay = (t) => t ? new Date(t * 1000).toLocaleDateString(undefined, { month: \"short\", day: \"numeric\" }) : \"–\";\n const ago = (t) => { const s = Math.max(0, Math.floor(Date.now() / 1000) - t); return s < 60 ? \"just now\" : s < 3600 ? Math.floor(s / 60) + \" min\" : s < 86400 ? Math.floor(s / 3600) + \" h\" : Math.floor(s / 86400) + \" d\"; };\n const esc = (s) => String(s ?? \"\").replace(/[&<>\"']/g, (c) => ({ \"&\": \"&\", \"<\": \"<\", \">\": \">\", '\"': \""\", \"'\": \"'\" })[c]);\n\n const IC = {\n x: '',\n undo: '',\n check: '',\n trash: '',\n ban: '',\n banuser: '',\n eye: '',\n lock: '',\n pen: '',\n people: '',\n person: '',\n gauge: '',\n bolt: '',\n copy: '',\n pin: '',\n };\n const ib = (icon, label, act, id, extra) => '\";\n\n const CH = \"qpzry9x8gf2tvdw0s3jn54khce6mua7l\";\n function npubToHex(s) {\n s = s.trim().toLowerCase();\n if (/^[0-9a-f]{64}$/.test(s)) return s;\n if (!s.startsWith(\"npub1\")) return null;\n const data = s.slice(5, -6).split(\"\").map((c) => CH.indexOf(c));\n if (data.some((d) => d < 0)) return null;\n let bits = 0, acc = 0, out = [];\n for (const d of data) { acc = (acc << 5) | d; bits += 5; if (bits >= 8) { bits -= 8; out.push((acc >> bits) & 255); } }\n return out.length === 32 ? out.map((b) => b.toString(16).padStart(2, \"0\")).join(\"\") : null;\n }\n\n async function sha256hex(s) {\n const b = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(s));\n return [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n }\n // ---- signing: a NIP-07 extension, or a NIP-46 remote signer ----\n // The remote path loads the bundled library on first use; its session\n // (client key, signer pubkey, relays) lives in localStorage until sign-out.\n let remote = null, lib = null, pendingNote = null;\n const NO_SIGNER = \"Install a nostr extension (Alby, nos2x, …) or connect a remote signer.\";\n const withTimeout = (p, ms, what) => Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error(what + \" did not answer; is the signer app open?\")), ms))]);\n const signer = {\n ready: () => !!remote || !!window.nostr,\n async getPublicKey() { if (remote) return withTimeout(remote.getPublicKey(), 20000, \"The remote signer\"); if (window.nostr) return window.nostr.getPublicKey(); throw new Error(NO_SIGNER); },\n async signEvent(ev) { if (remote) return withTimeout(remote.signEvent(ev), 60000, \"The remote signer\"); if (window.nostr) return window.nostr.signEvent(ev); throw new Error(NO_SIGNER); },\n };\n async function signerLib() {\n if (lib) return lib;\n if (!window.NostrSigner) await new Promise((res, rej) => { const s = document.createElement(\"script\"); s.src = window.SIGNER_URL || \"/signer.js\"; s.onload = res; s.onerror = () => rej(new Error(\"Could not load the signer library.\")); document.head.appendChild(s); });\n return (lib = window.NostrSigner);\n }\n const onauth = (u) => window.open(u, \"_blank\");\n // The signer conversation rides this relay, and a relay may ask the socket to\n // authenticate before it delivers kind 24133 to its parties; answer with the\n // session's own key.\n const authPool = (L, sk) => new L.SimplePool({ automaticallyAuth: () => (evt) => Promise.resolve(L.finalizeEvent(evt, sk)) });\n const saveSession = (sk, s, secret) => localStorage.setItem(\"nip46\", JSON.stringify({ sk: lib.bytesToHex(sk), pubkey: s.bp.pubkey, relays: s.bp.relays, secret: secret || null }));\n async function resumeRemote() {\n const raw = localStorage.getItem(\"nip46\");\n if (!raw) return false;\n try {\n const s = JSON.parse(raw); const L = await signerLib();\n remote = L.BunkerSigner.fromBunker(L.hexToBytes(s.sk), { pubkey: s.pubkey, relays: s.relays, secret: s.secret }, { onauth, pool: authPool(L, L.hexToBytes(s.sk)) });\n return true;\n } catch { localStorage.removeItem(\"nip46\"); return false; }\n }\n async function connectBunker(input) {\n const L = await signerLib();\n const bp = await L.parseBunkerInput(input.trim());\n if (!bp) throw new Error(\"That is not a bunker:// URL.\");\n if (!bp.relays.length) throw new Error(\"The bunker URL names no relay.\");\n const sk = L.generateSecretKey();\n const s = L.BunkerSigner.fromBunker(sk, bp, { onauth, pool: authPool(L, sk) });\n await withTimeout(s.connect({ name: host, url: location.origin }), 60000, \"The signer\");\n await Promise.race([s.switchRelays(), new Promise((r) => setTimeout(r, 3000))]);\n remote = s; saveSession(sk, s, bp.secret);\n }\n // The nostrconnect:// flow: this relay carries the traffic, so no third relay is involved.\n let ncPending = null;\n async function offerNostrConnect() {\n if (ncPending) return ncPending;\n const L = await signerLib();\n const sk = L.generateSecretKey();\n const secret = L.bytesToHex(crypto.getRandomValues(new Uint8Array(8)));\n const uri = L.createNostrConnectURI({ clientPubkey: L.getPublicKey(sk), relays: [wsURL], secret, name: host, url: location.origin, perms: [\"sign_event:27235\", \"sign_event:9734\"] });\n $(\"#nclink\").href = uri; $(\"#ncnote\").textContent = \"\";\n $(\"#ncqr\").src = \"/qr.svg?text=\" + encodeURIComponent(uri); $(\"#ncqr\").classList.remove(\"hidden\");\n ncPending = L.BunkerSigner.fromURI(sk, uri, { onauth, pool: authPool(L, sk) }, 600000).then((s) => { remote = s; saveSession(sk, s, secret); ncPending = null; return s; }, (e) => { ncPending = null; throw e; });\n return ncPending;\n }\n async function remoteDone() {\n me = await signer.getPublicKey();\n localStorage.setItem(\"me\", me);\n $(\"#remotesec\").classList.add(\"hidden\");\n toast(\"Remote signer connected\");\n if (pendingNote && !owner) { const n = pendingNote; pendingNote = null; await claimNow(n); return; }\n pendingNote = null;\n renderHeader(); await loadAdmin(); await loadPeople();\n }\n function showRemote(note) {\n pendingNote = note || null;\n $(\"#remotesec\").classList.remove(\"hidden\");\n $(\"#remotesec\").scrollIntoView({ behavior: \"smooth\", block: \"start\" });\n offerNostrConnect().then(remoteDone).catch((e) => { $(\"#ncnote\").textContent = e.message; });\n }\n\n async function rpc(method, ...params) {\n if (!signer.ready()) throw new Error(NO_SIGNER);\n const body = JSON.stringify({ method, params });\n const ev = await signer.signEvent({ kind: 27235, created_at: Math.floor(Date.now() / 1000), content: \"\", tags: [[\"u\", rpcURL], [\"method\", \"POST\"], [\"payload\", await sha256hex(body)]] });\n const resp = await fetch(rpcURL, { method: \"POST\", headers: { \"content-type\": \"application/nostr+json+rpc\", authorization: \"Nostr \" + btoa(JSON.stringify(ev)) }, body });\n const json = await resp.json();\n if (json.error) throw new Error(json.error);\n return json.result;\n }\n\n // ---- front of house ----\n // urlish shows a URL as a short link: the host and the start of the path, the whole thing on hover and as the target.\n class Html { constructor(s) { this.s = s; } }\n const urlish = (u) => {\n if (!u) return \"\";\n let label = u; try { const x = new URL(u); label = x.host + (x.pathname.length > 1 ? x.pathname.slice(0, 18) + (x.pathname.length > 18 ? \"\\u2026\" : \"\") : \"\"); } catch { /* not a URL */ }\n if (!/^https?:\\/\\//.test(u)) return u;\n return new Html('' + esc(label) + \"\");\n };\n function renderHeader() {\n const name = (info && info.name) || host.split(\".\")[0];\n $(\"#title\").textContent = name;\n document.title = name + \" - relay\";\n $(\"#url\").textContent = wsURL;\n $(\"#d-ws\").textContent = wsURL; $(\"#d-blossom\").textContent = location.origin; $(\"#d-nip05\").textContent = \"you@\" + host;\n $(\"#nip05-example\").textContent = \"alice@\" + host;\n const desc = (info && info.description) || \"\";\n $(\"#desc\").textContent = desc; $(\"#desc\").classList.toggle(\"hidden\", !desc);\n // What the owner declared about the relay, on the page, not only in the document clients read.\n const img = (id, url) => { const el = $(id); if (url) el.src = url; el.classList.toggle(\"hidden\", !url); };\n img(\"#bannerimg\", info?.banner); $(\"#banner\").classList.toggle(\"hidden\", !info?.banner);\n img(\"#iconimg\", info?.icon);\n const meta = [];\n for (const t of info?.tags || []) meta.push('' + esc(t) + \"\");\n const where = [...(info?.language_tags || []), ...(info?.relay_countries || [])];\n if (where.length) meta.push(\"\" + esc(where.join(\", \")) + \"\");\n const link = (label, href) => href ? '' + label + \"\" : \"\";\n const contact = info?.contact ? (/^(mailto:|https?:\\/\\/)/.test(info.contact) ? link(\"Contact\", info.contact) : \"\" + esc(info.contact) + \"\") : \"\";\n for (const x of [contact, link(\"Terms\", info?.terms_of_service), link(\"Posting policy\", info?.posting_policy), link(\"Privacy\", info?.privacy_policy)]) if (x) meta.push(x);\n $(\"#metarow\").innerHTML = meta.join('|'); $(\"#metarow\").classList.toggle(\"hidden\", meta.length === 0);\n $(\"#frontsec\").classList.toggle(\"hidden\", !desc && meta.length === 0);\n owner = (info && info.pubkey) || \"\";\n const isOwner = !!me && me === owner;\n const lease = !owner && info && info.lease ? info.lease : null;\n $(\"#ownerline\").innerHTML = owner ? 'run by ' + key(owner) + \"\" : lease ? \"temporary until \" + fmtDay(lease.expires_at) : \"unclaimed\";\n $(\"#owner-av\").classList.toggle(\"hidden\", !owner);\n if (owner) $(\"#owner-av\").style.setProperty(\"--h\", hue(owner));\n $(\"#who\").textContent = me ? (isOwner ? \"(that's you)\" : \"\") : \"\";\n $(\"#unclaimed\").classList.toggle(\"hidden\", !!owner || !!lease);\n $(\"#leased\").classList.toggle(\"hidden\", !lease);\n if (lease) {\n $(\"#lease-until\").textContent = fmtTime(lease.expires_at);\n $(\"#leasenote\").textContent = lease.holder ? \"Reserved for the key that asked for it; sign with that key.\" : \"\";\n }\n $(\"#signin\").classList.toggle(\"hidden\", !!me || !owner);\n $(\"#signin46\").classList.toggle(\"hidden\", !!me || !owner);\n $(\"#signout\").classList.toggle(\"hidden\", !me);\n $(\"#about\").innerHTML = [\n [\"Name\", info?.name], [\"Description\", info?.description], [\"Contact\", info?.contact], [\"Owner\", owner ? short(owner) : \"\"], [\"Relay key\", info?.self ? short(info.self) : \"\"], [\"Software\", urlish(info?.software)], [\"Version\", info?.version],\n [\"Max query\", info?.limitation?.max_limit], [\"Auth required\", String(!!info?.limitation?.auth_required)], [\"Restricted writes\", String(!!info?.limitation?.restricted_writes)], [\"Min PoW\", info?.limitation?.min_pow_difficulty || 0],\n [\"Tags\", info?.tags?.join(\", \")], [\"Languages\", info?.language_tags?.join(\", \")], [\"Countries\", info?.relay_countries?.join(\", \")],\n [\"Terms\", urlish(info?.terms_of_service)], [\"Posting policy\", urlish(info?.posting_policy)], [\"Privacy policy\", urlish(info?.privacy_policy)], [\"Icon\", urlish(info?.icon)], [\"Banner\", urlish(info?.banner)],\n [\"NIPs\", info?.supported_nips?.join(\" \")],\n ].map(([k, v]) => \"
                \" + k + \"\" + (v === undefined || v === \"\" ? '–' : v instanceof Html ? v.s : esc(v)) + \"
                \").join(\"\");\n renderCare();\n }\n\n function renderCare() {\n const g = (icon, label, off) => '' + IC[icon] + \"\" + label + \"\";\n const writes = policy ? policy.writes : (info?.limitation?.restricted_writes ? \"allowlist\" : \"open\");\n const reads = policy ? policy.reads : (info?.limitation?.auth_required ? \"auth\" : \"open\");\n let out = writes === \"owner\" ? g(\"person\", \"only owner writes\") : writes === \"allowlist\" ? g(\"people\", \"members write\") : writes === \"wot\" ? g(\"people\", \"members and follows write\") : g(\"pen\", \"anyone writes\");\n out += reads === \"members\" ? g(\"people\", \"members read\") : reads === \"auth\" ? g(\"lock\", \"sign in to read\") : g(\"eye\", \"anyone reads\");\n if (fuel) {\n const over = fuelOver();\n out += fuel.outOfFuel ? g(\"gauge\", \"out of fuel\", true) : over ? g(\"bolt\", \"burning sats\") : g(\"gauge\", \"on free allowance\");\n }\n $(\"#care\").innerHTML = out;\n }\n\n async function loadPeople() {\n try { people = await (await fetch(\"/people\")).json(); } catch { return; }\n const isOwner = !!me && me === owner;\n let list = people.people || [];\n if (!people.public && isOwner && policy) list = (window.__members || []);\n $(\"#peoplesec\").classList.toggle(\"hidden\", !owner || list.length === 0);\n $(\"#people-note\").classList.toggle(\"hidden\", people.public);\n $(\"#people-count\").textContent = list.length || \"\";\n $(\"#dir\").innerHTML = list.map((m) => '' + av(m.pubkey) + '' + (m.name ? esc(m.name) + \"@\" + host : key(m.pubkey)) + \"\" + (m.role === \"owner\" ? 'owner' : \"\") + \"\").join(\"\");\n }\n\n async function loadInfo() {\n info = await (await fetch(\"/\", { headers: { accept: \"application/nostr+json\" } })).json();\n renderHeader();\n const git = info.supported_grasps?.includes(\"GRASP-01\");\n $(\"#git-connect\").classList.toggle(\"hidden\", !git);\n const clone = \"git clone '\" + location.origin + \"//.git'\";\n $(\"#git-clone\").textContent = clone;\n $(\"#git-copy\").dataset.copytext = clone;\n }\n\n async function loadFuel() {\n try { fuel = await (await fetch(\"/fuel\")).json(); } catch { return; }\n $(\"#fuelsec\").classList.toggle(\"hidden\", !owner);\n const pct = (used, free) => Math.min(100, Math.round((used / Math.max(free, 1)) * 100));\n const gauge = (id, used, free, text) => { const g = $(\"#g-\" + id), share = free ? used / free : 0; g.style.width = pct(used, free) + \"%\"; g.classList.toggle(\"over\", share > 1); g.classList.toggle(\"warm\", share > 0.75 && share <= 1); $(\"#p-\" + id).textContent = share > 1 ? \"over\" : Math.round(share * 100) + \"%\"; $(\"#t-\" + id).textContent = text; };\n gauge(\"events\", fuel.eventBytes, fuel.freeEventBytes, fmtBytes(fuel.eventBytes) + \" of \" + fmtBytes(fuel.freeEventBytes) + \" free\");\n gauge(\"media\", fuel.mediaBytes, fuel.freeMediaBytes, fmtBytes(fuel.mediaBytes) + \" of \" + fmtBytes(fuel.freeMediaBytes) + \" free\");\n gauge(\"active\", fuel.activeMs, fuel.freeActiveMs, fmtHours(fuel.activeMs) + \" of \" + fmtHours(fuel.freeActiveMs) + \" free\");\n gauge(\"rows\", fuel.rowsWritten, fuel.freeRowsWritten, fuel.rowsWritten.toLocaleString() + \" of \" + fuel.freeRowsWritten.toLocaleString() + \" free\");\n const sats = Math.floor(fuel.balanceMsats / 1000);\n const r = fuel.rates;\n $(\"#fuel-balance\").innerHTML = fuel.outOfFuel\n ? 'out of fuel Writes are paused until someone tops up.'\n : \"Balance \" + sats.toLocaleString() + \" sats. Past the allowances, prices track what the hosting costs: \" + r.satsPerGBMonthEvents.toLocaleString() + \" sats per GB-month of events, \" + r.satsPerGBMonthMedia.toLocaleString() + \" per GB-month of files, \" + r.satsPerActiveHour.toLocaleString() + \" per hour awake, \" + r.satsPerMillionRows.toLocaleString() + \" per million rows written. Traffic is free.\";\n $(\"#topup\").classList.toggle(\"hidden\", !fuel.enabled);\n // Who paid is the owner's to see: it comes with the signed stats call.\n let credits = [];\n if (owner && signer.ready()) { try { credits = (await rpc(\"stats\")).credits || []; } catch { credits = []; } }\n $(\"#credits tbody\").innerHTML = credits.length ? credits.map((c) => '' + esc(fmtTime(c.at)) + '' + av(c.payer) + key(c.payer) + '' + Math.floor(c.msats / 1000).toLocaleString() + \"\").join(\"\") : 'no zaps yet';\n if (!fuel.enabled) $(\"#topup-note\").textContent = \"Top-ups are not enabled on this service yet.\";\n renderCare();\n renderFuelTile();\n }\n\n async function topUp(sats) {\n if (!signer.ready()) throw new Error(NO_SIGNER);\n const msats = Math.round(sats * 1000);\n const zapRequest = await signer.signEvent({ kind: 9734, created_at: Math.floor(Date.now() / 1000), content: \"fuel for \" + host, tags: [[\"p\", fuel.servicePubkey], [\"amount\", String(msats)], [\"relays\", wsURL]] });\n const r = await (await fetch(\"/fuel/invoice\", { method: \"POST\", body: JSON.stringify({ zapRequest }) })).json();\n if (r.error) throw new Error(r.error);\n const inv = r.invoice;\n $(\"#invoice\").classList.remove(\"hidden\");\n $(\"#inv-text\").value = inv; $(\"#inv-link\").href = \"lightning:\" + inv; $(\"#inv-state\").textContent = \"waiting for payment…\";\n if (window.webln) { try { await window.webln.enable(); await window.webln.sendPayment(inv); } catch (e) { toast(e.message || \"wallet declined\"); } }\n const before = fuel.creditedMsats;\n for (let i = 0; i < 120; i++) {\n await new Promise((r) => setTimeout(r, 2500));\n await loadFuel();\n if (fuel.creditedMsats > before) { $(\"#inv-state\").textContent = \"paid, thank you\"; toast(\"Fuel credited\"); return; }\n }\n $(\"#inv-state\").textContent = \"no receipt yet; it can take a minute after paying\";\n }\n\n // ---- console ----\n function showTab(name) {\n if (name === \"content\" || name === \"storage\") name = \"data\";\n const known = myRole === \"moderator\" ? [\"people\", \"moderation\"] : [\"people\", \"moderation\", \"rules\", \"identity\", \"data\", \"sync\", \"views\", \"health\", \"owner\"];\n if (!known.includes(name)) name = \"people\";\n $$(\".tabs a\").forEach((a) => a.classList.toggle(\"on\", a.dataset.tab === name));\n $$(\".panel\").forEach((p) => p.classList.toggle(\"on\", p.dataset.panel === name));\n }\n // Tabs switch in place. A fragment still opens a tab when someone arrives with one,\n // but clicking never writes one, and any fragment already there is dropped.\n $$(\".tabs a\").forEach((a) => a.addEventListener(\"click\", (ev) => { ev.preventDefault(); showTab(a.dataset.tab); if (location.hash) history.replaceState(null, \"\", location.pathname + location.search); }));\n window.addEventListener(\"hashchange\", () => showTab(location.hash.slice(1)));\n // The strip fades on whichever side has more tabs off screen.\n const tabsFade = () => { const t = $(\"#tabs\"); t.classList.toggle(\"fade-l\", t.scrollLeft > 4); t.classList.toggle(\"fade-r\", t.scrollLeft + t.clientWidth < t.scrollWidth - 4); };\n $(\"#tabs\").addEventListener(\"scroll\", tabsFade); window.addEventListener(\"resize\", tabsFade); new ResizeObserver(tabsFade).observe($(\"#tabs\"));\n\n function renderFuelTile() {\n if (!fuel) return;\n const over = fuelOver();\n const sats = Math.max(0, Math.floor(fuel.balanceMsats / 1000));\n const d = new Date(), end = Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1), days = Math.max(1, Math.ceil((end - Date.now()) / 86400000));\n if (fuel.outOfFuel) { $(\"#h-fuel\").textContent = \"0 sats\"; $(\"#h-fuel-label\").textContent = \"out of fuel\"; $(\"#h-fuel-sub\").textContent = \"writes are paused\"; }\n else if (over) { $(\"#h-fuel\").textContent = sats.toLocaleString() + \" sats\"; $(\"#h-fuel-label\").textContent = \"fuel left\"; $(\"#h-fuel-sub\").textContent = \"past the free allowance\"; }\n else { $(\"#h-fuel\").textContent = days + (days === 1 ? \" day\" : \" days\"); $(\"#h-fuel-label\").textContent = \"free allowance left\"; $(\"#h-fuel-sub\").textContent = sats ? \"then \" + sats.toLocaleString() + \" sats\" : \"then a top-up is needed\"; }\n $(\"#usage\").innerHTML = [[\"events stored\", fmtBytes(fuel.eventBytes)], [\"files stored\", fmtBytes(fuel.mediaBytes)], [\"awake this month\", fmtHours(fuel.activeMs)], [\"rows written\", fuel.rowsWritten.toLocaleString()], [\"rows read\", fuel.rowsRead.toLocaleString()], [\"received this month\", fmtBytes(fuel.bytesIn)], [\"served this month\", fmtBytes(fuel.bytesOut)], [\"charged\", Math.floor(fuel.chargedMsats / 1000).toLocaleString() + \" sats\"]]\n .map(([k, v]) => \"
                \" + k + \"\" + v + \"
                \").join(\"\");\n }\n\n function renderHealth(stats) {\n $(\"#h-last\").textContent = stats.newest ? ago(stats.newest) : \"none\";\n $(\"#h-last-sub\").textContent = stats.newest ? fmtTime(stats.newest) : \"no events yet\";\n $(\"#h-conns\").textContent = stats.connections;\n const buckets = [[\"notes\", \"k1\", [1]], [\"reactions\", \"k2\", [7]], [\"DMs\", \"k3\", [4, 14, 1059]], [\"long-form\", \"k4\", [30023]], [\"other\", \"k5\", null]];\n const sums = buckets.map(() => 0); let total = 0;\n for (const { kind, n } of stats.kinds || []) { total += n; const i = buckets.findIndex((b) => b[2] && b[2].includes(kind)); sums[i < 0 ? 4 : i] += n; }\n const parts = buckets.map((b, i) => [b[0], b[1], sums[i]]).filter((p) => p[2] > 0);\n $(\"#h-kinds\").innerHTML = total ? parts.map(([name, cls, n]) => '').join(\"\") : '';\n $(\"#h-kinds-legend\").innerHTML = total ? parts.map(([name, cls, n]) => '' + name + \" \" + Math.round(n * 100 / total) + \"%\").join(\"\") : \"no events yet\";\n renderFuelTile();\n }\n\n async function loadAdmin() {\n const isOwner = !!me && me === owner;\n myRole = isOwner ? \"owner\" : \"\";\n let stats = null, p = null;\n // A signed-in member may be a moderator; the relay says by answering stats.\n if (me && owner && !isOwner) { try { [stats, p] = await Promise.all([rpc(\"stats\"), rpc(\"getpolicy\")]); myRole = \"moderator\"; } catch { myRole = \"\"; } }\n $(\"#console\").classList.toggle(\"hidden\", !myRole);\n loadMine();\n $(\"#console\").classList.toggle(\"mod\", myRole === \"moderator\");\n if (!myRole) { policy = null; renderCare(); return; }\n if (isOwner) [stats, p] = await Promise.all([rpc(\"stats\"), rpc(\"getpolicy\")]);\n policy = p;\n renderHealth(stats);\n renderCare();\n const fa = $(\"#access\"), fi = $(\"#identity\");\n fa.writes.value = p.writes; fa.reads.value = p.reads; fa.openKinds.value = (p.openKinds || []).join(\", \"); fa.guestReplies.checked = !!p.guestReplies;\n $(\"#wordsform\").words.value = (p.blockedWords || []).join(\"\\n\"); $(\"#wordsform\").inTags.checked = !!p.blockedWordsInTags; $(\"#thresholdform\").reportThreshold.value = p.reportThreshold || 0; fa.minPow.value = p.minPow; fa.maxFuture.value = p.maxFuture; fa.maxLimit.value = p.maxLimit; fa.maxSubs.value = p.maxSubs; fa.maxMessageKB.value = p.maxMessageKB;\n fa.eventsPerMinute.value = p.eventsPerMinute; fa.reqsPerMinute.value = p.reqsPerMinute; fa.maxBlobMB.value = p.maxBlobMB;\n renderFeatures(p.features || {});\n fi.name.value = p.name; fi.contact.value = p.contact; fi.description.value = p.description; fi.icon.value = p.icon;\n const fj = $(\"#joinform\"); fj.joinTerms.value = p.joinTerms; fj.directoryPublic.checked = !!p.directoryPublic;\n loadCard();\n fi.banner.value = p.banner || \"\"; fi.postingPolicy.value = p.postingPolicy || \"\"; fi.privacyPolicy.value = p.privacyPolicy || \"\";\n fi.tags.value = (p.tags || []).join(\", \"); fi.languageTags.value = (p.languageTags || []).join(\", \"); fi.relayCountries.value = (p.relayCountries || []).join(\", \");\n const fn = $(\"#notify\"), nt = p.notify || {};\n fn.reports.checked = !!nt.reports; fn.fuel.checked = !!nt.fuel; fn.jobs.checked = !!nt.jobs; fn.succession.checked = !!nt.succession; fn.digest.checked = !!nt.digest;\n showTab(location.hash.slice(1));\n if (isOwner) { await renderPresets(); renderWire(); renderSuccession(); loadDomains(); }\n await Promise.all([loadLists(), loadEvents(true), loadPins(), ...(isOwner ? [loadStorage()] : [])]);\n }\n\n async function loadAudit(before) {\n const rows = await rpc(\"listaudit\", before || 0);\n const html = rows.map((r) => '' + esc(fmtTime(r.at)) + '' + av(r.actor) + key(r.actor) + '' + esc(r.action) + '' + (/^[0-9a-f]{64}$/.test(r.target) ? key(r.target) : esc(r.target)) + '' + esc(r.detail) + '').join(\"\");\n const tb = $(\"#audit tbody\");\n if (before) tb.insertAdjacentHTML(\"beforeend\", html); else tb.innerHTML = html || 'Nothing yet';\n $(\"#audit-more\").style.display = rows.length < 100 ? \"none\" : \"\";\n }\n $(\"#audit-more\").onclick = guard(async () => { const last = $(\"#audit tbody tr:last-child\"); await loadAudit(last ? +last.dataset.seq : 0); });\n async function loadLists() {\n loadAudit(0);\n const [mem, bans, bannedEvents, allow, block, invites, reports, blobs, blocks, sites] = await Promise.all([rpc(\"listmembers\"), rpc(\"listbannedpubkeys\"), rpc(\"listbannedevents\"), rpc(\"listallowedkinds\"), rpc(\"listblockedkinds\"), rpc(\"listinvites\"), rpc(\"listreports\"), rpc(\"listblobs\", 100), rpc(\"listblockedips\"), rpc(\"listsites\")]);\n const members = mem.members;\n window.__members = members;\n const roleCell = (m) => m.role === \"owner\" ? ' owner' : myRole === \"owner\" ? ' ' : m.role === \"moderator\" ? ' moderator' : \"\";\n const untouchable = (m) => m.role === \"owner\" || (myRole !== \"owner\" && m.role === \"moderator\");\n // The tree: everyone under whoever invited them, the owner and the owner's own additions at the root.\n const known = new Set(members.map((m) => m.pubkey));\n const byInviter = new Map();\n for (const m of members) { const k = m.role !== \"owner\" && known.has(m.invited_by) ? m.invited_by : \"\"; if (!byInviter.has(k)) byInviter.set(k, []); byInviter.get(k).push(m); }\n const ordered = [], placed = new Set();\n const walk = (k, depth) => { for (const m of byInviter.get(k) || []) { if (placed.has(m.pubkey)) continue; placed.add(m.pubkey); m.depth = depth; ordered.push(m); walk(m.pubkey, depth + 1); } };\n walk(\"\", 0);\n for (const m of members) if (!placed.has(m.pubkey)) { m.depth = 0; ordered.push(m); }\n const nameOf = (pk) => { const x = members.find((m) => m.pubkey === pk); return x && x.name ? x.name : short(pk); };\n const limits = (m) => m.role === \"owner\" ? \"\" : myRole === \"owner\"\n ? ''\n : '' + (m.keep_days ? m.keep_days + \" d\" : \"\") + (m.max_bytes ? \" \" + fmtBytes(m.max_bytes) : \"\") + \"\";\n $(\"#members tbody\").innerHTML = ordered.map((m) => '' + av(m.pubkey) + key(m.pubkey) + roleCell(m) + (m.depth ? ' via ' + esc(nameOf(m.invited_by)) + \"\" : \"\") + (m.invites ? ' ' + m.invites + \" inv\" : \"\") + '' + limits(m) + '' + esc(fmtDay(m.joined_at)) + \", \" + esc(m.via) + '' + ib(\"check\", \"Save\", \"savemember\", m.pubkey) + (untouchable(m) ? \"\" : ib(\"x\", \"Remove\", \"removemember\", m.pubkey) + ib(\"banuser\", \"Ban\", \"banpubkey\", m.pubkey, \"danger\")) + \"\").join(\"\");\n const tf = $(\"#treeform\");\n tf.classList.toggle(\"hidden\", myRole !== \"owner\");\n if (policy && policy.memberInvites) { tf.depth.value = policy.memberInvites.depth; tf.quota.value = policy.memberInvites.quota; }\n $(\"#transfer [name=pubkey]\").innerHTML = members.filter((m) => m.role !== \"owner\").map((m) => '\").join(\"\");\n $(\"#succession [name=heir]\").innerHTML = $(\"#transfer [name=pubkey]\").innerHTML;\n $(\"#tc-people\").textContent = members.length;\n const link = (code) => location.origin + \"/invite/\" + code;\n $(\"#invites\").innerHTML = invites.length ? invites.map((i) => '
              • inv…' + i.code.slice(-8) + \" \" + esc(i.note || \"\") + ' ' + i.uses + (i.max_uses ? \"/\" + i.max_uses : \"\") + \" used, until \" + esc(fmtDay(i.expires_at)) + \"\" + ib(\"copy\", \"Copy link\", \"copy\", link(i.code)) + ib(\"x\", \"Revoke\", \"revokeinvite\", i.code) + \"
              • \").join(\"\") : '
              • no invites
              • ';\n const person = (r, icon, label, act) => \"
              • \" + av(r.pubkey) + '' + short(r.pubkey) + \" \" + esc(r.reason || \"\") + \"\" + ib(icon, label, act, r.pubkey) + \"
              • \";\n $(\"#bans\").innerHTML = bans.length ? bans.map((r) => person(r, \"undo\", \"Unban\", \"unrulepubkey\")).join(\"\") : '
              • nobody banned
              • ';\n $(\"#blocks\").innerHTML = blocks.length ? blocks.map((r) => '
              • ip' + esc(r.ip) + \" \" + esc(r.reason || \"\") + \"\" + ib(\"undo\", \"Unblock\", \"unblockip\", r.ip) + \"
              • \").join(\"\") : '
              • no addresses blocked
              • ';\n $(\"#banned-events\").innerHTML = bannedEvents.map((r) => '
              • ev' + key(r.id) + \" \" + esc(r.reason || \"\") + \"\" + ib(\"check\", \"Allow again\", \"allowevent\", r.id) + \"
              • \").join(\"\");\n $(\"#reports tbody\").innerHTML = reports.length ? reports.map((r) => '' + esc(fmtTime(r.at)) + '' + esc(r.type || \"report\") + '' + av(r.target_pubkey) + key(r.target_pubkey) + (r.target_event ? (r.blob ? ' file ' + key(r.target_event) + \"\" : ' ev ' + key(r.target_event) + (r.hidden ? ' hidden' : \"\") + \"\") : \"\") + '' + esc(r.content) + '' + ib(\"check\", \"Dismiss\", \"resolve:dismiss\", r.id) + ib(\"trash\", r.blob ? \"Delete the file\" : \"Delete the event\", \"resolve:delete\", r.id) + ib(\"banuser\", \"Ban the author\", \"resolve:ban\", r.id, \"danger\") + \"\").join(\"\") : 'nothing reported';\n $(\"#reports-count\").textContent = reports.length || \"\"; $(\"#tc-reports\").textContent = reports.length || \"\";\n $(\"#blobs tbody\").innerHTML = blobs.length ? blobs.map((b) => '' + esc(fmtTime(b.uploaded)) + '' + key(b.sha256) + ' ' + esc(b.type) + '' + fmtBytes(b.size) + '' + av(b.uploader) + key(b.uploader) + '' + ib(\"trash\", \"Delete file\", \"deleteblob\", b.sha256, \"danger\") + \"\").join(\"\") : 'no uploads';\n $(\"#blobs-count\").textContent = blobs.length || \"\";\n $(\"#sites tbody\").innerHTML = sites.length ? sites.map((s) => '' + av(s.author) + key(s.author) + '' + esc(s.d || (s.kind === 5128 ? \"snapshot\" : \"root\")) + '' + esc(s.url) + '' + esc(s.paths) + (s.missing ? ' ' + esc(s.missing) + ' missing' : '') + '' + fmtBytes(s.size) + '' + esc(s.expires_at ? fmtTime(s.expires_at) : \"never\") + '' + ib(\"trash\", \"Delete site\", \"deleteevent\", s.id, \"danger\") + '').join(\"\") : 'no sites yet';\n $(\"#sites-count\").textContent = sites.length || \"\";\n const tag = (k, cls) => '' + k + ib(\"x\", \"Remove rule\", \"unrulekind\", String(k)) + \"\";\n $(\"#kinds-allow\").innerHTML = allow.length ? allow.map((k) => tag(k, \"ok\")).join(\"\") : 'all';\n $(\"#kinds-block\").innerHTML = block.length ? block.map((k) => tag(k, \"blk\")).join(\"\") : 'none';\n await loadPeople();\n }\n\n const KIND_NAMES = { 0: \"profiles\", 1: \"notes\", 3: \"contacts\", 4: \"DMs\", 5: \"deletions\", 6: \"reposts\", 7: \"reactions\", 16: \"reposts\", 1059: \"gift wraps\", 1063: \"file headers\", 1111: \"comments\", 1984: \"reports\", 9734: \"zap requests\", 9735: \"zap receipts\", 9802: \"highlights\", 10002: \"relay lists\", 13534: \"roster\", 9000: \"group adds\", 9001: \"group removals\", 9021: \"join requests\", 9022: \"leave requests\", 39000: \"group info\", 39001: \"group admins\", 39002: \"group members\", 39003: \"group roles\", 30023: \"articles\", 30024: \"drafts\", 30078: \"app data\", 30311: \"live events\", 30818: \"wiki\" };\n const kindName = (k) => KIND_NAMES[k] || (k >= 20000 && k < 30000 ? \"ephemeral\" : k >= 30000 && k < 40000 ? \"addressable\" : k >= 10000 && k < 20000 ? \"replaceable\" : \"kind \" + k);\n const SYS_KINDS = new Set([0, 3, 10002, 9735, 13534, 8000, 8001, 9000, 9001, 39000, 39001, 39002, 39003]);\n let storage = null;\n\n // Features (settings.ts): a select each; search has three modes, the rest on or off.\n const FEATURES = [\n [\"search\", \"Search\", \"NIP-50. Prose indexes notes, threads, comments, highlights, articles and wiki pages; full indexes every public kind with content. A change applies to events from then on.\", [\"prose:prose\", \"full:full\", \"off:off\"]],\n [\"sync\", \"Sync\", \"NIP-77 reconciliation, which reads the whole matching set per sync.\"],\n [\"count\", \"Counts\", \"NIP-45 COUNT, with HLL sketches.\"],\n [\"discovery\", \"Discovery record\", \"NIP-66: the record the relay signs about itself, for crawlers.\"],\n [\"names\", \"Names\", \"NIP-05 addresses under this relay's domain.\"],\n [\"files\", \"Files\", \"Blossom and NIP-96: uploads, downloads and listings.\"],\n [\"pages\", \"Pages and feed\", \"Notes and articles as pages, and the Atom feed.\"],\n [\"sites\", \"Static websites\", \"NIP-5A sites on their own hostnames. Mirroring copies missing files into this relay and costs fuel.\", [\"mirror:on, mirror files\", \"proxy:on, fetch as needed\", \"off:off\"]],\n [\"marmot\", \"Marmot transport\", \"Signed KeyPackages and encrypted group messages, with account admission for ephemeral authors.\"],\n [\"grasp\", \"Git repositories\", \"GRASP Git hosting with admitted repository state. The prototype backend has bounded storage and compute limits.\"],\n [\"signer\", \"Signer traffic\", \"NIP-46 remote signing carried for anyone, never stored.\"],\n ];\n function renderFeatures(f) {\n $(\"#features\").innerHTML = FEATURES.map(([k, title, about, modes]) => {\n const cur = k === \"sites\" ? (f.sites?.enabled === false ? \"off\" : f.sites?.mirror === false ? \"proxy\" : \"mirror\") : modes ? String(f[k] || \"prose\") : String(f[k] !== false);\n const opts = (modes || [\"true:on\", \"false:off\"]).map((m) => { const [v, l] = m.split(\":\"); return '\"; }).join(\"\");\n return \"\";\n }).join(\"\");\n }\n $(\"#features\").addEventListener(\"change\", guard(async (ev) => {\n const sel = ev.target.closest(\"select[data-feature]\"); if (!sel) return;\n const k = sel.dataset.feature, v = k === \"search\" || k === \"sites\" ? sel.value : sel.value === \"true\";\n policy = await rpc(\"setpolicy\", { features: { [k]: k === \"sites\" ? { enabled: v !== \"off\", mirror: v === \"mirror\" } : v } });\n toast(k === \"search\" ? \"Search: \" + v : (v ? \"Switched on \" : \"Switched off \") + k); await loadInfo();\n }));\n\n async function loadViews() {\n let views;\n try { views = await rpc(\"listviews\"); } catch { return; }\n $(\"#views\").innerHTML = views.map((v) => {\n const runs = v.trigger === \"off\" ? \"off\" : v.trigger === \"live\" ? \"live, from memory\" : v.trigger === \"write\" ? \"on write and daily\" : v.trigger;\n const label = (c) => (c === \"off\" ? \"off\" : c === \"write\" ? \"on write\" : c === \"live\" ? \"on\" : c);\n const choices = [...v.choices, v.default].filter((c, i, a) => a.indexOf(c) === i);\n const pick = '\";\n const who = v.audience === \"members\" ? \"members\" + (v.stored ? \"\" : \", on request\") : \"anyone\";\n const last = v.trigger === \"live\" ? \"\" : v.last ? \"last run \" + fmtTime(v.last.at) : \"not run yet\";\n const rows = v.trigger === \"live\" ? \"no rows\" : v.last ? v.last.rows.toLocaleString() + \" rows\" : \"\";\n const meta = [runs, who, last, rows].filter(Boolean).map((x) => \"\" + esc(x) + \"\").join('|');\n return '
                ' + esc(v.name) + '
                ' + esc(v.about) + '
                ' + pick + (v.on ? 'Open' : \"\") + '
                ' + meta + \"
                \";\n }).join(\"\");\n }\n $(\"#views\").addEventListener(\"change\", guard(async (ev) => {\n const sel = ev.target.closest(\"select[data-view]\"); if (!sel) return;\n const value = sel.value === \"live\" ? true : sel.value;\n await rpc(\"setpolicy\", { views: { [sel.dataset.view]: value } });\n toast(sel.value === \"off\" ? \"Took down \" + sel.dataset.view : sel.dataset.view + \": \" + (sel.value === \"live\" ? \"on\" : sel.value === \"write\" ? \"on write\" : sel.value)); await loadViews(); await loadInfo();\n }));\n async function loadDumps() {\n const list = await rpc(\"listdumps\");\n const f = $(\"#dumpform\");\n if (policy) { f.dumps.value = policy.dumps || \"off\"; f.keep.value = policy.dumpsKeep || 7; }\n $(\"#dumps-count\").textContent = list.length || \"\";\n $(\"#dumps\").innerHTML = list.length ? list.map((d) => '
              • jsonl' + esc(d.name) + ' ' + d.events.toLocaleString() + \" events, \" + fmtBytes(d.bytes) + \"\" + ib(\"copy\", \"Download\", \"downloaddump\", d.name) + ib(\"trash\", \"Delete\", \"deletedump\", d.name, \"danger\") + \"
              • \").join(\"\") : '
              • no dumps yet
              • ';\n }\n // A dump is fetched with a signed request and handed to the browser as a file.\n async function downloadDump(name) {\n if (!signer.ready()) throw new Error(NO_SIGNER);\n const url = location.origin + \"/dumps/\" + name;\n const ev = await signer.signEvent({ kind: 27235, created_at: Math.floor(Date.now() / 1000), content: \"\", tags: [[\"u\", url], [\"method\", \"GET\"]] });\n const resp = await fetch(url, { headers: { authorization: \"Nostr \" + btoa(JSON.stringify(ev)) } });\n if (!resp.ok) throw new Error((await resp.json()).error || \"download failed\");\n const a = document.createElement(\"a\");\n a.href = URL.createObjectURL(await resp.blob()); a.download = host.split(\".\")[0] + \"-\" + name; a.click(); URL.revokeObjectURL(a.href);\n }\n // A plain member's own invites, when the owner lets members invite.\n async function loadMine() {\n const sec = $(\"#myinvites\");\n if (!me || !owner || myRole || !signer.ready()) { sec.classList.add(\"hidden\"); return; }\n let mine;\n try { mine = await rpc(\"listinvites\"); } catch { sec.classList.add(\"hidden\"); return; }\n sec.classList.remove(\"hidden\");\n const link = (code) => location.origin + \"/invite/\" + code;\n $(\"#mine\").innerHTML = mine.length ? mine.map((i) => '
              • inv…' + i.code.slice(-8) + ' ' + i.uses + (i.max_uses ? \"/\" + i.max_uses : \"\") + \" used, until \" + esc(fmtDay(i.expires_at)) + \"\" + ib(\"copy\", \"Copy link\", \"copy\", link(i.code)) + ib(\"x\", \"Revoke\", \"revokeinvite\", i.code) + \"
              • \").join(\"\") : '
              • no invites yet
              • ';\n }\n async function loadStorage() {\n storage = await rpc(\"storagestats\");\n pollJobs();\n loadViews();\n loadDumps().catch(() => {});\n const st = storage;\n const top = st.kinds.slice(0, 4), rest = st.kinds.slice(4).reduce((a, k) => a + k.bytes, 0);\n const parts = [...top.map((k, i) => [k.kind + \" \" + kindName(k.kind), \"k\" + (i + 1), k.bytes]), ...(rest ? [[\"other\", \"k5\", rest]] : [])];\n const total = st.eventBytes || 1;\n $(\"#s-bar\").innerHTML = parts.length ? parts.map(([n, c, b]) => '').join(\"\") : '';\n $(\"#s-legend\").innerHTML = parts.length ? parts.map(([n, c, b]) => '' + esc(n) + \" \" + Math.round(b * 100 / total) + \"%\").join(\"\") : \"no events yet\";\n const overhead = Math.max(0, st.databaseBytes - st.eventBytes);\n $(\"#s-totals\").innerHTML = [[\"events\", st.events.toLocaleString() + \" \" + fmtBytes(st.eventBytes) + \"\"], [\"index and overhead\", fmtBytes(overhead)], [\"files\", st.blobs.toLocaleString() + \" \" + fmtBytes(st.mediaBytes) + \"\"]]\n .map(([k, v]) => \"
                \" + k + \"\" + v + \"
                \").join(\"\");\n const any = st.retention.find((r) => r.kind === null);\n const own = (kind) => { const r = st.retention.find((x) => x.kind === kind); return r ? r.days : \"\"; };\n const row = (k) => {\n const key = k.kind === null ? \"\" : String(k.kind);\n const placeholder = k.kind === null ? \"forever\" : k.replaceable || !any ? \"forever\" : any.days + \" (everything else)\";\n const pill = k.kind === null ? \"everything else\" : '' + k.kind + \" \" + esc(kindName(k.kind));\n const cells = k.protected\n ? 'required'\n : ' days' + ib(\"check\", \"Save keep-for rule\", \"saveretention\", key) + ib(\"trash\", \"Purge\", \"purgekind\", key, \"danger\") + \"\";\n return '' + pill + '' + (k.n === undefined ? \"\" : k.n.toLocaleString()) + '' + (k.bytes === undefined ? \"\" : fmtBytes(k.bytes)) + '' + (k.oldest ? esc(fmtDay(k.oldest)) : \"\") + \"\" + cells + \"\";\n };\n $(\"#kinds tbody\").innerHTML = [...st.kinds, { kind: null, days: any ? any.days : 0 }].map(row).join(\"\");\n }\n\n let searchQuery = \"\";\n async function loadEvents(reset) {\n const list = searchQuery ? await rpc(\"searchevents\", searchQuery, 200) : await rpc(\"listrecentevents\", reset ? 50 : 200);\n $(\"#events tbody\").innerHTML = list.length ? list.map((e) => '' + esc(fmtTime(e.created_at)) + '' + e.kind + '' + av(e.pubkey) + key(e.pubkey) + '' + esc(e.content) + '' + ib(\"pin\", \"Pin\", \"pinevent\", e.id) + ib(\"trash\", \"Delete event\", \"deleteevent\", e.id) + ib(\"ban\", \"Ban event\", \"banevent\", e.id, \"danger\") + ib(\"banuser\", \"Ban author\", \"banpubkey\", e.pubkey, \"danger\") + \"\").join(\"\") : 'no events yet';\n $(\"#more\").classList.toggle(\"hidden\", searchQuery || list.length < 50);\n }\n $(\"#searchform\").onsubmit = guard(async (ev) => {\n searchQuery = ev.target.q.value.trim();\n $(\"#searchclear\").classList.toggle(\"hidden\", !searchQuery);\n await loadEvents(true);\n });\n $(\"#searchclear\").onclick = guard(async () => {\n searchQuery = \"\"; $(\"#searchform\").reset(); $(\"#searchclear\").classList.add(\"hidden\");\n await loadEvents(true);\n });\n async function loadPins() {\n const pins = await rpc(\"listpins\");\n $(\"#pins-count\").textContent = pins.length || \"\";\n $(\"#pins\").innerHTML = pins.length ? pins.map((t) => '
              • ' + (t[0] === \"e\" ? \"event\" : \"address\") + '' + esc(t[1].length > 40 ? t[1].slice(0, 16) + \"\\u2026\" + t[1].slice(-8) : t[1]) + \"\" + ib(\"copy\", \"Copy\", \"copy\", t[1]) + ib(\"x\", \"Unpin\", \"unpinevent\", t[1]) + \"
              • \").join(\"\") : '
              • nothing pinned
              • ';\n }\n $(\"#pinform\").onsubmit = guard(async (ev) => {\n await rpc(\"pinevent\", ev.target.id.value.trim()); ev.target.reset(); toast(\"Pinned\"); await loadPins();\n });\n\n // ---- actions ----\n const refresh = () => Promise.all([loadLists(), loadEvents(true), loadStorage(), loadPins()]);\n\n $(\"#copy\").onclick = async () => { await navigator.clipboard.writeText(wsURL); toast(\"copied \" + wsURL); };\n $(\"#signin\").onclick = guard(async () => {\n if (!window.nostr) throw new Error(\"No nostr extension found. Install one (Alby, nos2x, …) and reload, or use a remote signer.\");\n me = await window.nostr.getPublicKey();\n localStorage.setItem(\"me\", me);\n renderHeader(); await loadAdmin(); await loadPeople();\n });\n $(\"#signin46\").onclick = () => showRemote(null);\n $$(\".remote\").forEach((b) => { b.onclick = () => showRemote($(\"#\" + b.dataset.note)); });\n $(\"#nccopy\").onclick = async () => { await navigator.clipboard.writeText($(\"#nclink\").href); toast(\"Link copied; paste it into your signer app\"); };\n $(\"#bunkerform\").onsubmit = guard(async (ev) => {\n $(\"#remotenote\").textContent = \"Connecting…\";\n try { await connectBunker(ev.target.url.value); } catch (e) { $(\"#remotenote\").textContent = e.message; throw e; }\n $(\"#remotenote\").textContent = \"\"; ev.target.reset();\n await remoteDone();\n });\n $(\"#signout\").onclick = async () => {\n if (remote) { const r = remote; remote = null; try { await withTimeout(r.logout(), 5000, \"The signer\"); } catch { /* the session is gone either way */ } }\n localStorage.removeItem(\"nip46\");\n me = null; localStorage.removeItem(\"me\"); renderHeader(); await loadAdmin(); await loadPeople();\n };\n const claimNow = async (note) => {\n if (!signer.ready()) { note.textContent = \"Sign the claim with a nostr extension or a remote signer.\"; showRemote(note); return; }\n me = await signer.getPublicKey();\n const r = await rpc(\"claim\");\n if (!r.claimed) throw new Error(\"Somebody else claimed it first.\");\n localStorage.setItem(\"me\", me);\n toast(\"It's yours.\");\n await loadInfo(); await loadFuel(); await loadAdmin(); await loadPeople();\n if (r.converted && confirm(\"This relay began as a temporary one: anyone can write, and everything is deleted after 14 days. Switch to the default rules and keep everything from now on? Each rule can be changed later on the Rules and Storage tabs.\")) {\n await rpc(\"resetrules\"); toast(\"Rules reset\"); await loadInfo(); await loadAdmin();\n }\n };\n $(\"#claim\").onclick = guard(() => claimNow($(\"#claimnote\")));\n $(\"#claimlease\").onclick = guard(() => claimNow($(\"#leasenote\")));\n // Jobs run in the background; the table follows them while the tab is open.\n let jobsTimer = 0;\n const fmtJob = (j) => {\n const what = j.kind === \"mirror\" ? \"mirror site\" : j.kind === \"import\" ? \"import\" : j.label === \"backfill\" ? \"fetch my history\" : j.kind === \"pull\" ? \"pull\" : \"rebroadcast\";\n const f = [];\n if (j.filter.authors) f.push(j.filter.authors.length === 1 && j.filter.authors[0] === me ? \"my events\" : j.filter.authors.length + \" authors\");\n if (j.filter.kinds) f.push(\"kinds \" + j.filter.kinds.join(\", \"));\n if (j.filter.since) f.push(\"since \" + fmtDay(j.filter.since));\n const when = j.every ? \"every \" + (j.every === 24 ? \"day\" : j.every + \" h\") + (j.nextRun ? \", next \" + fmtTime(j.nextRun) : \"\") : \"once\";\n const l = j.last;\n const count = (stored, blobs, sent, refused) => (j.kind === \"mirror\" ? blobs.toLocaleString() + \" files mirrored\" : j.kind === \"import\" ? stored.toLocaleString() + \" events\" + ((j.last ? j.last.duplicates : j.duplicates) ? \", \" + (j.last ? j.last.duplicates : j.duplicates) + \" already here\" : \"\") : j.kind === \"pull\" ? stored.toLocaleString() + \" events\" + (blobs ? \", \" + blobs + \" files\" : \"\") : sent.toLocaleString() + \" sent\" + (refused ? \", \" + refused + \" refused\" : \"\"));\n const res = j.running ? \"running: \" + count(j.stored, j.blobs, j.sent, j.refused) + \"...\" : !l ? \"waiting\" : l.error ? \"failed: \" + l.error : count(l.stored, l.blobs, l.sent, l.refused) + (l.skipped ? \", \" + l.skipped + \" skipped\" : \"\") + \", \" + fmtTime(l.finishedAt);\n return \"\" + what + \"\" + j.relays.map(esc).join(\"
                \") + \"\" + (f.join(\", \") || \"everything\") + \"\" + when + \"\" + esc(res) + \"\" + (j.running ? \"\" : ib(\"undo\", \"Run now\", \"runjob\", j.id)) + ib(\"x\", \"Remove\", \"removejob\", j.id) + \"\";\n };\n async function pollJobs() {\n clearTimeout(jobsTimer);\n let jobs;\n try { jobs = await rpc(\"listjobs\"); } catch { return; }\n $(\"#jobs tbody\").innerHTML = jobs.length ? jobs.map(fmtJob).join(\"\") : 'no jobs yet';\n if (jobs.some((j) => j.running || (j.nextRun && j.nextRun <= Math.floor(Date.now() / 1000) + 1))) jobsTimer = setTimeout(pollJobs, 3000);\n }\n const urls = (s) => s.split(/[\\s,]+/).map((u) => u.trim()).filter(Boolean);\n const kindsOf = (s) => s.split(/[\\s,]+/).map((k) => parseInt(k, 10)).filter((k) => Number.isInteger(k) && k >= 0);\n $(\"#pullform\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n await rpc(\"addjob\", { kind: \"pull\", relays: [f.url.value.trim()], every: +f.every.value });\n toast(+f.every.value ? \"Mirror scheduled\" : \"Pull started\"); f.reset(); await pollJobs();\n });\n $(\"#backfillform\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n await rpc(\"backfill\", urls(f.relays.value));\n toast(\"Fetching your history\"); f.reset(); await pollJobs();\n });\n $(\"#pushform\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n const filter = {};\n const kinds = kindsOf(f.kinds.value); if (kinds.length) filter.kinds = kinds;\n const days = +f.days.value; if (days > 0) filter.since = Math.floor(Date.now() / 1000) - days * 86400;\n await rpc(\"addjob\", { kind: \"push\", relays: urls(f.targets.value), filter, every: +f.every.value });\n toast(\"Rebroadcast started\"); f.reset(); await pollJobs();\n });\n // ---- presets: writes, reads, kinds and keep-for rules in one click ----\n let presets = null;\n async function renderPresets() {\n if (!presets) { try { presets = await rpc(\"listpresets\"); } catch { presets = []; } }\n $(\"#presets\").innerHTML = presets.map((p) => '\").join(\"\");\n $(\"#presetsourcerow\").classList.toggle(\"hidden\", !presets.some((p) => p.source));\n }\n $(\"#presets\").addEventListener(\"click\", async (ev) => {\n const b = ev.target.closest(\"button[data-preset]\"); if (!b) return;\n const p = (presets || []).find((x) => x.name === b.dataset.preset); if (!p) return;\n if (!confirm(p.title + \": \" + p.about + \"\\n\\nThis replaces the writes and reads rules, the directory setting, the kind rules and the keep-for rules. Limits, identity, people and bans stay.\")) return;\n const source = $(\"#presetsource\").value.trim();\n if (p.source === \"required\" && !source) { $(\"#presetnote\").textContent = p.title + \" needs a source relay to mirror; enter its wss:// URL first.\"; return; }\n b.disabled = true;\n try { policy = await rpc(\"applypreset\", p.name, p.source && source ? { source } : undefined); $(\"#presetnote\").textContent = \"Now: \" + p.about + (policy.job ? \" Mirroring \" + source + \" every \" + policy.job.every + \" h.\" : \"\"); toast(p.title + \" applied\"); await loadInfo(); await loadAdmin(); }\n catch (e) { toast(e.message); } finally { b.disabled = false; }\n });\n\n // ---- wire me in: this relay in the owner's own lists ----\n // The lists are replaceable, so a fresh list with only this relay would\n // clobber the real one once it spread. Every publish starts from the\n // newest copy found here or on the indexers, verified when the signer\n // library is around, and adds or removes this relay in it.\n const INDEXERS = [\"wss://purplepag.es\", \"wss://relay.nostr.band\", \"wss://relay.damus.io\", \"wss://nos.lol\"];\n const LISTS = [\n { kind: 10002, tag: \"r\", title: \"Relay list\", nip: \"NIP-65\", about: \"where clients read your notes and send you mentions\" },\n { kind: 10050, tag: \"relay\", title: \"DM inbox\", nip: \"NIP-17\", about: \"where people send you private messages\" },\n { kind: 10007, tag: \"relay\", title: \"Search relays\", nip: \"NIP-51\", about: \"where clients run your searches\" },\n { kind: 10063, tag: \"server\", title: \"Blossom servers\", nip: \"BUD-03\", about: \"where clients upload and look for your files\" },\n ];\n const mineFor = (l) => (l.tag === \"server\" ? location.origin : wsURL);\n const normURL = (u) => { try { const x = new URL(String(u).trim()); return (x.host + x.pathname).replace(/\\/+$/, \"\").toLowerCase(); } catch { return String(u).trim().toLowerCase(); } };\n const isMine = (l, t) => t[0] === l.tag && normURL(t[1] || \"\") === normURL(mineFor(l));\n const listHas = (list, l) => !!list && list.tags.some((t) => isMine(l, t));\n // mergeList is pure: the newest list with this relay put first or taken out, every other tag kept.\n function mergeList(list, l, include) {\n const tags = (list ? list.tags : []).filter((t) => !isMine(l, t));\n if (include) tags.unshift([l.tag, mineFor(l)]);\n return { kind: l.kind, created_at: Math.floor(Date.now() / 1000), content: list ? list.content : \"\", tags };\n }\n const relaysIn = (list) => list.tags.filter((t) => (t[0] === \"r\" || t[0] === \"relay\") && /^wss?:\\/\\//i.test(t[1] || \"\")).map((t) => t[1].trim());\n // overWS opens one socket, sends one message, feeds answers to onMessage until it says done or time runs out.\n function overWS(url, ms, first, onMessage) {\n return new Promise((res) => {\n let ws = null, done = false, out = null;\n const finish = () => { if (done) return; done = true; clearTimeout(timer); try { if (ws) ws.close(); } catch { /* closed */ } res(out); };\n const timer = setTimeout(finish, ms);\n try { ws = new WebSocket(url); } catch { return finish(); }\n ws.onopen = () => ws.send(JSON.stringify(first));\n ws.onmessage = (m) => { let d; try { d = JSON.parse(m.data); } catch { return; } if (!Array.isArray(d)) return; if (onMessage(d, (v) => { out = v; })) finish(); };\n ws.onerror = finish; ws.onclose = finish;\n });\n }\n function fetchNewest(url, filter, ms) {\n let best = null;\n return overWS(url, ms, [\"REQ\", \"w\", filter], (d, set) => {\n if (d[0] === \"EVENT\" && d[1] === \"w\" && d[2] && (!best || d[2].created_at > best.created_at)) { best = d[2]; set(best); }\n return (d[0] === \"EOSE\" || d[0] === \"CLOSED\") && d[1] === \"w\";\n });\n }\n function publishTo(url, event, ms) {\n return overWS(url, ms, [\"EVENT\", event], (d, set) => { if (d[0] === \"OK\" && d[1] === event.id) { set({ url, ok: !!d[2], msg: d[3] || \"\" }); return true; } return false; })\n .then((r) => r || { url, ok: false, msg: \"no answer\" });\n }\n // bridge signs a NIP-98 request to this relay's HTTP door, so the owner's own reads and writes pass any read rule.\n async function bridge(path, body) {\n const url = location.origin + path, raw = JSON.stringify(body);\n const ev = await signer.signEvent({ kind: 27235, created_at: Math.floor(Date.now() / 1000), content: \"\", tags: [[\"u\", url], [\"method\", \"POST\"], [\"payload\", await sha256hex(raw)]] });\n const resp = await fetch(url, { method: \"POST\", headers: { \"content-type\": \"application/json\", authorization: \"Nostr \" + btoa(JSON.stringify(ev)) }, body: raw });\n const json = await resp.json();\n if (!resp.ok) throw new Error(json.error || \"HTTP \" + resp.status);\n return json;\n }\n const wire = {};\n function renderWire() {\n const pill = (state) => {\n const cls = state === \"listed\" ? \"on\" : state === \"failed\" ? \"bad\" : state === \"not listed\" ? \"off\" : \"\";\n const label = state === \"checking\" || state === \"publishing\" ? state + \"\\u2026\" : state;\n return '' + esc(label) + \"\";\n };\n $(\"#wire\").innerHTML = LISTS.map((l) => {\n const w = wire[l.kind] || { state: \"\", results: [], list: null };\n const busy = w.state === \"checking\" || w.state === \"publishing\";\n const btn = (act, cls, label) => '\";\n const buttons = w.state === \"listed\" ? btn(\"remove\", \"\", \"Remove this relay\") : btn(\"add\", \"pri\", \"Add this relay\") + btn(\"check\", \"\", w.state ? \"Check again\" : \"Check\");\n const n = w.list ? w.list.tags.filter((t) => t[0] === l.tag).length : 0;\n const from = w.list ? \"\" + (n === 1 ? \"1 entry\" : n + \" entries\") + \", \" + fmtTime(w.list.created_at) + \"\" : w.state && !busy ? \"no list found\" : \"\";\n const sent = (w.results || []).map((r) => '' + esc(r.url.replace(/^wss?:\\/\\//, \"\")) + (r.ok ? \"\" : \" failed\") + \"\").join(\"\");\n const meta = (w.state ? pill(w.state) : \"\") + from + sent;\n return '
                ' + l.title + ' ' + l.nip + \"
                \" + l.about + '
                ' + buttons + '
                ' + meta + \"
                \";\n }).join(\"\");\n }\n async function wireCheck(l) {\n const w = (wire[l.kind] = { state: \"checking\", list: null, results: [] }); renderWire();\n const filter = { kinds: [l.kind], authors: [me], limit: 1 };\n const found = [];\n try { found.push(...(await bridge(\"/query\", [filter]))); } catch { /* the relay may hold none */ }\n const remote = await Promise.all(INDEXERS.map((u) => fetchNewest(u, filter, 4000)));\n let lib = null; try { lib = await signerLib(); } catch { /* unverified lists are still the owner's own, by pubkey */ }\n for (const e of remote) if (e && e.pubkey === me && e.kind === l.kind && Array.isArray(e.tags) && (!lib || lib.verifyEvent(e))) found.push(e);\n w.list = found.sort((a, b) => b.created_at - a.created_at)[0] || null;\n w.state = listHas(w.list, l) ? \"listed\" : \"not listed\"; renderWire();\n }\n async function wirePublish(l, include) {\n if (!wire[l.kind] || !wire[l.kind].state || wire[l.kind].state === \"failed\") await wireCheck(l);\n const w = wire[l.kind]; w.state = \"publishing\"; w.results = []; renderWire();\n try {\n const signed = await signer.signEvent(mergeList(w.list, l, include));\n const here = await bridge(\"/events\", signed).then((r) => ({ url: wsURL, ok: !!r.accepted, msg: r.message || \"\" })).catch((e) => ({ url: wsURL, ok: false, msg: e.message }));\n const targets = [...new Set([...relaysIn(signed), ...INDEXERS])].filter((u) => normURL(u) !== normURL(wsURL));\n const rest = await Promise.all(targets.map((u) => publishTo(u, signed, 6000)));\n w.results = [here, ...rest]; w.list = signed; w.state = include ? \"listed\" : \"not listed\";\n toast((include ? \"Added to your \" : \"Removed from your \") + l.title.toLowerCase());\n } catch (e) { w.state = \"failed\"; w.results = [{ url: wsURL, ok: false, msg: e.message }]; toast(e.message); }\n renderWire();\n }\n $(\"#wire\").addEventListener(\"click\", (ev) => {\n const b = ev.target.closest(\"button[data-wire]\"); if (!b) return;\n const l = LISTS.find((x) => String(x.kind) === b.dataset.wire); if (!l) return;\n if (b.dataset.do === \"check\") wireCheck(l); else wirePublish(l, b.dataset.do === \"add\");\n });\n\n // ---- custom domains: this relay under a hostname the owner controls ----\n let domainSites = [];\n const domainOptions = (current = \"\") => [{ label: \"\", title: \"This relay\" }, ...domainSites.map((s) => ({ label: s.label, title: (s.d || (s.kind === 5128 ? \"snapshot\" : \"root\")) + \" / \" + key(s.author) })), ...(current && !domainSites.some((s) => s.label === current) ? [{ label: current, title: \"Site \" + current }] : [])].map((s) => '\").join(\"\");\n let domains = null; // null: not enabled on this host\n function renderDomains() {\n $(\"#domains\").innerHTML = (domains || []).map((d) => {\n const state = d.ready ? \"active\" : \"hostname \" + d.status.replace(/_/g, \" \") + \", certificate \" + d.sslStatus.replace(/_/g, \" \");\n const btn = (act, cls, label) => '\";\n const rows = d.ready ? \"\" : '
                ' + d.records.map((r) => \"\").join(\"\") + \"
                TypeNameValue
                \" + esc(r.type) + '' + esc(r.name) + '' + esc(r.value) + \"\" + esc(r.note) + \"
                \";\n return '
                ' + esc(d.host) + '' + esc(state) + \"\" + btn(\"check\", \"\", \"Check\") + btn(\"remove\", \"danger\", \"Remove\") + '
                \" + rows;\n }).join(\"\");\n }\n async function loadDomains() {\n try { [domains, domainSites] = await Promise.all([rpc(\"listdomains\"), rpc(\"listsites\")]); $(\"#adddomain select[name=site]\").innerHTML = domainOptions(); $(\"#domainnote\").textContent = domains.length ? \"\" : \"No custom domain yet.\"; $(\"#adddomain\").classList.remove(\"hidden\"); }\n catch (e) { domains = null; $(\"#domainnote\").textContent = /^unsupported/.test(e.message) ? \"Custom domains are not enabled on this host.\" : e.message; $(\"#adddomain\").classList.add(\"hidden\"); }\n renderDomains();\n }\n $(\"#adddomain\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n await rpc(\"adddomain\", f.host.value.trim(), f.site.value); f.reset(); toast(\"Domain added; now create the CNAME\"); await loadDomains();\n });\n $(\"#domains\").addEventListener(\"change\", guard(async (ev) => {\n const select = ev.target.closest(\"select[data-domain-site]\"); if (!select) return;\n await rpc(\"setdomainsite\", select.dataset.domainSite, select.value);\n toast(\"Domain destination saved\"); await loadDomains();\n }));\n $(\"#domains\").addEventListener(\"click\", async (ev) => {\n const b = ev.target.closest(\"button[data-domain]\"); if (!b) return;\n const host = b.dataset.domain;\n if (b.dataset.do === \"remove\" && !confirm(\"Remove \" + host + \"? Its certificate goes with it and the name stops answering.\")) return;\n b.disabled = true;\n try {\n if (b.dataset.do === \"remove\") { await rpc(\"removedomain\", host); toast(\"Removed\"); }\n else { const d = await rpc(\"checkdomain\", host); toast(d.ready ? host + \" is live\" : \"Not yet: \" + (d.status === \"active\" ? \"certificate pending\" : \"waiting for the CNAME\")); }\n await loadDomains();\n } catch (e) { toast(e.message); } finally { b.disabled = false; }\n });\n\n $(\"#access\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n const openKinds = f.openKinds.value.split(/[\\s,]+/).filter(Boolean).map(Number);\n if (openKinds.some((k) => !Number.isInteger(k) || k < 0 || k > 65535)) throw new Error(\"Open kinds must be whole numbers.\");\n policy = await rpc(\"setpolicy\", { writes: f.writes.value, reads: f.reads.value, openKinds, guestReplies: f.guestReplies.checked, minPow: +f.minPow.value, maxFuture: +f.maxFuture.value, maxLimit: +f.maxLimit.value, maxSubs: +f.maxSubs.value, maxMessageKB: +f.maxMessageKB.value, eventsPerMinute: +f.eventsPerMinute.value, reqsPerMinute: +f.reqsPerMinute.value, maxBlobMB: +f.maxBlobMB.value });\n toast(\"Rules saved\"); await loadInfo();\n });\n $(\"#notify\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n policy = await rpc(\"setpolicy\", { notify: { reports: f.reports.checked, fuel: f.fuel.checked, jobs: f.jobs.checked, succession: f.succession.checked, digest: f.digest.checked } });\n toast(\"Notifications saved\");\n });\n $(\"#notifytest\").onclick = guard(async () => {\n const r = await rpc(\"notifytest\");\n toast(r.sent ? \"Sent. Look for a message from the relay in your DMs.\" : \"Could not send.\");\n });\n $(\"#identity\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n const list = (v) => v.split(\",\").map((s) => s.trim()).filter(Boolean);\n policy = await rpc(\"setpolicy\", { name: f.name.value, contact: f.contact.value, description: f.description.value, icon: f.icon.value,\n banner: f.banner.value, postingPolicy: f.postingPolicy.value, privacyPolicy: f.privacyPolicy.value, tags: list(f.tags.value), languageTags: list(f.languageTags.value), relayCountries: list(f.relayCountries.value) });\n toast(\"Identity saved\"); await loadInfo(); await loadPeople(); loadCard();\n });\n $(\"#addmember\").onsubmit = guard(async (ev) => {\n const f = ev.target; const pk = npubToHex(f.pubkey.value); if (!pk) throw new Error(\"That is not a pubkey.\");\n await rpc(\"setmember\", pk, { name: f.name.value.trim() || null, note: f.note.value }); f.reset(); toast(\"Member added\"); await loadLists();\n });\n $(\"#addblock\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n await rpc(\"blockip\", f.ip.value.trim(), f.reason.value); f.reset(); toast(\"Blocked\"); await loadLists();\n });\n $(\"#wordsform\").onsubmit = guard(async (ev) => {\n const words = ev.target.words.value.split(\"\\n\").map((s) => s.trim()).filter(Boolean);\n const kept = await rpc(\"setblockedwords\", words);\n policy = await rpc(\"setpolicy\", { blockedWordsInTags: ev.target.inTags.checked });\n ev.target.words.value = kept.join(\"\\n\"); toast(kept.length ? kept.length + \" words blocked\" : \"No words blocked\");\n });\n $(\"#thresholdform\").onsubmit = guard(async (ev) => {\n policy = await rpc(\"setpolicy\", { reportThreshold: +ev.target.reportThreshold.value });\n toast(policy.reportThreshold ? \"Hidden after \" + policy.reportThreshold + \" reports\" : \"Never hidden by reports\"); await loadLists();\n });\n $(\"#addban\").onsubmit = guard(async (ev) => {\n const pk = npubToHex(ev.target.pubkey.value); if (!pk) throw new Error(\"That is not a pubkey.\");\n await rpc(\"banpubkey\", pk, ev.target.reason.value, ev.target.erase.checked); ev.target.reset(); toast(ev.target.erase.checked ? \"Banned and erased\" : \"Banned\"); await loadLists();\n });\n $(\"#mintinvite\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n const inv = await rpc(\"createinvite\", +f.ttl.value, +f.max.value, f.note.value);\n await navigator.clipboard.writeText(location.origin + \"/invite/\" + inv.code).catch(() => {});\n f.note.value = \"\"; toast(\"Invite created and copied\"); await loadLists();\n });\n $(\"#kindform\").onsubmit = guard(async (ev) => {\n const rule = ev.submitter.value; const k = +ev.target.kind.value;\n await rpc(rule === \"allow\" ? \"allowkind\" : \"disallowkind\", k); ev.target.reset(); toast((rule === \"allow\" ? \"Allowed kind \" : \"Blocked kind \") + k); await loadLists();\n });\n $(\"#more\").onclick = guard(() => loadEvents(false));\n $(\"#dumpform\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n policy = await rpc(\"setpolicy\", { dumps: f.dumps.value, dumpsKeep: Math.max(1, Math.min(60, Math.floor(+f.keep.value || 7))) });\n toast(policy.dumps === \"off\" ? \"Dumps off\" : \"Dumping \" + policy.dumps); await loadDumps();\n });\n $(\"#importform\").onsubmit = guard(async (ev) => {\n const file = ev.target.file.files[0]; if (!file) return;\n if (!signer.ready()) throw new Error(NO_SIGNER);\n if (file.size > 64 * 1024 * 1024) throw new Error(\"At most 64 MB per import.\");\n const body = await file.text();\n const url = location.origin + \"/import?name=\" + encodeURIComponent(file.name);\n const token = await signer.signEvent({ kind: 27235, created_at: Math.floor(Date.now() / 1000), content: \"\", tags: [[\"u\", url], [\"method\", \"PUT\"], [\"payload\", await sha256hex(body)]] });\n const resp = await fetch(url, { method: \"PUT\", headers: { authorization: \"Nostr \" + btoa(JSON.stringify(token)), \"content-type\": \"application/x-ndjson\" }, body });\n const r = await resp.json();\n if (!resp.ok) throw new Error(r.error || \"import failed\");\n ev.target.reset(); toast(\"Importing \" + fmtBytes(r.bytes)); await pollJobs();\n });\n $(\"#dumpnow\").onclick = guard(async () => { const d = await rpc(\"dumpnow\"); toast(\"Dumped \" + d.events.toLocaleString() + \" events\"); await loadStorage(); });\n $(\"#treeform\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n policy = await rpc(\"setpolicy\", { memberInvites: { depth: Math.max(0, Math.floor(+f.depth.value || 0)), quota: Math.max(0, Math.floor(+f.quota.value || 0)) } });\n toast(policy.memberInvites.depth ? \"Members may invite\" : \"Only you and moderators invite\");\n });\n $(\"#mintmine\").onclick = guard(async () => {\n const inv = await rpc(\"createinvite\", 259200, 1, \"\");\n await navigator.clipboard.writeText(location.origin + \"/invite/\" + inv.code).catch(() => {});\n toast(\"Invite created and copied\"); await loadMine();\n });\n $(\"#exportcfg\").onclick = guard(async () => {\n const cfg = await rpc(\"exportconfig\");\n const a = document.createElement(\"a\");\n a.href = URL.createObjectURL(new Blob([JSON.stringify(cfg, null, 2)], { type: \"application/json\" }));\n a.download = host.split(\".\")[0] + \".bind.ws.config.json\";\n a.click(); URL.revokeObjectURL(a.href);\n });\n $(\"#importcfg\").onclick = () => $(\"#cfgfile\").click();\n $(\"#cfgfile\").onchange = guard(async (ev) => {\n const file = ev.target.files[0]; if (!file) return;\n const cfg = JSON.parse(await file.text());\n const check = await rpc(\"importconfig\", cfg, { dryRun: true });\n const lines = check.changes.summary.length ? check.changes.summary.join(\"\\n\") : \"Nothing would change.\";\n const dropped = check.warnings.length ? \"\\n\\nNot taken:\\n\" + check.warnings.join(\"\\n\") : \"\";\n if (!confirm(\"Apply \" + file.name + \" to this relay?\\n\\n\" + lines + dropped)) { ev.target.value = \"\"; return; }\n await rpc(\"importconfig\", cfg); ev.target.value = \"\"; toast(\"Configuration imported\"); await loadInfo(); await loadAdmin(); await loadPeople();\n });\n // Succession: the status line under the heir form, from successionstatus.\n async function renderSuccession() {\n const el = $(\"#successionnote\"), f = $(\"#succession\");\n let st;\n try { st = await rpc(\"successionstatus\"); } catch { el.textContent = \"\"; return; }\n const sc = st.succession;\n $(\"#clearsuccession\").classList.toggle(\"hidden\", !sc);\n f.querySelector(\"button.btn:not(#clearsuccession)\").textContent = sc ? \"Change heir\" : \"Set heir\";\n if (!sc) { el.textContent = \"No heir named. Last signed in \" + fmtTime(st.ownerSeenAt) + \".\"; return; }\n if (f.heir.querySelector('[value=\"' + sc.heir + '\"]')) f.heir.value = sc.heir;\n f.afterDays.value = String(sc.afterDays);\n const who = (window.__members || []).find((m) => m.pubkey === sc.heir);\n const heir = who && who.name ? who.name + \"@\" + host : short(sc.heir);\n el.textContent = \"Heir: \" + heir + \". Last signed in \" + fmtTime(st.ownerSeenAt) + (st.silentDays ? \" (\" + st.silentDays + \" days ago)\" : \"\") + \". \" +\n (st.warning ? \"The warning month is running: the relay goes to \" + heir + \" on \" + fmtDay(st.handoverAt) + \" unless you sign in.\" : \"If you stay away, it goes to \" + heir + \" around \" + fmtDay(st.handoverAt) + \".\") +\n (st.log && st.log.length ? \" Handed over before: \" + st.log.map((l) => fmtDay(l.at) + \" to \" + short(l.to)).join(\", \") + \".\" : \"\");\n }\n $(\"#succession\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n await rpc(\"setsuccession\", { heir: f.heir.value, afterDays: +f.afterDays.value });\n toast(\"Heir set\"); await loadAdmin();\n });\n $(\"#clearsuccession\").onclick = guard(async () => {\n await rpc(\"clearsuccession\");\n toast(\"Heir cleared\"); await loadAdmin();\n });\n $(\"#transfer\").onsubmit = guard(async (ev) => {\n const pk = ev.target.pubkey.value; if (!pk) return;\n const name = host.split(\".\")[0];\n const typed = prompt(\"This hands \" + host + \" to \" + short(pk) + \" for good. You stay on as a moderator. Type the relay name (\" + name + \") to confirm.\");\n if (typed === null) return;\n if (typed.trim() !== name) { toast(\"That didn't match; nothing changed.\"); return; }\n await rpc(\"transferowner\", pk);\n toast(\"Transferred\");\n await loadInfo(); await loadAdmin(); await loadPeople();\n });\n // ---- fork: a new name with this relay's events, claim reserved for a key ----\n $(\"#forkform\").scope.onchange = (ev) => $(\"#forkkinds\").classList.toggle(\"hidden\", ev.target.value !== \"kinds\");\n $(\"#joinform\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n policy = await rpc(\"setpolicy\", { joinTerms: f.joinTerms.value, directoryPublic: f.directoryPublic.checked });\n toast(\"Saved\"); await loadInfo(); await loadPeople();\n });\n $(\"#forkform\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n const opts = { people: f.people.checked };\n if (f.name.value.trim()) opts.name = f.name.value.trim().toLowerCase();\n if (f.holder.value.trim()) { const pk = npubToHex(f.holder.value); if (!pk) throw new Error(\"That is not a pubkey.\"); opts.holder = pk; }\n if (f.scope.value === \"mine\") opts.filter = { authors: [me] };\n if (f.scope.value === \"kinds\") { const kinds = f.kinds.value.split(/[\\s,]+/).filter(Boolean).map(Number); if (!kinds.length || kinds.some((k) => !Number.isInteger(k) || k < 0)) throw new Error(\"Give kinds as numbers.\"); opts.filter = { kinds }; }\n if (!confirm(\"Fork this relay into a new name\" + (opts.name ? \" (\" + opts.name + \")\" : \"\") + \"? It pulls \" + (f.scope.value === \"all\" ? \"everything\" : f.scope.value === \"mine\" ? \"your events\" : \"the chosen kinds\") + (opts.people ? \" and the people\" : \"\") + \", and only \" + (opts.holder ? \"that key\" : \"you\") + \" can claim it.\")) return;\n const r = await rpc(\"forkrelay\", opts);\n $(\"#forknote\").textContent = r.handover + \" Expires \" + fmtTime(r.expires_at) + \".\";\n $(\"#forkurl\").textContent = r.console;\n $(\"#forkresult\").classList.remove(\"hidden\");\n toast(\"Forked to \" + r.name);\n });\n $(\"#forkcopy\").onclick = async () => { await navigator.clipboard.writeText($(\"#forkurl\").textContent); toast(\"copied\"); };\n $(\"#deleterelay\").onclick = guard(async () => {\n const name = host.split(\".\")[0];\n const typed = prompt(\"This deletes everything on \" + host + \" and gives the name up. Type the relay name (\" + name + \") to confirm.\");\n if (typed === null) return;\n if (typed.trim() !== name) { toast(\"That didn't match; nothing was deleted.\"); return; }\n await rpc(\"deleterelay\", name);\n localStorage.removeItem(\"me\");\n location.href = \"/\";\n });\n $(\"#topup\").onsubmit = guard((ev) => topUp(+ev.target.sats.value));\n $(\"#inv-copy\").onclick = async () => { await navigator.clipboard.writeText($(\"#inv-text\").value); toast(\"invoice copied\"); };\n $$(\"button[data-copy]\").forEach((b) => { b.onclick = async () => { await navigator.clipboard.writeText(b.dataset.copy === \"ws\" ? wsURL : location.origin); toast(\"copied\"); }; });\n document.addEventListener(\"click\", async (ev) => {\n const b = ev.target.closest(\"button[data-act]\"); if (!b) return;\n const act = b.dataset.act, id = b.dataset.id;\n if (act === \"copy\") { await navigator.clipboard.writeText(id); toast(\"copied\"); return; }\n if ((act === \"banpubkey\" || act === \"banevent\" || act === \"resolve:ban\") && !confirm(act === \"banevent\" ? \"Delete this event and refuse it forever?\" : \"Ban this author and refuse everything they post?\")) return;\n const erase = (act === \"banpubkey\" || act === \"resolve:ban\") && confirm(\"Also erase everything they wrote and uploaded here?\");\n if (act === \"deleteblob\" && !confirm(\"Delete this file for good?\")) return;\n if (act === \"deletedump\" && !confirm(\"Delete this dump?\")) return;\n if (act === \"downloaddump\") { b.disabled = true; try { await downloadDump(id); } catch (e) { toast(e.message); } finally { b.disabled = false; } return; }\n if ((act === \"removemember\" || act === \"banpubkey\") && (window.__members || []).some((m) => m.invited_by === id) && confirm(\"Also remove everyone this member invited, and everyone they invited in turn?\")) {\n b.disabled = true;\n try { const r = await rpc(\"removesubtree\", id); if (act === \"banpubkey\") await rpc(\"banpubkey\", id, \"\", erase); toast(\"Removed \" + r.removed.length); await refresh(); } catch (e) { toast(e.message); } finally { b.disabled = false; }\n return;\n }\n if (act === \"removejob\" && !confirm(\"Remove this job?\")) return;\n if (act === \"purgekind\") {\n const kind = id === \"\" ? null : +id;\n const label = kind === null ? \"everything without its own rule\" : kindName(kind) + \" (kind \" + kind + \")\";\n const typed = prompt(\"Purge \" + label + \" older than how many days? 0 purges all of them. This cannot be undone.\", \"30\");\n if (typed === null) return;\n const days = Math.max(0, Math.floor(+typed || 0));\n b.disabled = true;\n try { const r = await rpc(\"purgekind\", kind, days); toast(\"Purged \" + r.deleted.toLocaleString() + \" events\"); await refresh(); } catch (e) { toast(e.message); } finally { b.disabled = false; }\n return;\n }\n if (act === \"saveretention\") {\n const kind = id === \"\" ? null : +id;\n const days = Math.max(0, Math.floor(+b.closest(\"tr\").querySelector(\".days\").value || 0));\n b.disabled = true;\n try { await rpc(\"setretention\", kind, days); toast(days ? \"Kept for \" + days + \" days\" : \"Kept forever\"); await loadStorage(); await loadInfo(); } catch (e) { toast(e.message); } finally { b.disabled = false; }\n return;\n }\n b.disabled = true;\n try {\n if (act === \"savemember\") { const tr = b.closest(\"tr\"), role = tr.querySelector(\"select.role\"), keep = tr.querySelector(\".keep\"), cap = tr.querySelector(\".cap\"); await rpc(\"setmember\", id, { name: tr.querySelector(\".name\").value.trim() || null, note: tr.querySelector(\".note\").value, ...(role ? { role: role.value } : {}), ...(keep ? { keepDays: Math.max(0, Math.floor(+keep.value || 0)), maxBytes: Math.max(0, Math.floor(+cap.value || 0)) * 1024 } : {}) }); }\n else if (act.startsWith(\"resolve:\")) await rpc(\"resolvereport\", id, act.slice(8), erase);\n else if (act === \"banpubkey\") await rpc(\"banpubkey\", id, \"\", erase);\n else await rpc(act, act === \"unrulekind\" ? +id : id, \"\");\n toast(\"Done\"); await (myRole ? refresh() : loadMine());\n if (act === \"pinevent\" || act === \"unpinevent\") await loadPins();\n } catch (e) { toast(e.message); } finally { b.disabled = false; }\n });\n\n // The share block: the card picture, the group naddr and its QR.\n let card = null;\n async function loadCard() {\n try {\n card = await (await fetch(\"/card.json\", { cache: \"no-store\" })).json();\n $(\"#cardimg\").src = \"/card.svg?t=\" + Date.now();\n $(\"#naddr\").textContent = card.naddr || \"\";\n const q = $(\"#naddrqr\");\n if (card.naddr) { q.src = \"/qr.svg?text=\" + encodeURIComponent(card.naddr); q.classList.remove(\"hidden\"); } else q.classList.add(\"hidden\");\n } catch { /* the card is decoration */ }\n renderApps();\n }\n // The app rows on the Connect section: one per client people actually use,\n // with the link that lands on this relay in it. Relay apps take the relay\n // or the group address; feed apps take the owner's profile with this relay\n // as the hint, since they have no notion of opening a relay.\n function renderApps() {\n const el = $(\"#apps\"); if (!el) return;\n const enc = encodeURIComponent;\n const nprofile = card && card.nprofile ? card.nprofile : \"\";\n const naddr = card && card.naddr ? card.naddr : \"\";\n const whose = me && owner && me === owner ? \"your\" : \"the owner's\";\n const link = (label, href) => '' + label + \"\";\n const app = (label, uri) => '' + label + \"\";\n const copy = (label, text) => '\";\n const row = (name, where, note, acts) => '
                ' + name + \"\" + where + \"

                \" + note + '

                ' + acts.filter(Boolean).join(\"\") + \"
                \";\n const profileNote = \"Opens \" + whose + \" profile with this relay attached.\";\n const groups = [\n [\"As a place\", \"These open the relay itself: its feed, its people, its group.\", [\n row(\"Jumble\", \"web\", \"A feed of everything on this relay.\", [link(\"Open\", \"https://jumble.social/?r=\" + enc(wsURL))]),\n row(\"Coracle\", \"web\", \"The relay's page: its feed and its people.\", [link(\"Open\", \"https://coracle.social/relays/\" + enc(host))]),\n row(\"Flotilla\", \"web, phone\", \"The relay as a space, with the group as a room.\", [link(\"Open\", \"https://app.flotilla.social/spaces/\" + enc(host)), naddr && app(\"Open group\", \"nostr:\" + naddr)]),\n row(\"0xchat\", \"phone\", \"The group, in a chat app.\", [naddr && app(\"Open group\", \"nostr:\" + naddr), naddr && copy(\"Copy naddr\", naddr)]),\n row(\"noStrudel\", \"web\", \"Relays, add this one, then open its page.\", [copy(\"Copy relay URL\", wsURL)]),\n ]],\n [\"Find me here\", \"Feed apps have no relay pages. They meet this relay through a profile link that names it, then keep it once it is in the relay settings.\", [\n row(\"Primal\", \"web, phone\", profileNote, [nprofile && link(\"Open\", \"https://primal.net/p/\" + nprofile), nprofile && app(\"Open in app\", \"nostr:\" + nprofile)]),\n row(\"YakiHonne\", \"web, phone\", profileNote, [nprofile && link(\"Open\", \"https://yakihonne.com/profile/\" + nprofile), nprofile && app(\"Open in app\", \"nostr:\" + nprofile)]),\n row(\"Damus\", \"iPhone\", profileNote + \" Then Settings, Relays.\", [nprofile && app(\"Open in app\", \"nostr:\" + nprofile), copy(\"Copy relay URL\", wsURL)]),\n row(\"Amethyst\", \"Android\", profileNote + \" Then Relays in the drawer.\", [nprofile && app(\"Open in app\", \"nostr:\" + nprofile), copy(\"Copy relay URL\", wsURL)]),\n row(\"Nostur\", \"iPhone, Mac\", profileNote + \" Then Settings, Relays.\", [nprofile && app(\"Open in app\", \"nostr:\" + nprofile), copy(\"Copy relay URL\", wsURL)]),\n ]],\n ];\n el.innerHTML = groups.map(([h, note, rows]) => '

                ' + h + '

                ' + note + '

                ' + rows.join(\"\") + \"
                \").join(\"\");\n $(\"#apps-ws\").textContent = wsURL;\n const tile = (label, text) => '
                ' + label + '\"QR
                ';\n $(\"#phones\").innerHTML = [nprofile && tile(\"Find me here, for a phone\", \"nostr:\" + nprofile), naddr && tile(\"The group, for a phone\", \"nostr:\" + naddr)].filter(Boolean).join(\"\");\n }\n // The folds are a group: opening one closes the rest. Browsers with the\n // details name attribute do this themselves; this covers the others.\n $$(\".folds details\").forEach((d) => d.addEventListener(\"toggle\", () => { if (d.open) $$(\".folds details\").forEach((o) => { if (o !== d && o.open) o.open = false; }); }));\n document.addEventListener(\"click\", async (ev) => {\n const b = ev.target.closest(\"button[data-copytext]\"); if (!b) return;\n try { await navigator.clipboard.writeText(b.dataset.copytext); toast(\"copied\"); } catch { /* no clipboard */ }\n });\n $(\"#copynaddr\").onclick = async () => { if (!card || !card.naddr) return; await navigator.clipboard.writeText(card.naddr); toast(\"copied naddr\"); };\n $(\"#copyembed\").onclick = async () => { await navigator.clipboard.writeText('\"''); toast(\"copied embed\"); };\n\n // A click on a key copies it; a double-click selects the whole key so the usual copy shortcut takes it too.\n document.addEventListener(\"dblclick\", (ev) => {\n const k = ev.target.closest(\".key\"); if (!k) return;\n const s = window.getSelection(), r = document.createRange(); r.selectNodeContents(k.querySelector(\".full\")); s.removeAllRanges(); s.addRange(r);\n });\n document.addEventListener(\"click\", async (ev) => {\n const k = ev.target.closest(\".key\"); if (!k || ev.detail > 1 || String(window.getSelection())) return;\n try { await navigator.clipboard.writeText(k.title); toast(\"copied \" + k.dataset.short); } catch { /* no clipboard */ }\n });\n // ---- boot ----\n try { await loadInfo(); } catch { renderHeader(); }\n await loadFuel();\n await loadCard();\n me = localStorage.getItem(\"me\");\n if (me && await resumeRemote()) { /* a remote session answers for itself when first used */ }\n else if (me && window.nostr) { try { const pk = await window.nostr.getPublicKey(); if (pk !== me) me = null; } catch { me = null; } }\n else if (me) me = null;\n renderHeader();\n renderApps();\n await loadAdmin();\n await loadPeople();\n})();\n"; +export const CONSOLE_JS = "(async () => {\n const $ = (s) => document.querySelector(s);\n const $$ = (s) => document.querySelectorAll(s);\n const host = location.host;\n const wsURL = (location.protocol === \"https:\" ? \"wss://\" : \"ws://\") + host;\n const rpcURL = location.origin + \"/\";\n let info = null, me = null, owner = \"\", policy = null, fuel = null, people = null, myRole = \"\";\n\n const toast = (msg) => { const t = $(\"#toast\"); t.textContent = msg; t.classList.add(\"show\"); clearTimeout(t._t); t._t = setTimeout(() => t.classList.remove(\"show\"), 2600); };\n // guard wraps a handler: disables the button, shows errors as toasts. Defined first, since handlers below use it.\n const guard = (fn) => async (ev) => { ev.preventDefault(); const b = ev.submitter || ev.target; if (b) b.disabled = true; try { await fn(ev); } catch (e) { toast(e.message); } finally { if (b) b.disabled = false; } };\n const short = (hex) => hex ? hex.slice(0, 8) + \"…\" + hex.slice(-4) : \"\";\n // key shows a key short but keeps the whole of it in the DOM: selecting, double-clicking or clicking it copies the full hex.\n const key = (hex) => hex ? '' + hex + '' : '';\n const hue = (hex) => (parseInt(hex.slice(0, 2), 16) * 360 / 256).toFixed(0) + \"deg\";\n const av = (hex) => '';\n const fmtBytes = (n) => n < 1e6 ? (n / 1e3).toFixed(0) + \" KB\" : n < 1e9 ? (n / 1e6).toFixed(1) + \" MB\" : (n / 1e9).toFixed(2) + \" GB\";\n const fmtHours = (ms) => ms < 3600e3 ? Math.round(ms / 60e3) + \" min\" : (ms / 3600e3).toFixed(ms < 36e6 ? 1 : 0) + \" h\";\n const fuelOver = () => !!fuel && (fuel.eventBytes > fuel.freeEventBytes || fuel.mediaBytes > fuel.freeMediaBytes || fuel.activeMs > fuel.freeActiveMs || fuel.rowsWritten > fuel.freeRowsWritten);\n const fmtTime = (t) => t ? new Date(t * 1000).toLocaleString(undefined, { month: \"short\", day: \"numeric\", hour: \"2-digit\", minute: \"2-digit\" }) : \"–\";\n const fmtDay = (t) => t ? new Date(t * 1000).toLocaleDateString(undefined, { month: \"short\", day: \"numeric\" }) : \"–\";\n const ago = (t) => { const s = Math.max(0, Math.floor(Date.now() / 1000) - t); return s < 60 ? \"just now\" : s < 3600 ? Math.floor(s / 60) + \" min\" : s < 86400 ? Math.floor(s / 3600) + \" h\" : Math.floor(s / 86400) + \" d\"; };\n const esc = (s) => String(s ?? \"\").replace(/[&<>\"']/g, (c) => ({ \"&\": \"&\", \"<\": \"<\", \">\": \">\", '\"': \""\", \"'\": \"'\" })[c]);\n\n const IC = {\n x: '',\n undo: '',\n check: '',\n trash: '',\n ban: '',\n banuser: '',\n eye: '',\n lock: '',\n pen: '',\n people: '',\n person: '',\n gauge: '',\n bolt: '',\n copy: '',\n pin: '',\n };\n const ib = (icon, label, act, id, extra) => '\";\n\n const CH = \"qpzry9x8gf2tvdw0s3jn54khce6mua7l\";\n function npubToHex(s) {\n s = s.trim().toLowerCase();\n if (/^[0-9a-f]{64}$/.test(s)) return s;\n if (!s.startsWith(\"npub1\")) return null;\n const data = s.slice(5, -6).split(\"\").map((c) => CH.indexOf(c));\n if (data.some((d) => d < 0)) return null;\n let bits = 0, acc = 0, out = [];\n for (const d of data) { acc = (acc << 5) | d; bits += 5; if (bits >= 8) { bits -= 8; out.push((acc >> bits) & 255); } }\n return out.length === 32 ? out.map((b) => b.toString(16).padStart(2, \"0\")).join(\"\") : null;\n }\n\n async function sha256hex(s) {\n const b = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(s));\n return [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n }\n // ---- signing: a NIP-07 extension, or a NIP-46 remote signer ----\n // The remote path loads the bundled library on first use; its session\n // (client key, signer pubkey, relays) lives in localStorage until sign-out.\n let remote = null, lib = null, pendingNote = null;\n const NO_SIGNER = \"Install a nostr extension (Alby, nos2x, …) or connect a remote signer.\";\n const withTimeout = (p, ms, what) => Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error(what + \" did not answer; is the signer app open?\")), ms))]);\n const signer = {\n ready: () => !!remote || !!window.nostr,\n async getPublicKey() { if (remote) return withTimeout(remote.getPublicKey(), 20000, \"The remote signer\"); if (window.nostr) return window.nostr.getPublicKey(); throw new Error(NO_SIGNER); },\n async signEvent(ev) { if (remote) return withTimeout(remote.signEvent(ev), 60000, \"The remote signer\"); if (window.nostr) return window.nostr.signEvent(ev); throw new Error(NO_SIGNER); },\n };\n async function signerLib() {\n if (lib) return lib;\n if (!window.NostrSigner) await new Promise((res, rej) => { const s = document.createElement(\"script\"); s.src = window.SIGNER_URL || \"/signer.js\"; s.onload = res; s.onerror = () => rej(new Error(\"Could not load the signer library.\")); document.head.appendChild(s); });\n return (lib = window.NostrSigner);\n }\n const onauth = (u) => window.open(u, \"_blank\");\n // The signer conversation rides this relay, and a relay may ask the socket to\n // authenticate before it delivers kind 24133 to its parties; answer with the\n // session's own key.\n const authPool = (L, sk) => new L.SimplePool({ automaticallyAuth: () => (evt) => Promise.resolve(L.finalizeEvent(evt, sk)) });\n const saveSession = (sk, s, secret) => localStorage.setItem(\"nip46\", JSON.stringify({ sk: lib.bytesToHex(sk), pubkey: s.bp.pubkey, relays: s.bp.relays, secret: secret || null }));\n async function resumeRemote() {\n const raw = localStorage.getItem(\"nip46\");\n if (!raw) return false;\n try {\n const s = JSON.parse(raw); const L = await signerLib();\n remote = L.BunkerSigner.fromBunker(L.hexToBytes(s.sk), { pubkey: s.pubkey, relays: s.relays, secret: s.secret }, { onauth, pool: authPool(L, L.hexToBytes(s.sk)) });\n return true;\n } catch { localStorage.removeItem(\"nip46\"); return false; }\n }\n async function connectBunker(input) {\n const L = await signerLib();\n const bp = await L.parseBunkerInput(input.trim());\n if (!bp) throw new Error(\"That is not a bunker:// URL.\");\n if (!bp.relays.length) throw new Error(\"The bunker URL names no relay.\");\n const sk = L.generateSecretKey();\n const s = L.BunkerSigner.fromBunker(sk, bp, { onauth, pool: authPool(L, sk) });\n await withTimeout(s.connect({ name: host, url: location.origin }), 60000, \"The signer\");\n await Promise.race([s.switchRelays(), new Promise((r) => setTimeout(r, 3000))]);\n remote = s; saveSession(sk, s, bp.secret);\n }\n // The nostrconnect:// flow: this relay carries the traffic, so no third relay is involved.\n let ncPending = null;\n async function offerNostrConnect() {\n if (ncPending) return ncPending;\n const L = await signerLib();\n const sk = L.generateSecretKey();\n const secret = L.bytesToHex(crypto.getRandomValues(new Uint8Array(8)));\n const uri = L.createNostrConnectURI({ clientPubkey: L.getPublicKey(sk), relays: [wsURL], secret, name: host, url: location.origin, perms: [\"sign_event:27235\", \"sign_event:9734\"] });\n $(\"#nclink\").href = uri; $(\"#ncnote\").textContent = \"\";\n $(\"#ncqr\").src = \"/qr.svg?text=\" + encodeURIComponent(uri); $(\"#ncqr\").classList.remove(\"hidden\");\n ncPending = L.BunkerSigner.fromURI(sk, uri, { onauth, pool: authPool(L, sk) }, 600000).then((s) => { remote = s; saveSession(sk, s, secret); ncPending = null; return s; }, (e) => { ncPending = null; throw e; });\n return ncPending;\n }\n async function remoteDone() {\n me = await signer.getPublicKey();\n localStorage.setItem(\"me\", me);\n $(\"#remotesec\").classList.add(\"hidden\");\n toast(\"Remote signer connected\");\n if (pendingNote && !owner) { const n = pendingNote; pendingNote = null; await claimNow(n); return; }\n pendingNote = null;\n renderHeader(); await loadAdmin(); await loadPeople();\n }\n function showRemote(note) {\n pendingNote = note || null;\n $(\"#remotesec\").classList.remove(\"hidden\");\n $(\"#remotesec\").scrollIntoView({ behavior: \"smooth\", block: \"start\" });\n offerNostrConnect().then(remoteDone).catch((e) => { $(\"#ncnote\").textContent = e.message; });\n }\n\n async function rpc(method, ...params) {\n if (!signer.ready()) throw new Error(NO_SIGNER);\n const body = JSON.stringify({ method, params });\n const ev = await signer.signEvent({ kind: 27235, created_at: Math.floor(Date.now() / 1000), content: \"\", tags: [[\"u\", rpcURL], [\"method\", \"POST\"], [\"payload\", await sha256hex(body)]] });\n const resp = await fetch(rpcURL, { method: \"POST\", headers: { \"content-type\": \"application/nostr+json+rpc\", authorization: \"Nostr \" + btoa(JSON.stringify(ev)) }, body });\n const json = await resp.json();\n if (json.error) throw new Error(json.error);\n return json.result;\n }\n\n // ---- front of house ----\n // urlish shows a URL as a short link: the host and the start of the path, the whole thing on hover and as the target.\n class Html { constructor(s) { this.s = s; } }\n const urlish = (u) => {\n if (!u) return \"\";\n let label = u; try { const x = new URL(u); label = x.host + (x.pathname.length > 1 ? x.pathname.slice(0, 18) + (x.pathname.length > 18 ? \"\\u2026\" : \"\") : \"\"); } catch { /* not a URL */ }\n if (!/^https?:\\/\\//.test(u)) return u;\n return new Html('' + esc(label) + \"\");\n };\n function renderHeader() {\n const name = (info && info.name) || host.split(\".\")[0];\n $(\"#title\").textContent = name;\n document.title = name + \" - relay\";\n $(\"#url\").textContent = wsURL;\n $(\"#d-ws\").textContent = wsURL; $(\"#d-blossom\").textContent = location.origin; $(\"#d-nip05\").textContent = \"you@\" + host;\n $(\"#nip05-example\").textContent = \"alice@\" + host;\n const desc = (info && info.description) || \"\";\n $(\"#desc\").textContent = desc; $(\"#desc\").classList.toggle(\"hidden\", !desc);\n // What the owner declared about the relay, on the page, not only in the document clients read.\n const img = (id, url) => { const el = $(id); if (url) el.src = url; el.classList.toggle(\"hidden\", !url); };\n img(\"#bannerimg\", info?.banner); $(\"#banner\").classList.toggle(\"hidden\", !info?.banner);\n img(\"#iconimg\", info?.icon);\n const meta = [];\n for (const t of info?.tags || []) meta.push('' + esc(t) + \"\");\n const where = [...(info?.language_tags || []), ...(info?.relay_countries || [])];\n if (where.length) meta.push(\"\" + esc(where.join(\", \")) + \"\");\n const link = (label, href) => href ? '' + label + \"\" : \"\";\n const contact = info?.contact ? (/^(mailto:|https?:\\/\\/)/.test(info.contact) ? link(\"Contact\", info.contact) : \"\" + esc(info.contact) + \"\") : \"\";\n for (const x of [contact, link(\"Terms\", info?.terms_of_service), link(\"Posting policy\", info?.posting_policy), link(\"Privacy\", info?.privacy_policy)]) if (x) meta.push(x);\n $(\"#metarow\").innerHTML = meta.join('|'); $(\"#metarow\").classList.toggle(\"hidden\", meta.length === 0);\n $(\"#frontsec\").classList.toggle(\"hidden\", !desc && meta.length === 0);\n owner = (info && info.pubkey) || \"\";\n const isOwner = !!me && me === owner;\n const lease = !owner && info && info.lease ? info.lease : null;\n $(\"#ownerline\").innerHTML = owner ? 'run by ' + key(owner) + \"\" : lease ? \"temporary until \" + fmtDay(lease.expires_at) : \"unclaimed\";\n $(\"#owner-av\").classList.toggle(\"hidden\", !owner);\n if (owner) $(\"#owner-av\").style.setProperty(\"--h\", hue(owner));\n $(\"#who\").textContent = me ? (isOwner ? \"(that's you)\" : \"\") : \"\";\n $(\"#unclaimed\").classList.toggle(\"hidden\", !!owner || !!lease);\n $(\"#leased\").classList.toggle(\"hidden\", !lease);\n if (lease) {\n $(\"#lease-until\").textContent = fmtTime(lease.expires_at);\n $(\"#leasenote\").textContent = lease.holder ? \"Reserved for the key that asked for it; sign with that key.\" : \"\";\n }\n $(\"#signin\").classList.toggle(\"hidden\", !!me || !owner);\n $(\"#signin46\").classList.toggle(\"hidden\", !!me || !owner);\n $(\"#signout\").classList.toggle(\"hidden\", !me);\n $(\"#about\").innerHTML = [\n [\"Name\", info?.name], [\"Description\", info?.description], [\"Contact\", info?.contact], [\"Owner\", owner ? short(owner) : \"\"], [\"Relay key\", info?.self ? short(info.self) : \"\"], [\"Software\", urlish(info?.software)], [\"Version\", info?.version],\n [\"Max query\", info?.limitation?.max_limit], [\"Auth required\", String(!!info?.limitation?.auth_required)], [\"Restricted writes\", String(!!info?.limitation?.restricted_writes)], [\"Min PoW\", info?.limitation?.min_pow_difficulty || 0],\n [\"Tags\", info?.tags?.join(\", \")], [\"Languages\", info?.language_tags?.join(\", \")], [\"Countries\", info?.relay_countries?.join(\", \")],\n [\"Terms\", urlish(info?.terms_of_service)], [\"Posting policy\", urlish(info?.posting_policy)], [\"Privacy policy\", urlish(info?.privacy_policy)], [\"Icon\", urlish(info?.icon)], [\"Banner\", urlish(info?.banner)],\n [\"NIPs\", info?.supported_nips?.join(\" \")],\n ].map(([k, v]) => \"
                \" + k + \"\" + (v === undefined || v === \"\" ? '–' : v instanceof Html ? v.s : esc(v)) + \"
                \").join(\"\");\n renderCare();\n }\n\n function renderCare() {\n const g = (icon, label, off) => '' + IC[icon] + \"\" + label + \"\";\n const writes = policy ? policy.writes : (info?.limitation?.restricted_writes ? \"allowlist\" : \"open\");\n const reads = policy ? policy.reads : (info?.limitation?.auth_required ? \"auth\" : \"open\");\n let out = writes === \"owner\" ? g(\"person\", \"only owner writes\") : writes === \"allowlist\" ? g(\"people\", \"members write\") : writes === \"wot\" ? g(\"people\", \"members and follows write\") : g(\"pen\", \"anyone writes\");\n out += reads === \"members\" ? g(\"people\", \"members read\") : reads === \"auth\" ? g(\"lock\", \"sign in to read\") : g(\"eye\", \"anyone reads\");\n if (fuel) {\n const over = fuelOver();\n out += fuel.outOfFuel ? g(\"gauge\", \"out of fuel\", true) : over ? g(\"bolt\", \"burning sats\") : g(\"gauge\", \"on free allowance\");\n }\n $(\"#care\").innerHTML = out;\n }\n\n async function loadPeople() {\n try { people = await (await fetch(\"/people\")).json(); } catch { return; }\n const isOwner = !!me && me === owner;\n let list = people.people || [];\n if (!people.public && isOwner && policy) list = (window.__members || []);\n $(\"#peoplesec\").classList.toggle(\"hidden\", !owner || list.length === 0);\n $(\"#people-note\").classList.toggle(\"hidden\", people.public);\n $(\"#people-count\").textContent = list.length || \"\";\n $(\"#dir\").innerHTML = list.map((m) => '' + av(m.pubkey) + '' + (m.name ? esc(m.name) + \"@\" + host : key(m.pubkey)) + \"\" + (m.role === \"owner\" ? 'owner' : \"\") + \"\").join(\"\");\n }\n\n async function loadInfo() {\n info = await (await fetch(\"/\", { headers: { accept: \"application/nostr+json\" } })).json();\n renderHeader();\n const git = info.supported_grasps?.includes(\"GRASP-01\");\n $(\"#git-connect\").classList.toggle(\"hidden\", !git);\n const clone = \"git clone '\" + location.origin + \"//.git'\";\n $(\"#git-clone\").textContent = clone;\n $(\"#git-copy\").dataset.copytext = clone;\n renderApps();\n }\n\n async function loadFuel() {\n try { fuel = await (await fetch(\"/fuel\")).json(); } catch { return; }\n $(\"#fuelsec\").classList.toggle(\"hidden\", !owner);\n const pct = (used, free) => Math.min(100, Math.round((used / Math.max(free, 1)) * 100));\n const gauge = (id, used, free, text) => { const g = $(\"#g-\" + id), share = free ? used / free : 0; g.style.width = pct(used, free) + \"%\"; g.classList.toggle(\"over\", share > 1); g.classList.toggle(\"warm\", share > 0.75 && share <= 1); $(\"#p-\" + id).textContent = share > 1 ? \"over\" : Math.round(share * 100) + \"%\"; $(\"#t-\" + id).textContent = text; };\n gauge(\"events\", fuel.eventBytes, fuel.freeEventBytes, fmtBytes(fuel.eventBytes) + \" of \" + fmtBytes(fuel.freeEventBytes) + \" free\");\n gauge(\"media\", fuel.mediaBytes, fuel.freeMediaBytes, fmtBytes(fuel.mediaBytes) + \" of \" + fmtBytes(fuel.freeMediaBytes) + \" free\");\n gauge(\"active\", fuel.activeMs, fuel.freeActiveMs, fmtHours(fuel.activeMs) + \" of \" + fmtHours(fuel.freeActiveMs) + \" free\");\n gauge(\"rows\", fuel.rowsWritten, fuel.freeRowsWritten, fuel.rowsWritten.toLocaleString() + \" of \" + fuel.freeRowsWritten.toLocaleString() + \" free\");\n const sats = Math.floor(fuel.balanceMsats / 1000);\n const r = fuel.rates;\n $(\"#fuel-balance\").innerHTML = fuel.outOfFuel\n ? 'out of fuel Writes are paused until someone tops up.'\n : \"Balance \" + sats.toLocaleString() + \" sats. Past the allowances, prices track what the hosting costs: \" + r.satsPerGBMonthEvents.toLocaleString() + \" sats per GB-month of events, \" + r.satsPerGBMonthMedia.toLocaleString() + \" per GB-month of files, \" + r.satsPerActiveHour.toLocaleString() + \" per hour awake, \" + r.satsPerMillionRows.toLocaleString() + \" per million rows written. Traffic is free.\";\n $(\"#topup\").classList.toggle(\"hidden\", !fuel.enabled);\n // Who paid is the owner's to see: it comes with the signed stats call.\n let credits = [];\n if (owner && signer.ready()) { try { credits = (await rpc(\"stats\")).credits || []; } catch { credits = []; } }\n $(\"#credits tbody\").innerHTML = credits.length ? credits.map((c) => '' + esc(fmtTime(c.at)) + '' + av(c.payer) + key(c.payer) + '' + Math.floor(c.msats / 1000).toLocaleString() + \"\").join(\"\") : 'no zaps yet';\n if (!fuel.enabled) $(\"#topup-note\").textContent = \"Top-ups are not enabled on this service yet.\";\n renderCare();\n renderFuelTile();\n }\n\n async function topUp(sats) {\n if (!signer.ready()) throw new Error(NO_SIGNER);\n const msats = Math.round(sats * 1000);\n const zapRequest = await signer.signEvent({ kind: 9734, created_at: Math.floor(Date.now() / 1000), content: \"fuel for \" + host, tags: [[\"p\", fuel.servicePubkey], [\"amount\", String(msats)], [\"relays\", wsURL]] });\n const r = await (await fetch(\"/fuel/invoice\", { method: \"POST\", body: JSON.stringify({ zapRequest }) })).json();\n if (r.error) throw new Error(r.error);\n const inv = r.invoice;\n $(\"#invoice\").classList.remove(\"hidden\");\n $(\"#inv-text\").value = inv; $(\"#inv-link\").href = \"lightning:\" + inv; $(\"#inv-state\").textContent = \"waiting for payment…\";\n if (window.webln) { try { await window.webln.enable(); await window.webln.sendPayment(inv); } catch (e) { toast(e.message || \"wallet declined\"); } }\n const before = fuel.creditedMsats;\n for (let i = 0; i < 120; i++) {\n await new Promise((r) => setTimeout(r, 2500));\n await loadFuel();\n if (fuel.creditedMsats > before) { $(\"#inv-state\").textContent = \"paid, thank you\"; toast(\"Fuel credited\"); return; }\n }\n $(\"#inv-state\").textContent = \"no receipt yet; it can take a minute after paying\";\n }\n\n // ---- console ----\n function showTab(name) {\n if (name === \"content\" || name === \"storage\") name = \"data\";\n const known = myRole === \"moderator\" ? [\"people\", \"moderation\"] : [\"people\", \"moderation\", \"rules\", \"identity\", \"data\", \"sync\", \"views\", \"health\", \"owner\"];\n if (!known.includes(name)) name = \"people\";\n $$(\".tabs a\").forEach((a) => a.classList.toggle(\"on\", a.dataset.tab === name));\n $$(\".panel\").forEach((p) => p.classList.toggle(\"on\", p.dataset.panel === name));\n }\n // Tabs switch in place. A fragment still opens a tab when someone arrives with one,\n // but clicking never writes one, and any fragment already there is dropped.\n $$(\".tabs a\").forEach((a) => a.addEventListener(\"click\", (ev) => { ev.preventDefault(); showTab(a.dataset.tab); if (location.hash) history.replaceState(null, \"\", location.pathname + location.search); }));\n window.addEventListener(\"hashchange\", () => showTab(location.hash.slice(1)));\n // The strip fades on whichever side has more tabs off screen.\n const tabsFade = () => { const t = $(\"#tabs\"); t.classList.toggle(\"fade-l\", t.scrollLeft > 4); t.classList.toggle(\"fade-r\", t.scrollLeft + t.clientWidth < t.scrollWidth - 4); };\n $(\"#tabs\").addEventListener(\"scroll\", tabsFade); window.addEventListener(\"resize\", tabsFade); new ResizeObserver(tabsFade).observe($(\"#tabs\"));\n\n function renderFuelTile() {\n if (!fuel) return;\n const over = fuelOver();\n const sats = Math.max(0, Math.floor(fuel.balanceMsats / 1000));\n const d = new Date(), end = Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1), days = Math.max(1, Math.ceil((end - Date.now()) / 86400000));\n if (fuel.outOfFuel) { $(\"#h-fuel\").textContent = \"0 sats\"; $(\"#h-fuel-label\").textContent = \"out of fuel\"; $(\"#h-fuel-sub\").textContent = \"writes are paused\"; }\n else if (over) { $(\"#h-fuel\").textContent = sats.toLocaleString() + \" sats\"; $(\"#h-fuel-label\").textContent = \"fuel left\"; $(\"#h-fuel-sub\").textContent = \"past the free allowance\"; }\n else { $(\"#h-fuel\").textContent = days + (days === 1 ? \" day\" : \" days\"); $(\"#h-fuel-label\").textContent = \"free allowance left\"; $(\"#h-fuel-sub\").textContent = sats ? \"then \" + sats.toLocaleString() + \" sats\" : \"then a top-up is needed\"; }\n $(\"#usage\").innerHTML = [[\"events stored\", fmtBytes(fuel.eventBytes)], [\"files stored\", fmtBytes(fuel.mediaBytes)], [\"awake this month\", fmtHours(fuel.activeMs)], [\"rows written\", fuel.rowsWritten.toLocaleString()], [\"rows read\", fuel.rowsRead.toLocaleString()], [\"received this month\", fmtBytes(fuel.bytesIn)], [\"served this month\", fmtBytes(fuel.bytesOut)], [\"charged\", Math.floor(fuel.chargedMsats / 1000).toLocaleString() + \" sats\"]]\n .map(([k, v]) => \"
                \" + k + \"\" + v + \"
                \").join(\"\");\n }\n\n function renderHealth(stats) {\n $(\"#h-last\").textContent = stats.newest ? ago(stats.newest) : \"none\";\n $(\"#h-last-sub\").textContent = stats.newest ? fmtTime(stats.newest) : \"no events yet\";\n $(\"#h-conns\").textContent = stats.connections;\n const buckets = [[\"notes\", \"k1\", [1]], [\"reactions\", \"k2\", [7]], [\"DMs\", \"k3\", [4, 14, 1059]], [\"long-form\", \"k4\", [30023]], [\"other\", \"k5\", null]];\n const sums = buckets.map(() => 0); let total = 0;\n for (const { kind, n } of stats.kinds || []) { total += n; const i = buckets.findIndex((b) => b[2] && b[2].includes(kind)); sums[i < 0 ? 4 : i] += n; }\n const parts = buckets.map((b, i) => [b[0], b[1], sums[i]]).filter((p) => p[2] > 0);\n $(\"#h-kinds\").innerHTML = total ? parts.map(([name, cls, n]) => '').join(\"\") : '';\n $(\"#h-kinds-legend\").innerHTML = total ? parts.map(([name, cls, n]) => '' + name + \" \" + Math.round(n * 100 / total) + \"%\").join(\"\") : \"no events yet\";\n renderFuelTile();\n }\n\n async function loadAdmin() {\n const isOwner = !!me && me === owner;\n myRole = isOwner ? \"owner\" : \"\";\n let stats = null, p = null;\n // A signed-in member may be a moderator; the relay says by answering stats.\n if (me && owner && !isOwner) { try { [stats, p] = await Promise.all([rpc(\"stats\"), rpc(\"getpolicy\")]); myRole = \"moderator\"; } catch { myRole = \"\"; } }\n $(\"#console\").classList.toggle(\"hidden\", !myRole);\n loadMine();\n $(\"#console\").classList.toggle(\"mod\", myRole === \"moderator\");\n if (!myRole) { policy = null; renderCare(); return; }\n if (isOwner) [stats, p] = await Promise.all([rpc(\"stats\"), rpc(\"getpolicy\")]);\n policy = p;\n renderHealth(stats);\n renderCare();\n const fa = $(\"#access\"), fi = $(\"#identity\");\n fa.writes.value = p.writes; fa.reads.value = p.reads; fa.openKinds.value = (p.openKinds || []).join(\", \"); fa.guestReplies.checked = !!p.guestReplies;\n $(\"#wordsform\").words.value = (p.blockedWords || []).join(\"\\n\"); $(\"#wordsform\").inTags.checked = !!p.blockedWordsInTags; $(\"#thresholdform\").reportThreshold.value = p.reportThreshold || 0; fa.minPow.value = p.minPow; fa.maxFuture.value = p.maxFuture; fa.maxLimit.value = p.maxLimit; fa.maxSubs.value = p.maxSubs; fa.maxMessageKB.value = p.maxMessageKB;\n fa.eventsPerMinute.value = p.eventsPerMinute; fa.reqsPerMinute.value = p.reqsPerMinute; fa.maxBlobMB.value = p.maxBlobMB;\n renderFeatures(p.features || {});\n fi.name.value = p.name; fi.contact.value = p.contact; fi.description.value = p.description; fi.icon.value = p.icon;\n const fj = $(\"#joinform\"); fj.joinTerms.value = p.joinTerms; fj.directoryPublic.checked = !!p.directoryPublic;\n loadCard();\n fi.banner.value = p.banner || \"\"; fi.postingPolicy.value = p.postingPolicy || \"\"; fi.privacyPolicy.value = p.privacyPolicy || \"\";\n fi.tags.value = (p.tags || []).join(\", \"); fi.languageTags.value = (p.languageTags || []).join(\", \"); fi.relayCountries.value = (p.relayCountries || []).join(\", \");\n const fn = $(\"#notify\"), nt = p.notify || {};\n fn.reports.checked = !!nt.reports; fn.fuel.checked = !!nt.fuel; fn.jobs.checked = !!nt.jobs; fn.succession.checked = !!nt.succession; fn.digest.checked = !!nt.digest;\n showTab(location.hash.slice(1));\n if (isOwner) { await renderPresets(); renderWire(); renderSuccession(); loadDomains(); }\n await Promise.all([loadLists(), loadEvents(true), loadPins(), ...(isOwner ? [loadStorage()] : [])]);\n }\n\n async function loadAudit(before) {\n const rows = await rpc(\"listaudit\", before || 0);\n const html = rows.map((r) => '' + esc(fmtTime(r.at)) + '' + av(r.actor) + key(r.actor) + '' + esc(r.action) + '' + (/^[0-9a-f]{64}$/.test(r.target) ? key(r.target) : esc(r.target)) + '' + esc(r.detail) + '').join(\"\");\n const tb = $(\"#audit tbody\");\n if (before) tb.insertAdjacentHTML(\"beforeend\", html); else tb.innerHTML = html || 'Nothing yet';\n $(\"#audit-more\").style.display = rows.length < 100 ? \"none\" : \"\";\n }\n $(\"#audit-more\").onclick = guard(async () => { const last = $(\"#audit tbody tr:last-child\"); await loadAudit(last ? +last.dataset.seq : 0); });\n async function loadLists() {\n loadAudit(0);\n const [mem, bans, bannedEvents, allow, block, invites, reports, blobs, blocks, sites] = await Promise.all([rpc(\"listmembers\"), rpc(\"listbannedpubkeys\"), rpc(\"listbannedevents\"), rpc(\"listallowedkinds\"), rpc(\"listblockedkinds\"), rpc(\"listinvites\"), rpc(\"listreports\"), rpc(\"listblobs\", 100), rpc(\"listblockedips\"), rpc(\"listsites\")]);\n const members = mem.members;\n window.__members = members;\n const roleCell = (m) => m.role === \"owner\" ? ' owner' : myRole === \"owner\" ? ' ' : m.role === \"moderator\" ? ' moderator' : \"\";\n const untouchable = (m) => m.role === \"owner\" || (myRole !== \"owner\" && m.role === \"moderator\");\n // The tree: everyone under whoever invited them, the owner and the owner's own additions at the root.\n const known = new Set(members.map((m) => m.pubkey));\n const byInviter = new Map();\n for (const m of members) { const k = m.role !== \"owner\" && known.has(m.invited_by) ? m.invited_by : \"\"; if (!byInviter.has(k)) byInviter.set(k, []); byInviter.get(k).push(m); }\n const ordered = [], placed = new Set();\n const walk = (k, depth) => { for (const m of byInviter.get(k) || []) { if (placed.has(m.pubkey)) continue; placed.add(m.pubkey); m.depth = depth; ordered.push(m); walk(m.pubkey, depth + 1); } };\n walk(\"\", 0);\n for (const m of members) if (!placed.has(m.pubkey)) { m.depth = 0; ordered.push(m); }\n const nameOf = (pk) => { const x = members.find((m) => m.pubkey === pk); return x && x.name ? x.name : short(pk); };\n const limits = (m) => m.role === \"owner\" ? \"\" : myRole === \"owner\"\n ? ''\n : '' + (m.keep_days ? m.keep_days + \" d\" : \"\") + (m.max_bytes ? \" \" + fmtBytes(m.max_bytes) : \"\") + \"\";\n $(\"#members tbody\").innerHTML = ordered.map((m) => '' + av(m.pubkey) + key(m.pubkey) + roleCell(m) + (m.depth ? ' via ' + esc(nameOf(m.invited_by)) + \"\" : \"\") + (m.invites ? ' ' + m.invites + \" inv\" : \"\") + '' + limits(m) + '' + esc(fmtDay(m.joined_at)) + \", \" + esc(m.via) + '' + ib(\"check\", \"Save\", \"savemember\", m.pubkey) + (untouchable(m) ? \"\" : ib(\"x\", \"Remove\", \"removemember\", m.pubkey) + ib(\"banuser\", \"Ban\", \"banpubkey\", m.pubkey, \"danger\")) + \"\").join(\"\");\n const tf = $(\"#treeform\");\n tf.classList.toggle(\"hidden\", myRole !== \"owner\");\n if (policy && policy.memberInvites) { tf.depth.value = policy.memberInvites.depth; tf.quota.value = policy.memberInvites.quota; }\n $(\"#transfer [name=pubkey]\").innerHTML = members.filter((m) => m.role !== \"owner\").map((m) => '\").join(\"\");\n $(\"#succession [name=heir]\").innerHTML = $(\"#transfer [name=pubkey]\").innerHTML;\n $(\"#tc-people\").textContent = members.length;\n const link = (code) => location.origin + \"/invite/\" + code;\n $(\"#invites\").innerHTML = invites.length ? invites.map((i) => '
              • inv…' + i.code.slice(-8) + \" \" + esc(i.note || \"\") + ' ' + i.uses + (i.max_uses ? \"/\" + i.max_uses : \"\") + \" used, until \" + esc(fmtDay(i.expires_at)) + \"\" + ib(\"copy\", \"Copy link\", \"copy\", link(i.code)) + ib(\"x\", \"Revoke\", \"revokeinvite\", i.code) + \"
              • \").join(\"\") : '
              • no invites
              • ';\n const person = (r, icon, label, act) => \"
              • \" + av(r.pubkey) + '' + short(r.pubkey) + \" \" + esc(r.reason || \"\") + \"\" + ib(icon, label, act, r.pubkey) + \"
              • \";\n $(\"#bans\").innerHTML = bans.length ? bans.map((r) => person(r, \"undo\", \"Unban\", \"unrulepubkey\")).join(\"\") : '
              • nobody banned
              • ';\n $(\"#blocks\").innerHTML = blocks.length ? blocks.map((r) => '
              • ip' + esc(r.ip) + \" \" + esc(r.reason || \"\") + \"\" + ib(\"undo\", \"Unblock\", \"unblockip\", r.ip) + \"
              • \").join(\"\") : '
              • no addresses blocked
              • ';\n $(\"#banned-events\").innerHTML = bannedEvents.map((r) => '
              • ev' + key(r.id) + \" \" + esc(r.reason || \"\") + \"\" + ib(\"check\", \"Allow again\", \"allowevent\", r.id) + \"
              • \").join(\"\");\n $(\"#reports tbody\").innerHTML = reports.length ? reports.map((r) => '' + esc(fmtTime(r.at)) + '' + esc(r.type || \"report\") + '' + av(r.target_pubkey) + key(r.target_pubkey) + (r.target_event ? (r.blob ? ' file ' + key(r.target_event) + \"\" : ' ev ' + key(r.target_event) + (r.hidden ? ' hidden' : \"\") + \"\") : \"\") + '' + esc(r.content) + '' + ib(\"check\", \"Dismiss\", \"resolve:dismiss\", r.id) + ib(\"trash\", r.blob ? \"Delete the file\" : \"Delete the event\", \"resolve:delete\", r.id) + ib(\"banuser\", \"Ban the author\", \"resolve:ban\", r.id, \"danger\") + \"\").join(\"\") : 'nothing reported';\n $(\"#reports-count\").textContent = reports.length || \"\"; $(\"#tc-reports\").textContent = reports.length || \"\";\n $(\"#blobs tbody\").innerHTML = blobs.length ? blobs.map((b) => '' + esc(fmtTime(b.uploaded)) + '' + key(b.sha256) + ' ' + esc(b.type) + '' + fmtBytes(b.size) + '' + av(b.uploader) + key(b.uploader) + '' + ib(\"trash\", \"Delete file\", \"deleteblob\", b.sha256, \"danger\") + \"\").join(\"\") : 'no uploads';\n $(\"#blobs-count\").textContent = blobs.length || \"\";\n $(\"#sites tbody\").innerHTML = sites.length ? sites.map((s) => '' + av(s.author) + key(s.author) + '' + esc(s.d || (s.kind === 5128 ? \"snapshot\" : \"root\")) + '' + esc(s.url) + '' + esc(s.paths) + (s.missing ? ' ' + esc(s.missing) + ' missing' : '') + '' + fmtBytes(s.size) + '' + esc(s.expires_at ? fmtTime(s.expires_at) : \"never\") + '' + ib(\"trash\", \"Delete site\", \"deleteevent\", s.id, \"danger\") + '').join(\"\") : 'no sites yet';\n $(\"#sites-count\").textContent = sites.length || \"\";\n const tag = (k, cls) => '' + k + ib(\"x\", \"Remove rule\", \"unrulekind\", String(k)) + \"\";\n $(\"#kinds-allow\").innerHTML = allow.length ? allow.map((k) => tag(k, \"ok\")).join(\"\") : 'all';\n $(\"#kinds-block\").innerHTML = block.length ? block.map((k) => tag(k, \"blk\")).join(\"\") : 'none';\n await loadPeople();\n }\n\n const KIND_NAMES = { 0: \"profiles\", 1: \"notes\", 3: \"contacts\", 4: \"DMs\", 5: \"deletions\", 6: \"reposts\", 7: \"reactions\", 16: \"reposts\", 1059: \"gift wraps\", 1063: \"file headers\", 1111: \"comments\", 1984: \"reports\", 9734: \"zap requests\", 9735: \"zap receipts\", 9802: \"highlights\", 10002: \"relay lists\", 13534: \"roster\", 9000: \"group adds\", 9001: \"group removals\", 9021: \"join requests\", 9022: \"leave requests\", 39000: \"group info\", 39001: \"group admins\", 39002: \"group members\", 39003: \"group roles\", 30023: \"articles\", 30024: \"drafts\", 30078: \"app data\", 30311: \"live events\", 30818: \"wiki\" };\n const kindName = (k) => KIND_NAMES[k] || (k >= 20000 && k < 30000 ? \"ephemeral\" : k >= 30000 && k < 40000 ? \"addressable\" : k >= 10000 && k < 20000 ? \"replaceable\" : \"kind \" + k);\n const SYS_KINDS = new Set([0, 3, 10002, 9735, 13534, 8000, 8001, 9000, 9001, 39000, 39001, 39002, 39003]);\n let storage = null;\n\n // Features (settings.ts): a select each; search has three modes, the rest on or off.\n const FEATURES = [\n [\"search\", \"Search\", \"NIP-50. Prose indexes notes, threads, comments, highlights, articles and wiki pages; full indexes every public kind with content. A change applies to events from then on.\", [\"prose:prose\", \"full:full\", \"off:off\"]],\n [\"sync\", \"Sync\", \"NIP-77 reconciliation, which reads the whole matching set per sync.\"],\n [\"count\", \"Counts\", \"NIP-45 COUNT, with HLL sketches.\"],\n [\"discovery\", \"Discovery record\", \"NIP-66: the record the relay signs about itself, for crawlers.\"],\n [\"names\", \"Names\", \"NIP-05 addresses under this relay's domain.\"],\n [\"files\", \"Files\", \"Blossom and NIP-96: uploads, downloads and listings.\"],\n [\"pages\", \"Pages and feed\", \"Notes and articles as pages, and the Atom feed.\"],\n [\"sites\", \"Static websites\", \"NIP-5A sites on their own hostnames. Mirroring copies missing files into this relay and costs fuel.\", [\"mirror:on, mirror files\", \"proxy:on, fetch as needed\", \"off:off\"]],\n [\"marmot\", \"Marmot transport\", \"Signed KeyPackages and encrypted group messages, with account admission for ephemeral authors.\"],\n [\"grasp\", \"Git repositories\", \"GRASP Git hosting with admitted repository state. The prototype backend has bounded storage and compute limits.\"],\n [\"signer\", \"Signer traffic\", \"NIP-46 remote signing carried for anyone, never stored.\"],\n ];\n function renderFeatures(f) {\n $(\"#features\").innerHTML = FEATURES.map(([k, title, about, modes]) => {\n const cur = k === \"sites\" ? (f.sites?.enabled === false ? \"off\" : f.sites?.mirror === false ? \"proxy\" : \"mirror\") : modes ? String(f[k] || \"prose\") : String(f[k] !== false);\n const opts = (modes || [\"true:on\", \"false:off\"]).map((m) => { const [v, l] = m.split(\":\"); return '\"; }).join(\"\");\n return \"\";\n }).join(\"\");\n }\n $(\"#features\").addEventListener(\"change\", guard(async (ev) => {\n const sel = ev.target.closest(\"select[data-feature]\"); if (!sel) return;\n const k = sel.dataset.feature, v = k === \"search\" || k === \"sites\" ? sel.value : sel.value === \"true\";\n policy = await rpc(\"setpolicy\", { features: { [k]: k === \"sites\" ? { enabled: v !== \"off\", mirror: v === \"mirror\" } : v } });\n toast(k === \"search\" ? \"Search: \" + v : (v ? \"Switched on \" : \"Switched off \") + k); await loadInfo();\n }));\n\n async function loadViews() {\n let views;\n try { views = await rpc(\"listviews\"); } catch { return; }\n $(\"#views\").innerHTML = views.map((v) => {\n const runs = v.trigger === \"off\" ? \"off\" : v.trigger === \"live\" ? \"live, from memory\" : v.trigger === \"write\" ? \"on write and daily\" : v.trigger;\n const label = (c) => (c === \"off\" ? \"off\" : c === \"write\" ? \"on write\" : c === \"live\" ? \"on\" : c);\n const choices = [...v.choices, v.default].filter((c, i, a) => a.indexOf(c) === i);\n const pick = '\";\n const who = v.audience === \"members\" ? \"members\" + (v.stored ? \"\" : \", on request\") : \"anyone\";\n const last = v.trigger === \"live\" ? \"\" : v.last ? \"last run \" + fmtTime(v.last.at) : \"not run yet\";\n const rows = v.trigger === \"live\" ? \"no rows\" : v.last ? v.last.rows.toLocaleString() + \" rows\" : \"\";\n const meta = [runs, who, last, rows].filter(Boolean).map((x) => \"\" + esc(x) + \"\").join('|');\n return '
                ' + esc(v.name) + '
                ' + esc(v.about) + '
                ' + pick + (v.on ? 'Open' : \"\") + '
                ' + meta + \"
                \";\n }).join(\"\");\n }\n $(\"#views\").addEventListener(\"change\", guard(async (ev) => {\n const sel = ev.target.closest(\"select[data-view]\"); if (!sel) return;\n const value = sel.value === \"live\" ? true : sel.value;\n await rpc(\"setpolicy\", { views: { [sel.dataset.view]: value } });\n toast(sel.value === \"off\" ? \"Took down \" + sel.dataset.view : sel.dataset.view + \": \" + (sel.value === \"live\" ? \"on\" : sel.value === \"write\" ? \"on write\" : sel.value)); await loadViews(); await loadInfo();\n }));\n async function loadDumps() {\n const list = await rpc(\"listdumps\");\n const f = $(\"#dumpform\");\n if (policy) { f.dumps.value = policy.dumps || \"off\"; f.keep.value = policy.dumpsKeep || 7; }\n $(\"#dumps-count\").textContent = list.length || \"\";\n $(\"#dumps\").innerHTML = list.length ? list.map((d) => '
              • jsonl' + esc(d.name) + ' ' + d.events.toLocaleString() + \" events, \" + fmtBytes(d.bytes) + \"\" + ib(\"copy\", \"Download\", \"downloaddump\", d.name) + ib(\"trash\", \"Delete\", \"deletedump\", d.name, \"danger\") + \"
              • \").join(\"\") : '
              • no dumps yet
              • ';\n }\n // A dump is fetched with a signed request and handed to the browser as a file.\n async function downloadDump(name) {\n if (!signer.ready()) throw new Error(NO_SIGNER);\n const url = location.origin + \"/dumps/\" + name;\n const ev = await signer.signEvent({ kind: 27235, created_at: Math.floor(Date.now() / 1000), content: \"\", tags: [[\"u\", url], [\"method\", \"GET\"]] });\n const resp = await fetch(url, { headers: { authorization: \"Nostr \" + btoa(JSON.stringify(ev)) } });\n if (!resp.ok) throw new Error((await resp.json()).error || \"download failed\");\n const a = document.createElement(\"a\");\n a.href = URL.createObjectURL(await resp.blob()); a.download = host.split(\".\")[0] + \"-\" + name; a.click(); URL.revokeObjectURL(a.href);\n }\n // A plain member's own invites, when the owner lets members invite.\n async function loadMine() {\n const sec = $(\"#myinvites\");\n if (!me || !owner || myRole || !signer.ready()) { sec.classList.add(\"hidden\"); return; }\n let mine;\n try { mine = await rpc(\"listinvites\"); } catch { sec.classList.add(\"hidden\"); return; }\n sec.classList.remove(\"hidden\");\n const link = (code) => location.origin + \"/invite/\" + code;\n $(\"#mine\").innerHTML = mine.length ? mine.map((i) => '
              • inv…' + i.code.slice(-8) + ' ' + i.uses + (i.max_uses ? \"/\" + i.max_uses : \"\") + \" used, until \" + esc(fmtDay(i.expires_at)) + \"\" + ib(\"copy\", \"Copy link\", \"copy\", link(i.code)) + ib(\"x\", \"Revoke\", \"revokeinvite\", i.code) + \"
              • \").join(\"\") : '
              • no invites yet
              • ';\n }\n async function loadStorage() {\n storage = await rpc(\"storagestats\");\n pollJobs();\n loadViews();\n loadDumps().catch(() => {});\n const st = storage;\n const top = st.kinds.slice(0, 4), rest = st.kinds.slice(4).reduce((a, k) => a + k.bytes, 0);\n const parts = [...top.map((k, i) => [k.kind + \" \" + kindName(k.kind), \"k\" + (i + 1), k.bytes]), ...(rest ? [[\"other\", \"k5\", rest]] : [])];\n const total = st.eventBytes || 1;\n $(\"#s-bar\").innerHTML = parts.length ? parts.map(([n, c, b]) => '').join(\"\") : '';\n $(\"#s-legend\").innerHTML = parts.length ? parts.map(([n, c, b]) => '' + esc(n) + \" \" + Math.round(b * 100 / total) + \"%\").join(\"\") : \"no events yet\";\n const overhead = Math.max(0, st.databaseBytes - st.eventBytes);\n $(\"#s-totals\").innerHTML = [[\"events\", st.events.toLocaleString() + \" \" + fmtBytes(st.eventBytes) + \"\"], [\"index and overhead\", fmtBytes(overhead)], [\"files\", st.blobs.toLocaleString() + \" \" + fmtBytes(st.mediaBytes) + \"\"]]\n .map(([k, v]) => \"
                \" + k + \"\" + v + \"
                \").join(\"\");\n const any = st.retention.find((r) => r.kind === null);\n const own = (kind) => { const r = st.retention.find((x) => x.kind === kind); return r ? r.days : \"\"; };\n const row = (k) => {\n const key = k.kind === null ? \"\" : String(k.kind);\n const placeholder = k.kind === null ? \"forever\" : k.replaceable || !any ? \"forever\" : any.days + \" (everything else)\";\n const pill = k.kind === null ? \"everything else\" : '' + k.kind + \" \" + esc(kindName(k.kind));\n const cells = k.protected\n ? 'required'\n : ' days' + ib(\"check\", \"Save keep-for rule\", \"saveretention\", key) + ib(\"trash\", \"Purge\", \"purgekind\", key, \"danger\") + \"\";\n return '' + pill + '' + (k.n === undefined ? \"\" : k.n.toLocaleString()) + '' + (k.bytes === undefined ? \"\" : fmtBytes(k.bytes)) + '' + (k.oldest ? esc(fmtDay(k.oldest)) : \"\") + \"\" + cells + \"\";\n };\n $(\"#kinds tbody\").innerHTML = [...st.kinds, { kind: null, days: any ? any.days : 0 }].map(row).join(\"\");\n }\n\n let searchQuery = \"\";\n async function loadEvents(reset) {\n const list = searchQuery ? await rpc(\"searchevents\", searchQuery, 200) : await rpc(\"listrecentevents\", reset ? 50 : 200);\n $(\"#events tbody\").innerHTML = list.length ? list.map((e) => '' + esc(fmtTime(e.created_at)) + '' + e.kind + '' + av(e.pubkey) + key(e.pubkey) + '' + esc(e.content) + '' + ib(\"pin\", \"Pin\", \"pinevent\", e.id) + ib(\"trash\", \"Delete event\", \"deleteevent\", e.id) + ib(\"ban\", \"Ban event\", \"banevent\", e.id, \"danger\") + ib(\"banuser\", \"Ban author\", \"banpubkey\", e.pubkey, \"danger\") + \"\").join(\"\") : 'no events yet';\n $(\"#more\").classList.toggle(\"hidden\", searchQuery || list.length < 50);\n }\n $(\"#searchform\").onsubmit = guard(async (ev) => {\n searchQuery = ev.target.q.value.trim();\n $(\"#searchclear\").classList.toggle(\"hidden\", !searchQuery);\n await loadEvents(true);\n });\n $(\"#searchclear\").onclick = guard(async () => {\n searchQuery = \"\"; $(\"#searchform\").reset(); $(\"#searchclear\").classList.add(\"hidden\");\n await loadEvents(true);\n });\n async function loadPins() {\n const pins = await rpc(\"listpins\");\n $(\"#pins-count\").textContent = pins.length || \"\";\n $(\"#pins\").innerHTML = pins.length ? pins.map((t) => '
              • ' + (t[0] === \"e\" ? \"event\" : \"address\") + '' + esc(t[1].length > 40 ? t[1].slice(0, 16) + \"\\u2026\" + t[1].slice(-8) : t[1]) + \"\" + ib(\"copy\", \"Copy\", \"copy\", t[1]) + ib(\"x\", \"Unpin\", \"unpinevent\", t[1]) + \"
              • \").join(\"\") : '
              • nothing pinned
              • ';\n }\n $(\"#pinform\").onsubmit = guard(async (ev) => {\n await rpc(\"pinevent\", ev.target.id.value.trim()); ev.target.reset(); toast(\"Pinned\"); await loadPins();\n });\n\n // ---- actions ----\n const refresh = () => Promise.all([loadLists(), loadEvents(true), loadStorage(), loadPins()]);\n\n $(\"#copy\").onclick = async () => { await navigator.clipboard.writeText(wsURL); toast(\"copied \" + wsURL); };\n $(\"#signin\").onclick = guard(async () => {\n if (!window.nostr) throw new Error(\"No nostr extension found. Install one (Alby, nos2x, …) and reload, or use a remote signer.\");\n me = await window.nostr.getPublicKey();\n localStorage.setItem(\"me\", me);\n renderHeader(); await loadAdmin(); await loadPeople();\n });\n $(\"#signin46\").onclick = () => showRemote(null);\n $$(\".remote\").forEach((b) => { b.onclick = () => showRemote($(\"#\" + b.dataset.note)); });\n $(\"#nccopy\").onclick = async () => { await navigator.clipboard.writeText($(\"#nclink\").href); toast(\"Link copied; paste it into your signer app\"); };\n $(\"#bunkerform\").onsubmit = guard(async (ev) => {\n $(\"#remotenote\").textContent = \"Connecting…\";\n try { await connectBunker(ev.target.url.value); } catch (e) { $(\"#remotenote\").textContent = e.message; throw e; }\n $(\"#remotenote\").textContent = \"\"; ev.target.reset();\n await remoteDone();\n });\n $(\"#signout\").onclick = async () => {\n if (remote) { const r = remote; remote = null; try { await withTimeout(r.logout(), 5000, \"The signer\"); } catch { /* the session is gone either way */ } }\n localStorage.removeItem(\"nip46\");\n me = null; localStorage.removeItem(\"me\"); renderHeader(); await loadAdmin(); await loadPeople();\n };\n const claimNow = async (note) => {\n if (!signer.ready()) { note.textContent = \"Sign the claim with a nostr extension or a remote signer.\"; showRemote(note); return; }\n me = await signer.getPublicKey();\n const r = await rpc(\"claim\");\n if (!r.claimed) throw new Error(\"Somebody else claimed it first.\");\n localStorage.setItem(\"me\", me);\n toast(\"It's yours.\");\n await loadInfo(); await loadFuel(); await loadAdmin(); await loadPeople();\n if (r.converted && confirm(\"This relay began as a temporary one: anyone can write, and everything is deleted after 14 days. Switch to the default rules and keep everything from now on? Each rule can be changed later on the Rules and Storage tabs.\")) {\n await rpc(\"resetrules\"); toast(\"Rules reset\"); await loadInfo(); await loadAdmin();\n }\n };\n $(\"#claim\").onclick = guard(() => claimNow($(\"#claimnote\")));\n $(\"#claimlease\").onclick = guard(() => claimNow($(\"#leasenote\")));\n // Jobs run in the background; the table follows them while the tab is open.\n let jobsTimer = 0;\n const fmtJob = (j) => {\n const what = j.kind === \"mirror\" ? \"mirror site\" : j.kind === \"import\" ? \"import\" : j.label === \"backfill\" ? \"fetch my history\" : j.kind === \"pull\" ? \"pull\" : \"rebroadcast\";\n const f = [];\n if (j.filter.authors) f.push(j.filter.authors.length === 1 && j.filter.authors[0] === me ? \"my events\" : j.filter.authors.length + \" authors\");\n if (j.filter.kinds) f.push(\"kinds \" + j.filter.kinds.join(\", \"));\n if (j.filter.since) f.push(\"since \" + fmtDay(j.filter.since));\n const when = j.every ? \"every \" + (j.every === 24 ? \"day\" : j.every + \" h\") + (j.nextRun ? \", next \" + fmtTime(j.nextRun) : \"\") : \"once\";\n const l = j.last;\n const count = (stored, blobs, sent, refused) => (j.kind === \"mirror\" ? blobs.toLocaleString() + \" files mirrored\" : j.kind === \"import\" ? stored.toLocaleString() + \" events\" + ((j.last ? j.last.duplicates : j.duplicates) ? \", \" + (j.last ? j.last.duplicates : j.duplicates) + \" already here\" : \"\") : j.kind === \"pull\" ? stored.toLocaleString() + \" events\" + (blobs ? \", \" + blobs + \" files\" : \"\") : sent.toLocaleString() + \" sent\" + (refused ? \", \" + refused + \" refused\" : \"\"));\n const res = j.running ? \"running: \" + count(j.stored, j.blobs, j.sent, j.refused) + \"...\" : !l ? \"waiting\" : l.error ? \"failed: \" + l.error : count(l.stored, l.blobs, l.sent, l.refused) + (l.skipped ? \", \" + l.skipped + \" skipped\" : \"\") + \", \" + fmtTime(l.finishedAt);\n return \"\" + what + \"\" + j.relays.map(esc).join(\"
                \") + \"\" + (f.join(\", \") || \"everything\") + \"\" + when + \"\" + esc(res) + \"\" + (j.running ? \"\" : ib(\"undo\", \"Run now\", \"runjob\", j.id)) + ib(\"x\", \"Remove\", \"removejob\", j.id) + \"\";\n };\n async function pollJobs() {\n clearTimeout(jobsTimer);\n let jobs;\n try { jobs = await rpc(\"listjobs\"); } catch { return; }\n $(\"#jobs tbody\").innerHTML = jobs.length ? jobs.map(fmtJob).join(\"\") : 'no jobs yet';\n if (jobs.some((j) => j.running || (j.nextRun && j.nextRun <= Math.floor(Date.now() / 1000) + 1))) jobsTimer = setTimeout(pollJobs, 3000);\n }\n const urls = (s) => s.split(/[\\s,]+/).map((u) => u.trim()).filter(Boolean);\n const kindsOf = (s) => s.split(/[\\s,]+/).map((k) => parseInt(k, 10)).filter((k) => Number.isInteger(k) && k >= 0);\n $(\"#pullform\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n await rpc(\"addjob\", { kind: \"pull\", relays: [f.url.value.trim()], every: +f.every.value });\n toast(+f.every.value ? \"Mirror scheduled\" : \"Pull started\"); f.reset(); await pollJobs();\n });\n $(\"#backfillform\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n await rpc(\"backfill\", urls(f.relays.value));\n toast(\"Fetching your history\"); f.reset(); await pollJobs();\n });\n $(\"#pushform\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n const filter = {};\n const kinds = kindsOf(f.kinds.value); if (kinds.length) filter.kinds = kinds;\n const days = +f.days.value; if (days > 0) filter.since = Math.floor(Date.now() / 1000) - days * 86400;\n await rpc(\"addjob\", { kind: \"push\", relays: urls(f.targets.value), filter, every: +f.every.value });\n toast(\"Rebroadcast started\"); f.reset(); await pollJobs();\n });\n // ---- presets: writes, reads, kinds and keep-for rules in one click ----\n let presets = null;\n async function renderPresets() {\n if (!presets) { try { presets = await rpc(\"listpresets\"); } catch { presets = []; } }\n $(\"#presets\").innerHTML = presets.map((p) => '\").join(\"\");\n $(\"#presetsourcerow\").classList.toggle(\"hidden\", !presets.some((p) => p.source));\n }\n $(\"#presets\").addEventListener(\"click\", async (ev) => {\n const b = ev.target.closest(\"button[data-preset]\"); if (!b) return;\n const p = (presets || []).find((x) => x.name === b.dataset.preset); if (!p) return;\n if (!confirm(p.title + \": \" + p.about + \"\\n\\nThis replaces the writes and reads rules, the directory setting, the kind rules and the keep-for rules. Limits, identity, people and bans stay.\")) return;\n const source = $(\"#presetsource\").value.trim();\n if (p.source === \"required\" && !source) { $(\"#presetnote\").textContent = p.title + \" needs a source relay to mirror; enter its wss:// URL first.\"; return; }\n b.disabled = true;\n try { policy = await rpc(\"applypreset\", p.name, p.source && source ? { source } : undefined); $(\"#presetnote\").textContent = \"Now: \" + p.about + (policy.job ? \" Mirroring \" + source + \" every \" + policy.job.every + \" h.\" : \"\"); toast(p.title + \" applied\"); await loadInfo(); await loadAdmin(); }\n catch (e) { toast(e.message); } finally { b.disabled = false; }\n });\n\n // ---- wire me in: this relay in the owner's own lists ----\n // The lists are replaceable, so a fresh list with only this relay would\n // clobber the real one once it spread. Every publish starts from the\n // newest copy found here or on the indexers, verified when the signer\n // library is around, and adds or removes this relay in it.\n const INDEXERS = [\"wss://purplepag.es\", \"wss://relay.nostr.band\", \"wss://relay.damus.io\", \"wss://nos.lol\"];\n const LISTS = [\n { kind: 10002, tag: \"r\", title: \"Relay list\", nip: \"NIP-65\", about: \"where clients read your notes and send you mentions\" },\n { kind: 10050, tag: \"relay\", title: \"DM inbox\", nip: \"NIP-17\", about: \"where people send you private messages\" },\n { kind: 10007, tag: \"relay\", title: \"Search relays\", nip: \"NIP-51\", about: \"where clients run your searches\" },\n { kind: 10063, tag: \"server\", title: \"Blossom servers\", nip: \"BUD-03\", about: \"where clients upload and look for your files\" },\n ];\n const mineFor = (l) => (l.tag === \"server\" ? location.origin : wsURL);\n const normURL = (u) => { try { const x = new URL(String(u).trim()); return (x.host + x.pathname).replace(/\\/+$/, \"\").toLowerCase(); } catch { return String(u).trim().toLowerCase(); } };\n const isMine = (l, t) => t[0] === l.tag && normURL(t[1] || \"\") === normURL(mineFor(l));\n const listHas = (list, l) => !!list && list.tags.some((t) => isMine(l, t));\n // mergeList is pure: the newest list with this relay put first or taken out, every other tag kept.\n function mergeList(list, l, include) {\n const tags = (list ? list.tags : []).filter((t) => !isMine(l, t));\n if (include) tags.unshift([l.tag, mineFor(l)]);\n return { kind: l.kind, created_at: Math.floor(Date.now() / 1000), content: list ? list.content : \"\", tags };\n }\n const relaysIn = (list) => list.tags.filter((t) => (t[0] === \"r\" || t[0] === \"relay\") && /^wss?:\\/\\//i.test(t[1] || \"\")).map((t) => t[1].trim());\n // overWS opens one socket, sends one message, feeds answers to onMessage until it says done or time runs out.\n function overWS(url, ms, first, onMessage) {\n return new Promise((res) => {\n let ws = null, done = false, out = null;\n const finish = () => { if (done) return; done = true; clearTimeout(timer); try { if (ws) ws.close(); } catch { /* closed */ } res(out); };\n const timer = setTimeout(finish, ms);\n try { ws = new WebSocket(url); } catch { return finish(); }\n ws.onopen = () => ws.send(JSON.stringify(first));\n ws.onmessage = (m) => { let d; try { d = JSON.parse(m.data); } catch { return; } if (!Array.isArray(d)) return; if (onMessage(d, (v) => { out = v; })) finish(); };\n ws.onerror = finish; ws.onclose = finish;\n });\n }\n function fetchNewest(url, filter, ms) {\n let best = null;\n return overWS(url, ms, [\"REQ\", \"w\", filter], (d, set) => {\n if (d[0] === \"EVENT\" && d[1] === \"w\" && d[2] && (!best || d[2].created_at > best.created_at)) { best = d[2]; set(best); }\n return (d[0] === \"EOSE\" || d[0] === \"CLOSED\") && d[1] === \"w\";\n });\n }\n function publishTo(url, event, ms) {\n return overWS(url, ms, [\"EVENT\", event], (d, set) => { if (d[0] === \"OK\" && d[1] === event.id) { set({ url, ok: !!d[2], msg: d[3] || \"\" }); return true; } return false; })\n .then((r) => r || { url, ok: false, msg: \"no answer\" });\n }\n // bridge signs a NIP-98 request to this relay's HTTP door, so the owner's own reads and writes pass any read rule.\n async function bridge(path, body) {\n const url = location.origin + path, raw = JSON.stringify(body);\n const ev = await signer.signEvent({ kind: 27235, created_at: Math.floor(Date.now() / 1000), content: \"\", tags: [[\"u\", url], [\"method\", \"POST\"], [\"payload\", await sha256hex(raw)]] });\n const resp = await fetch(url, { method: \"POST\", headers: { \"content-type\": \"application/json\", authorization: \"Nostr \" + btoa(JSON.stringify(ev)) }, body: raw });\n const json = await resp.json();\n if (!resp.ok) throw new Error(json.error || \"HTTP \" + resp.status);\n return json;\n }\n const wire = {};\n function renderWire() {\n const pill = (state) => {\n const cls = state === \"listed\" ? \"on\" : state === \"failed\" ? \"bad\" : state === \"not listed\" ? \"off\" : \"\";\n const label = state === \"checking\" || state === \"publishing\" ? state + \"\\u2026\" : state;\n return '' + esc(label) + \"\";\n };\n $(\"#wire\").innerHTML = LISTS.map((l) => {\n const w = wire[l.kind] || { state: \"\", results: [], list: null };\n const busy = w.state === \"checking\" || w.state === \"publishing\";\n const btn = (act, cls, label) => '\";\n const buttons = w.state === \"listed\" ? btn(\"remove\", \"\", \"Remove this relay\") : btn(\"add\", \"pri\", \"Add this relay\") + btn(\"check\", \"\", w.state ? \"Check again\" : \"Check\");\n const n = w.list ? w.list.tags.filter((t) => t[0] === l.tag).length : 0;\n const from = w.list ? \"\" + (n === 1 ? \"1 entry\" : n + \" entries\") + \", \" + fmtTime(w.list.created_at) + \"\" : w.state && !busy ? \"no list found\" : \"\";\n const sent = (w.results || []).map((r) => '' + esc(r.url.replace(/^wss?:\\/\\//, \"\")) + (r.ok ? \"\" : \" failed\") + \"\").join(\"\");\n const meta = (w.state ? pill(w.state) : \"\") + from + sent;\n return '
                ' + l.title + ' ' + l.nip + \"
                \" + l.about + '
                ' + buttons + '
                ' + meta + \"
                \";\n }).join(\"\");\n }\n async function wireCheck(l) {\n const w = (wire[l.kind] = { state: \"checking\", list: null, results: [] }); renderWire();\n const filter = { kinds: [l.kind], authors: [me], limit: 1 };\n const found = [];\n try { found.push(...(await bridge(\"/query\", [filter]))); } catch { /* the relay may hold none */ }\n const remote = await Promise.all(INDEXERS.map((u) => fetchNewest(u, filter, 4000)));\n let lib = null; try { lib = await signerLib(); } catch { /* unverified lists are still the owner's own, by pubkey */ }\n for (const e of remote) if (e && e.pubkey === me && e.kind === l.kind && Array.isArray(e.tags) && (!lib || lib.verifyEvent(e))) found.push(e);\n w.list = found.sort((a, b) => b.created_at - a.created_at)[0] || null;\n w.state = listHas(w.list, l) ? \"listed\" : \"not listed\"; renderWire();\n }\n async function wirePublish(l, include) {\n if (!wire[l.kind] || !wire[l.kind].state || wire[l.kind].state === \"failed\") await wireCheck(l);\n const w = wire[l.kind]; w.state = \"publishing\"; w.results = []; renderWire();\n try {\n const signed = await signer.signEvent(mergeList(w.list, l, include));\n const here = await bridge(\"/events\", signed).then((r) => ({ url: wsURL, ok: !!r.accepted, msg: r.message || \"\" })).catch((e) => ({ url: wsURL, ok: false, msg: e.message }));\n const targets = [...new Set([...relaysIn(signed), ...INDEXERS])].filter((u) => normURL(u) !== normURL(wsURL));\n const rest = await Promise.all(targets.map((u) => publishTo(u, signed, 6000)));\n w.results = [here, ...rest]; w.list = signed; w.state = include ? \"listed\" : \"not listed\";\n toast((include ? \"Added to your \" : \"Removed from your \") + l.title.toLowerCase());\n } catch (e) { w.state = \"failed\"; w.results = [{ url: wsURL, ok: false, msg: e.message }]; toast(e.message); }\n renderWire();\n }\n $(\"#wire\").addEventListener(\"click\", (ev) => {\n const b = ev.target.closest(\"button[data-wire]\"); if (!b) return;\n const l = LISTS.find((x) => String(x.kind) === b.dataset.wire); if (!l) return;\n if (b.dataset.do === \"check\") wireCheck(l); else wirePublish(l, b.dataset.do === \"add\");\n });\n\n // ---- custom domains: this relay under a hostname the owner controls ----\n let domainSites = [];\n const domainOptions = (current = \"\") => [{ label: \"\", title: \"This relay\" }, ...domainSites.map((s) => ({ label: s.label, title: (s.d || (s.kind === 5128 ? \"snapshot\" : \"root\")) + \" / \" + key(s.author) })), ...(current && !domainSites.some((s) => s.label === current) ? [{ label: current, title: \"Site \" + current }] : [])].map((s) => '\").join(\"\");\n let domains = null; // null: not enabled on this host\n function renderDomains() {\n $(\"#domains\").innerHTML = (domains || []).map((d) => {\n const state = d.ready ? \"active\" : \"hostname \" + d.status.replace(/_/g, \" \") + \", certificate \" + d.sslStatus.replace(/_/g, \" \");\n const btn = (act, cls, label) => '\";\n const rows = d.ready ? \"\" : '
                ' + d.records.map((r) => \"\").join(\"\") + \"
                TypeNameValue
                \" + esc(r.type) + '' + esc(r.name) + '' + esc(r.value) + \"\" + esc(r.note) + \"
                \";\n return '
                ' + esc(d.host) + '' + esc(state) + \"\" + btn(\"check\", \"\", \"Check\") + btn(\"remove\", \"danger\", \"Remove\") + '
                \" + rows;\n }).join(\"\");\n }\n async function loadDomains() {\n try { [domains, domainSites] = await Promise.all([rpc(\"listdomains\"), rpc(\"listsites\")]); $(\"#adddomain select[name=site]\").innerHTML = domainOptions(); $(\"#domainnote\").textContent = domains.length ? \"\" : \"No custom domain yet.\"; $(\"#adddomain\").classList.remove(\"hidden\"); }\n catch (e) { domains = null; $(\"#domainnote\").textContent = /^unsupported/.test(e.message) ? \"Custom domains are not enabled on this host.\" : e.message; $(\"#adddomain\").classList.add(\"hidden\"); }\n renderDomains();\n }\n $(\"#adddomain\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n await rpc(\"adddomain\", f.host.value.trim(), f.site.value); f.reset(); toast(\"Domain added; now create the CNAME\"); await loadDomains();\n });\n $(\"#domains\").addEventListener(\"change\", guard(async (ev) => {\n const select = ev.target.closest(\"select[data-domain-site]\"); if (!select) return;\n await rpc(\"setdomainsite\", select.dataset.domainSite, select.value);\n toast(\"Domain destination saved\"); await loadDomains();\n }));\n $(\"#domains\").addEventListener(\"click\", async (ev) => {\n const b = ev.target.closest(\"button[data-domain]\"); if (!b) return;\n const host = b.dataset.domain;\n if (b.dataset.do === \"remove\" && !confirm(\"Remove \" + host + \"? Its certificate goes with it and the name stops answering.\")) return;\n b.disabled = true;\n try {\n if (b.dataset.do === \"remove\") { await rpc(\"removedomain\", host); toast(\"Removed\"); }\n else { const d = await rpc(\"checkdomain\", host); toast(d.ready ? host + \" is live\" : \"Not yet: \" + (d.status === \"active\" ? \"certificate pending\" : \"waiting for the CNAME\")); }\n await loadDomains();\n } catch (e) { toast(e.message); } finally { b.disabled = false; }\n });\n\n $(\"#access\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n const openKinds = f.openKinds.value.split(/[\\s,]+/).filter(Boolean).map(Number);\n if (openKinds.some((k) => !Number.isInteger(k) || k < 0 || k > 65535)) throw new Error(\"Open kinds must be whole numbers.\");\n policy = await rpc(\"setpolicy\", { writes: f.writes.value, reads: f.reads.value, openKinds, guestReplies: f.guestReplies.checked, minPow: +f.minPow.value, maxFuture: +f.maxFuture.value, maxLimit: +f.maxLimit.value, maxSubs: +f.maxSubs.value, maxMessageKB: +f.maxMessageKB.value, eventsPerMinute: +f.eventsPerMinute.value, reqsPerMinute: +f.reqsPerMinute.value, maxBlobMB: +f.maxBlobMB.value });\n toast(\"Rules saved\"); await loadInfo();\n });\n $(\"#notify\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n policy = await rpc(\"setpolicy\", { notify: { reports: f.reports.checked, fuel: f.fuel.checked, jobs: f.jobs.checked, succession: f.succession.checked, digest: f.digest.checked } });\n toast(\"Notifications saved\");\n });\n $(\"#notifytest\").onclick = guard(async () => {\n const r = await rpc(\"notifytest\");\n toast(r.sent ? \"Sent. Look for a message from the relay in your DMs.\" : \"Could not send.\");\n });\n $(\"#identity\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n const list = (v) => v.split(\",\").map((s) => s.trim()).filter(Boolean);\n policy = await rpc(\"setpolicy\", { name: f.name.value, contact: f.contact.value, description: f.description.value, icon: f.icon.value,\n banner: f.banner.value, postingPolicy: f.postingPolicy.value, privacyPolicy: f.privacyPolicy.value, tags: list(f.tags.value), languageTags: list(f.languageTags.value), relayCountries: list(f.relayCountries.value) });\n toast(\"Identity saved\"); await loadInfo(); await loadPeople(); loadCard();\n });\n $(\"#addmember\").onsubmit = guard(async (ev) => {\n const f = ev.target; const pk = npubToHex(f.pubkey.value); if (!pk) throw new Error(\"That is not a pubkey.\");\n await rpc(\"setmember\", pk, { name: f.name.value.trim() || null, note: f.note.value }); f.reset(); toast(\"Member added\"); await loadLists();\n });\n $(\"#addblock\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n await rpc(\"blockip\", f.ip.value.trim(), f.reason.value); f.reset(); toast(\"Blocked\"); await loadLists();\n });\n $(\"#wordsform\").onsubmit = guard(async (ev) => {\n const words = ev.target.words.value.split(\"\\n\").map((s) => s.trim()).filter(Boolean);\n const kept = await rpc(\"setblockedwords\", words);\n policy = await rpc(\"setpolicy\", { blockedWordsInTags: ev.target.inTags.checked });\n ev.target.words.value = kept.join(\"\\n\"); toast(kept.length ? kept.length + \" words blocked\" : \"No words blocked\");\n });\n $(\"#thresholdform\").onsubmit = guard(async (ev) => {\n policy = await rpc(\"setpolicy\", { reportThreshold: +ev.target.reportThreshold.value });\n toast(policy.reportThreshold ? \"Hidden after \" + policy.reportThreshold + \" reports\" : \"Never hidden by reports\"); await loadLists();\n });\n $(\"#addban\").onsubmit = guard(async (ev) => {\n const pk = npubToHex(ev.target.pubkey.value); if (!pk) throw new Error(\"That is not a pubkey.\");\n await rpc(\"banpubkey\", pk, ev.target.reason.value, ev.target.erase.checked); ev.target.reset(); toast(ev.target.erase.checked ? \"Banned and erased\" : \"Banned\"); await loadLists();\n });\n $(\"#mintinvite\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n const inv = await rpc(\"createinvite\", +f.ttl.value, +f.max.value, f.note.value);\n await navigator.clipboard.writeText(location.origin + \"/invite/\" + inv.code).catch(() => {});\n f.note.value = \"\"; toast(\"Invite created and copied\"); await loadLists();\n });\n $(\"#kindform\").onsubmit = guard(async (ev) => {\n const rule = ev.submitter.value; const k = +ev.target.kind.value;\n await rpc(rule === \"allow\" ? \"allowkind\" : \"disallowkind\", k); ev.target.reset(); toast((rule === \"allow\" ? \"Allowed kind \" : \"Blocked kind \") + k); await loadLists();\n });\n $(\"#more\").onclick = guard(() => loadEvents(false));\n $(\"#dumpform\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n policy = await rpc(\"setpolicy\", { dumps: f.dumps.value, dumpsKeep: Math.max(1, Math.min(60, Math.floor(+f.keep.value || 7))) });\n toast(policy.dumps === \"off\" ? \"Dumps off\" : \"Dumping \" + policy.dumps); await loadDumps();\n });\n $(\"#importform\").onsubmit = guard(async (ev) => {\n const file = ev.target.file.files[0]; if (!file) return;\n if (!signer.ready()) throw new Error(NO_SIGNER);\n if (file.size > 64 * 1024 * 1024) throw new Error(\"At most 64 MB per import.\");\n const body = await file.text();\n const url = location.origin + \"/import?name=\" + encodeURIComponent(file.name);\n const token = await signer.signEvent({ kind: 27235, created_at: Math.floor(Date.now() / 1000), content: \"\", tags: [[\"u\", url], [\"method\", \"PUT\"], [\"payload\", await sha256hex(body)]] });\n const resp = await fetch(url, { method: \"PUT\", headers: { authorization: \"Nostr \" + btoa(JSON.stringify(token)), \"content-type\": \"application/x-ndjson\" }, body });\n const r = await resp.json();\n if (!resp.ok) throw new Error(r.error || \"import failed\");\n ev.target.reset(); toast(\"Importing \" + fmtBytes(r.bytes)); await pollJobs();\n });\n $(\"#dumpnow\").onclick = guard(async () => { const d = await rpc(\"dumpnow\"); toast(\"Dumped \" + d.events.toLocaleString() + \" events\"); await loadStorage(); });\n $(\"#treeform\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n policy = await rpc(\"setpolicy\", { memberInvites: { depth: Math.max(0, Math.floor(+f.depth.value || 0)), quota: Math.max(0, Math.floor(+f.quota.value || 0)) } });\n toast(policy.memberInvites.depth ? \"Members may invite\" : \"Only you and moderators invite\");\n });\n $(\"#mintmine\").onclick = guard(async () => {\n const inv = await rpc(\"createinvite\", 259200, 1, \"\");\n await navigator.clipboard.writeText(location.origin + \"/invite/\" + inv.code).catch(() => {});\n toast(\"Invite created and copied\"); await loadMine();\n });\n $(\"#exportcfg\").onclick = guard(async () => {\n const cfg = await rpc(\"exportconfig\");\n const a = document.createElement(\"a\");\n a.href = URL.createObjectURL(new Blob([JSON.stringify(cfg, null, 2)], { type: \"application/json\" }));\n a.download = host.split(\".\")[0] + \".bind.ws.config.json\";\n a.click(); URL.revokeObjectURL(a.href);\n });\n $(\"#importcfg\").onclick = () => $(\"#cfgfile\").click();\n $(\"#cfgfile\").onchange = guard(async (ev) => {\n const file = ev.target.files[0]; if (!file) return;\n const cfg = JSON.parse(await file.text());\n const check = await rpc(\"importconfig\", cfg, { dryRun: true });\n const lines = check.changes.summary.length ? check.changes.summary.join(\"\\n\") : \"Nothing would change.\";\n const dropped = check.warnings.length ? \"\\n\\nNot taken:\\n\" + check.warnings.join(\"\\n\") : \"\";\n if (!confirm(\"Apply \" + file.name + \" to this relay?\\n\\n\" + lines + dropped)) { ev.target.value = \"\"; return; }\n await rpc(\"importconfig\", cfg); ev.target.value = \"\"; toast(\"Configuration imported\"); await loadInfo(); await loadAdmin(); await loadPeople();\n });\n // Succession: the status line under the heir form, from successionstatus.\n async function renderSuccession() {\n const el = $(\"#successionnote\"), f = $(\"#succession\");\n let st;\n try { st = await rpc(\"successionstatus\"); } catch { el.textContent = \"\"; return; }\n const sc = st.succession;\n $(\"#clearsuccession\").classList.toggle(\"hidden\", !sc);\n f.querySelector(\"button.btn:not(#clearsuccession)\").textContent = sc ? \"Change heir\" : \"Set heir\";\n if (!sc) { el.textContent = \"No heir named. Last signed in \" + fmtTime(st.ownerSeenAt) + \".\"; return; }\n if (f.heir.querySelector('[value=\"' + sc.heir + '\"]')) f.heir.value = sc.heir;\n f.afterDays.value = String(sc.afterDays);\n const who = (window.__members || []).find((m) => m.pubkey === sc.heir);\n const heir = who && who.name ? who.name + \"@\" + host : short(sc.heir);\n el.textContent = \"Heir: \" + heir + \". Last signed in \" + fmtTime(st.ownerSeenAt) + (st.silentDays ? \" (\" + st.silentDays + \" days ago)\" : \"\") + \". \" +\n (st.warning ? \"The warning month is running: the relay goes to \" + heir + \" on \" + fmtDay(st.handoverAt) + \" unless you sign in.\" : \"If you stay away, it goes to \" + heir + \" around \" + fmtDay(st.handoverAt) + \".\") +\n (st.log && st.log.length ? \" Handed over before: \" + st.log.map((l) => fmtDay(l.at) + \" to \" + short(l.to)).join(\", \") + \".\" : \"\");\n }\n $(\"#succession\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n await rpc(\"setsuccession\", { heir: f.heir.value, afterDays: +f.afterDays.value });\n toast(\"Heir set\"); await loadAdmin();\n });\n $(\"#clearsuccession\").onclick = guard(async () => {\n await rpc(\"clearsuccession\");\n toast(\"Heir cleared\"); await loadAdmin();\n });\n $(\"#transfer\").onsubmit = guard(async (ev) => {\n const pk = ev.target.pubkey.value; if (!pk) return;\n const name = host.split(\".\")[0];\n const typed = prompt(\"This hands \" + host + \" to \" + short(pk) + \" for good. You stay on as a moderator. Type the relay name (\" + name + \") to confirm.\");\n if (typed === null) return;\n if (typed.trim() !== name) { toast(\"That didn't match; nothing changed.\"); return; }\n await rpc(\"transferowner\", pk);\n toast(\"Transferred\");\n await loadInfo(); await loadAdmin(); await loadPeople();\n });\n // ---- fork: a new name with this relay's events, claim reserved for a key ----\n $(\"#forkform\").scope.onchange = (ev) => $(\"#forkkinds\").classList.toggle(\"hidden\", ev.target.value !== \"kinds\");\n $(\"#joinform\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n policy = await rpc(\"setpolicy\", { joinTerms: f.joinTerms.value, directoryPublic: f.directoryPublic.checked });\n toast(\"Saved\"); await loadInfo(); await loadPeople();\n });\n $(\"#forkform\").onsubmit = guard(async (ev) => {\n const f = ev.target;\n const opts = { people: f.people.checked };\n if (f.name.value.trim()) opts.name = f.name.value.trim().toLowerCase();\n if (f.holder.value.trim()) { const pk = npubToHex(f.holder.value); if (!pk) throw new Error(\"That is not a pubkey.\"); opts.holder = pk; }\n if (f.scope.value === \"mine\") opts.filter = { authors: [me] };\n if (f.scope.value === \"kinds\") { const kinds = f.kinds.value.split(/[\\s,]+/).filter(Boolean).map(Number); if (!kinds.length || kinds.some((k) => !Number.isInteger(k) || k < 0)) throw new Error(\"Give kinds as numbers.\"); opts.filter = { kinds }; }\n if (!confirm(\"Fork this relay into a new name\" + (opts.name ? \" (\" + opts.name + \")\" : \"\") + \"? It pulls \" + (f.scope.value === \"all\" ? \"everything\" : f.scope.value === \"mine\" ? \"your events\" : \"the chosen kinds\") + (opts.people ? \" and the people\" : \"\") + \", and only \" + (opts.holder ? \"that key\" : \"you\") + \" can claim it.\")) return;\n const r = await rpc(\"forkrelay\", opts);\n $(\"#forknote\").textContent = r.handover + \" Expires \" + fmtTime(r.expires_at) + \".\";\n $(\"#forkurl\").textContent = r.console;\n $(\"#forkresult\").classList.remove(\"hidden\");\n toast(\"Forked to \" + r.name);\n });\n $(\"#forkcopy\").onclick = async () => { await navigator.clipboard.writeText($(\"#forkurl\").textContent); toast(\"copied\"); };\n $(\"#deleterelay\").onclick = guard(async () => {\n const name = host.split(\".\")[0];\n const typed = prompt(\"This deletes everything on \" + host + \" and gives the name up. Type the relay name (\" + name + \") to confirm.\");\n if (typed === null) return;\n if (typed.trim() !== name) { toast(\"That didn't match; nothing was deleted.\"); return; }\n await rpc(\"deleterelay\", name);\n localStorage.removeItem(\"me\");\n location.href = \"/\";\n });\n $(\"#topup\").onsubmit = guard((ev) => topUp(+ev.target.sats.value));\n $(\"#inv-copy\").onclick = async () => { await navigator.clipboard.writeText($(\"#inv-text\").value); toast(\"invoice copied\"); };\n $$(\"button[data-copy]\").forEach((b) => { b.onclick = async () => { await navigator.clipboard.writeText(b.dataset.copy === \"ws\" ? wsURL : location.origin); toast(\"copied\"); }; });\n document.addEventListener(\"click\", async (ev) => {\n const b = ev.target.closest(\"button[data-act]\"); if (!b) return;\n const act = b.dataset.act, id = b.dataset.id;\n if (act === \"copy\") { await navigator.clipboard.writeText(id); toast(\"copied\"); return; }\n if ((act === \"banpubkey\" || act === \"banevent\" || act === \"resolve:ban\") && !confirm(act === \"banevent\" ? \"Delete this event and refuse it forever?\" : \"Ban this author and refuse everything they post?\")) return;\n const erase = (act === \"banpubkey\" || act === \"resolve:ban\") && confirm(\"Also erase everything they wrote and uploaded here?\");\n if (act === \"deleteblob\" && !confirm(\"Delete this file for good?\")) return;\n if (act === \"deletedump\" && !confirm(\"Delete this dump?\")) return;\n if (act === \"downloaddump\") { b.disabled = true; try { await downloadDump(id); } catch (e) { toast(e.message); } finally { b.disabled = false; } return; }\n if ((act === \"removemember\" || act === \"banpubkey\") && (window.__members || []).some((m) => m.invited_by === id) && confirm(\"Also remove everyone this member invited, and everyone they invited in turn?\")) {\n b.disabled = true;\n try { const r = await rpc(\"removesubtree\", id); if (act === \"banpubkey\") await rpc(\"banpubkey\", id, \"\", erase); toast(\"Removed \" + r.removed.length); await refresh(); } catch (e) { toast(e.message); } finally { b.disabled = false; }\n return;\n }\n if (act === \"removejob\" && !confirm(\"Remove this job?\")) return;\n if (act === \"purgekind\") {\n const kind = id === \"\" ? null : +id;\n const label = kind === null ? \"everything without its own rule\" : kindName(kind) + \" (kind \" + kind + \")\";\n const typed = prompt(\"Purge \" + label + \" older than how many days? 0 purges all of them. This cannot be undone.\", \"30\");\n if (typed === null) return;\n const days = Math.max(0, Math.floor(+typed || 0));\n b.disabled = true;\n try { const r = await rpc(\"purgekind\", kind, days); toast(\"Purged \" + r.deleted.toLocaleString() + \" events\"); await refresh(); } catch (e) { toast(e.message); } finally { b.disabled = false; }\n return;\n }\n if (act === \"saveretention\") {\n const kind = id === \"\" ? null : +id;\n const days = Math.max(0, Math.floor(+b.closest(\"tr\").querySelector(\".days\").value || 0));\n b.disabled = true;\n try { await rpc(\"setretention\", kind, days); toast(days ? \"Kept for \" + days + \" days\" : \"Kept forever\"); await loadStorage(); await loadInfo(); } catch (e) { toast(e.message); } finally { b.disabled = false; }\n return;\n }\n b.disabled = true;\n try {\n if (act === \"savemember\") { const tr = b.closest(\"tr\"), role = tr.querySelector(\"select.role\"), keep = tr.querySelector(\".keep\"), cap = tr.querySelector(\".cap\"); await rpc(\"setmember\", id, { name: tr.querySelector(\".name\").value.trim() || null, note: tr.querySelector(\".note\").value, ...(role ? { role: role.value } : {}), ...(keep ? { keepDays: Math.max(0, Math.floor(+keep.value || 0)), maxBytes: Math.max(0, Math.floor(+cap.value || 0)) * 1024 } : {}) }); }\n else if (act.startsWith(\"resolve:\")) await rpc(\"resolvereport\", id, act.slice(8), erase);\n else if (act === \"banpubkey\") await rpc(\"banpubkey\", id, \"\", erase);\n else await rpc(act, act === \"unrulekind\" ? +id : id, \"\");\n toast(\"Done\"); await (myRole ? refresh() : loadMine());\n if (act === \"pinevent\" || act === \"unpinevent\") await loadPins();\n } catch (e) { toast(e.message); } finally { b.disabled = false; }\n });\n\n // The share block: the card picture, the group naddr and its QR.\n let card = null;\n async function loadCard() {\n try {\n card = await (await fetch(\"/card.json\", { cache: \"no-store\" })).json();\n $(\"#cardimg\").src = \"/card.svg?t=\" + Date.now();\n $(\"#naddr\").textContent = card.naddr || \"\";\n const q = $(\"#naddrqr\");\n if (card.naddr) { q.src = \"/qr.svg?text=\" + encodeURIComponent(card.naddr); q.classList.remove(\"hidden\"); } else q.classList.add(\"hidden\");\n } catch { /* the card is decoration */ }\n renderApps();\n }\n // The app rows on the Connect section: one per client people actually use,\n // with the link that lands on this relay in it. Relay apps take the relay\n // or the group address; feed apps take the owner's profile with this relay\n // as the hint, since they have no notion of opening a relay.\n function renderApps() {\n const el = $(\"#apps\"); if (!el) return;\n const enc = encodeURIComponent;\n const nprofile = card && card.nprofile ? card.nprofile : \"\";\n const naddr = card && card.naddr ? card.naddr : \"\";\n const whose = me && owner && me === owner ? \"your\" : \"the owner's\";\n const link = (label, href) => '' + label + \"\";\n const app = (label, uri) => '' + label + \"\";\n const copy = (label, text) => '\";\n const row = (name, where, note, acts) => '
                ' + name + \"\" + where + \"

                \" + note + '

                ' + acts.filter(Boolean).join(\"\") + \"
                \";\n const profileNote = \"Opens \" + whose + \" profile with this relay attached.\";\n const groups = [\n [\"As a place\", \"These open the relay itself: its feed, its people, its group.\", [\n row(\"Jumble\", \"web\", \"A feed of everything on this relay.\", [link(\"Open\", \"https://jumble.social/?r=\" + enc(wsURL))]),\n row(\"Coracle\", \"web\", \"The relay's page: its feed and its people.\", [link(\"Open\", \"https://coracle.social/relays/\" + enc(host))]),\n row(\"Flotilla\", \"web, phone\", \"The relay as a space, with the group as a room.\", [link(\"Open\", \"https://app.flotilla.social/spaces/\" + enc(host)), naddr && app(\"Open group\", \"nostr:\" + naddr)]),\n row(\"0xchat\", \"phone\", \"The group, in a chat app.\", [naddr && app(\"Open group\", \"nostr:\" + naddr), naddr && copy(\"Copy naddr\", naddr)]),\n row(\"noStrudel\", \"web\", \"Relays, add this one, then open its page.\", [copy(\"Copy relay URL\", wsURL)]),\n ]],\n [\"Find me here\", \"Feed apps have no relay pages. They meet this relay through a profile link that names it, then keep it once it is in the relay settings.\", [\n row(\"Primal\", \"web, phone\", profileNote, [nprofile && link(\"Open\", \"https://primal.net/p/\" + nprofile), nprofile && app(\"Open in app\", \"nostr:\" + nprofile)]),\n row(\"YakiHonne\", \"web, phone\", profileNote, [nprofile && link(\"Open\", \"https://yakihonne.com/profile/\" + nprofile), nprofile && app(\"Open in app\", \"nostr:\" + nprofile)]),\n row(\"Damus\", \"iPhone\", profileNote + \" Then Settings, Relays.\", [nprofile && app(\"Open in app\", \"nostr:\" + nprofile), copy(\"Copy relay URL\", wsURL)]),\n row(\"Amethyst\", \"Android\", profileNote + \" Then Relays in the drawer.\", [nprofile && app(\"Open in app\", \"nostr:\" + nprofile), copy(\"Copy relay URL\", wsURL)]),\n row(\"Nostur\", \"iPhone, Mac\", profileNote + \" Then Settings, Relays.\", [nprofile && app(\"Open in app\", \"nostr:\" + nprofile), copy(\"Copy relay URL\", wsURL)]),\n ]],\n ];\n if (info?.supported_grasps?.includes(\"GRASP-01\")) groups.push([\n \"Git repositories\", \"Use this relay with a Git client.\", [\n row(\"GitWorkshop\", \"web\", \"Browse and collaborate on Git repositories.\", [link(\"Open\", \"https://gitworkshop.dev/\"), copy(\"Copy relay URL\", wsURL)]),\n ],\n ]);\n el.innerHTML = groups.map(([h, note, rows]) => '

                ' + h + '

                ' + note + '

                ' + rows.join(\"\") + \"
                \").join(\"\");\n $(\"#apps-ws\").textContent = wsURL;\n const tile = (label, text) => '
                ' + label + '\"QR
                ';\n $(\"#phones\").innerHTML = [nprofile && tile(\"Find me here, for a phone\", \"nostr:\" + nprofile), naddr && tile(\"The group, for a phone\", \"nostr:\" + naddr)].filter(Boolean).join(\"\");\n }\n // The folds are a group: opening one closes the rest. Browsers with the\n // details name attribute do this themselves; this covers the others.\n $$(\".folds details\").forEach((d) => d.addEventListener(\"toggle\", () => { if (d.open) $$(\".folds details\").forEach((o) => { if (o !== d && o.open) o.open = false; }); }));\n document.addEventListener(\"click\", async (ev) => {\n const b = ev.target.closest(\"button[data-copytext]\"); if (!b) return;\n try { await navigator.clipboard.writeText(b.dataset.copytext); toast(\"copied\"); } catch { /* no clipboard */ }\n });\n $(\"#copynaddr\").onclick = async () => { if (!card || !card.naddr) return; await navigator.clipboard.writeText(card.naddr); toast(\"copied naddr\"); };\n $(\"#copyembed\").onclick = async () => { await navigator.clipboard.writeText('\"''); toast(\"copied embed\"); };\n\n // A click on a key copies it; a double-click selects the whole key so the usual copy shortcut takes it too.\n document.addEventListener(\"dblclick\", (ev) => {\n const k = ev.target.closest(\".key\"); if (!k) return;\n const s = window.getSelection(), r = document.createRange(); r.selectNodeContents(k.querySelector(\".full\")); s.removeAllRanges(); s.addRange(r);\n });\n document.addEventListener(\"click\", async (ev) => {\n const k = ev.target.closest(\".key\"); if (!k || ev.detail > 1 || String(window.getSelection())) return;\n try { await navigator.clipboard.writeText(k.title); toast(\"copied \" + k.dataset.short); } catch { /* no clipboard */ }\n });\n // ---- boot ----\n try { await loadInfo(); } catch { renderHeader(); }\n await loadFuel();\n await loadCard();\n me = localStorage.getItem(\"me\");\n if (me && await resumeRemote()) { /* a remote session answers for itself when first used */ }\n else if (me && window.nostr) { try { const pk = await window.nostr.getPublicKey(); if (pk !== me) me = null; } catch { me = null; } }\n else if (me) me = null;\n renderHeader();\n renderApps();\n await loadAdmin();\n await loadPeople();\n})();\n"; diff --git a/src/git-storage.ts b/src/git-storage.ts new file mode 100644 index 0000000..55b2329 --- /dev/null +++ b/src/git-storage.ts @@ -0,0 +1,49 @@ +// Owner-requested Git storage inventory. Repository identity selects the R2 +// namespace; server limits bound work and the report never permits deletion. +import { boundedInventory, R2InventoryListing, R2ObjectStore, LimitError, type InventoryLimits } from "ntig"; +import { repository } from "./grasp-state.ts"; +import { gitStoragePrefix } from "./grasp.ts"; +import { featureOn } from "./settings.ts"; +import { now } from "./event.ts"; +import type { Relay } from "./relay.ts"; + +export const GIT_INVENTORY_LIMITS: Readonly = Object.freeze({ + maxGets: 10_000, maxReadBytes: 16 * 1024 * 1024, maxObjectBytes: 4 * 1024 * 1024, + maxListedKeys: 10_000, maxPages: 100, maxIndexNodes: 10_000, maxReceipts: 10_000, + maxKeyBytes: 1024, maxCursorBytes: 8192, +}); +const nextInventory = new WeakMap(); +const failure = (error: string, status: number) => ({ body: { error }, status }); + +// gitStorage compares one complete physical inventory with quota reservations. +// The cooldown limits repeated manual scans in this instance, including failures. +export async function gitStorage(relay: Relay, owner: string, identifier: string) { + return relay.repositoryAccess.run("control", async () => { + if (!featureOn(relay.settings.policy, "grasp")) return failure("not found", 404); + if (relay.settings.isUnclaimed() || relay.settings.leaseExpired(now())) return failure("restricted: relay is not active", 403); + const repo = repository(relay, owner, identifier); + if (!repo) return failure("not found", 404); + if (relay.fuelStatus().outOfFuel) return failure("restricted: relay storage or fuel limit reached", 403); + const retryAfter = (nextInventory.get(relay) ?? 0) - now(); + if (retryAfter > 0) return { body: { error: "restricted: Git inventory cooldown; retry", retryAfter }, status: 429 }; + nextInventory.set(relay, now() + 60); + const operations = { gets: 0, lists: 0 }; + let completed = false; + try { + const prefix = await gitStoragePrefix(relay, repo); + const r2 = new R2ObjectStore(relay.media, { prefix, maxObjectBytes: GIT_INVENTORY_LIMITS.maxObjectBytes }); + const listing = new R2InventoryListing({ list: (options) => { operations.lists++; return relay.media.list(options); } }, { prefix, pageSize: 1000 }); + const inventory = await boundedInventory({ get: (key) => { operations.gets++; return r2.get(key); } }, listing, { prefix: "data/", limits: GIT_INVENTORY_LIMITS }); + const reservations = relay.sql.exec<{ keys: number; bytes: number }>(`SELECT count(*) AS keys, coalesce(sum(size),0) AS bytes FROM grasp_objects WHERE substr(key,1,?)=?`, prefix.length, prefix).one(); + completed = true; + return { body: { result: { repository: { owner, identifier, announcement: repo.id }, inventory, reservations, + reservationMinusListedBytes: reservations.bytes - inventory.listed.bytes, operations, limits: GIT_INVENTORY_LIMITS, + cooldownSeconds: 60, capturedAt: now() } }, status: 200 }; + } catch (error) { + return error instanceof LimitError ? failure("restricted: Git inventory limit reached; no complete report", 413) + : failure("error: Git inventory unavailable; no complete report", 503); + } finally { + console.log(JSON.stringify({ msg: "git-inventory", relay: relay.slug, ...operations, completed })); + } + }, () => failure("restricted: relay operation in progress; retry", 429)); +} diff --git a/src/grasp.ts b/src/grasp.ts index bd18836..b148666 100644 --- a/src/grasp.ts +++ b/src/grasp.ts @@ -21,10 +21,12 @@ const answer = (reason: string, status: number) => new Response(reason, { status // isGitPath reserves malformed Git paths too, so every failure has CORS. export const isGitPath = (url: URL) => /^\/(?:npub|prs\/)/.test(url.pathname) || /\.git(?:\/|$)/.test(url.pathname); +export const gitStoragePrefix = async (relay: Relay, repo: RepositoryAnnouncement) => `${relay.slug}/git/${await repositoryStoragePrefix(repositoryAddress(npubEncode(repo.owner), repo.identifier))}`; + // gitRepository records each R2 key's retained size, including orphan writes. // Reservations precede PUT: an ambiguous response never makes bytes free. export async function gitRepository(relay: Relay, repo: RepositoryAnnouncement): Promise { - const prefix = `${relay.slug}/git/${await repositoryStoragePrefix(repositoryAddress(npubEncode(repo.owner), repo.identifier))}`; + const prefix = await gitStoragePrefix(relay, repo); const r2 = new R2ObjectStore(relay.media, { prefix, maxObjectBytes: 4 * 1024 * 1024 }); const store: ObjectStore = { get: async (key) => r2.get(key), @@ -127,29 +129,28 @@ export async function grasp(relay: Relay, req: Request, url: URL): Promise${esc(repo.identifier)}

                Git storage follows signed Nostr repository state.

                Open in a Nostr Git client

                git clone ${esc(relay.webURL(url.host) + parsed.prefix)}
                `); - return new Response(req.method === "HEAD" ? null : html, { headers: { ...CORS, "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } }); + return relay.repositoryAccess.run("git", async () => { + try { + if (parsed.endpoint === "root") { + if (req.method !== "GET" && req.method !== "HEAD") return answer("invalid: method not allowed", 405); + const coordinate = naddrEncode({ kind: KIND_REPO, pubkey: repo.owner, identifier: repo.identifier }); + const html = page(repo.identifier, `

                ${esc(repo.identifier)}

                Git storage follows signed Nostr repository state.

                Open in a Nostr Git client

                git clone ${esc(relay.webURL(url.host) + parsed.prefix)}
                `); + return new Response(req.method === "HEAD" ? null : html, { headers: { ...CORS, "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } }); + } + const wal = await gitRepository(relay, repo); + const response = await wal.withReadSession(async (scopedWal) => { + const handler = createGitHandler(authorizedRepository(relay, repo, scopedWal), { prefix: parsed.prefix, authorizePush: () => true, observe: (event) => relay.meterBytes(event.requestBytes, event.responseBytes) }); + return await handler(req); + }); + const headers = new Headers(response.headers); + for (const [key, value] of Object.entries(CORS)) headers.set(key, value); + return new Response(response.body, { status: response.status, headers }); + } catch (error) { + return answer(error instanceof LimitError ? "restricted: Git repository limit reached" : "error: Git repository unavailable", error instanceof LimitError ? 413 : 503); + } finally { + await relay.ensureAlarm(now() + 60); } - const wal = await gitRepository(relay, repo); - const response = await wal.withReadSession(async (scopedWal) => { - const handler = createGitHandler(authorizedRepository(relay, repo, scopedWal), { prefix: parsed.prefix, authorizePush: () => true, observe: (event) => relay.meterBytes(event.requestBytes, event.responseBytes) }); - return await handler(req); - }); - const headers = new Headers(response.headers); - for (const [key, value] of Object.entries(CORS)) headers.set(key, value); - return new Response(response.body, { status: response.status, headers }); - } catch (error) { - return answer(error instanceof LimitError ? "restricted: Git repository limit reached" : "error: Git repository unavailable", error instanceof LimitError ? 413 : 503); - } finally { - relay.graspBusy = false; - await relay.ensureAlarm(now() + 60); - } + }, () => answer("restricted: relay operation in progress; retry", 429)); } // graspTick expires purgatory and cleans one repository per alarm. Event diff --git a/src/landing.ts b/src/landing.ts index 0aa0a54..e2b887c 100644 --- a/src/landing.ts +++ b/src/landing.ts @@ -98,7 +98,7 @@ const PROTOCOL: [string, string][] = [ ["94, 96", "The same files through the NIP-96 door, with NIP-94 metadata in every answer."], ["NIP-5A", "Root, named and snapshot websites from signed manifests, on isolated hostnames. Site hosting and mirroring are on by default; the relay's read rule governs access."], ["Marmot", "Opt-in KeyPackages and opaque MLS group messages. Account admission and caps apply to ephemeral authors; clients handle encryption."], - ["GRASP-01", "Opt-in public Git Smart HTTP. Signed NIP-34 state authorizes refs, and publication waits for matching Git objects. Later GRASP specifications are not advertised."], + ["GRASP-01", "Opt-in public Git Smart HTTP. Signed NIP-34 state authorizes refs, and publication waits for matching Git objects. Owners can inspect retained storage. Later GRASP specifications are not advertised."], ]; function table(heads: string[], rows: string[][], right: number[] = []): string { diff --git a/src/manage.ts b/src/manage.ts index 61322a5..f6ed79b 100644 --- a/src/manage.ts +++ b/src/manage.ts @@ -25,6 +25,7 @@ import { PRESETS, applyPreset, findPreset } from "./presets.ts"; import { addDomain, checkDomain, listDomains, removeDomain, setDomainSite } from "./domains.ts"; import { verifyNIP98 } from "./auth.ts"; import { SITE_KINDS, checkSite, siteLabel, sitePaths } from "./sites.ts"; +import { gitStorage } from "./git-storage.ts"; // A call: the relay and the request, who is calling and as what, the // parameters with their readers, and how to answer. @@ -455,6 +456,14 @@ export const METHODS: Record = { return reply({ result: { kinds, events: kinds.reduce((a, k) => a + k.n, 0), eventBytes: kinds.reduce((a, k) => a + k.bytes, 0), databaseBytes: relay.eventBytes(), blobs: blobs.n ?? 0, mediaBytes: blobs.bytes ?? 0, dumps: listDumps(relay.sql).length, dumpBytes: dumpBytes(relay.sql), retention: s.listRetention() } }); }, }, + gitstorage: { + action: "storage", reads: true, + run: async ({ relay, params, str, hex64, reply }) => { + if (params.length !== 2 || !hex64(str(0)) || typeof params[1] !== "string" || !str(1) || new TextEncoder().encode(str(1)).length > 256) return reply({ error: "invalid: expected repository owner hex pubkey and identifier" }, 400); + const result = await gitStorage(relay, str(0), str(1)); + return reply(result.body, result.status); + }, + }, setretention: { action: "rules", run: ({ s, params, num, reply }) => { @@ -735,36 +744,38 @@ export async function manage(relay: Relay, req: Request): Promise { const auth = verifyNIP98(req.headers.get("authorization") ?? "", req.url, req.method, bodyText); if (typeof auth === "string") return reply({ error: auth }, 401); - const s = relay.settings; - const p = s.policy; - const t = now(); - const caller = auth.pubkey; + return relay.repositoryAccess.run("control", async () => { + const s = relay.settings; + const p = s.policy; + const t = now(); + const caller = auth.pubkey; - const role = s.roleOf(caller); - const outranks = (pk: string) => role !== "owner" && (s.isOwner(pk) || s.roleOf(pk) === "moderator"); - const str = (i: number) => (typeof params[i] === "string" ? (params[i] as string) : ""); - const num = (i: number) => (Number.isInteger(params[i]) ? (params[i] as number) : parseInt(str(i), 10)); - const hex64 = (v: string) => /^[0-9a-f]{64}$/.test(v); - const call: Call = { relay, req, s, p, t, caller, role, method, params, str, num, hex64, reply, outranks }; - if (m.action === "open") return m.run(call); - // The heir may read the succession status: a member, with no console otherwise. - if (method === "successionstatus" && p.succession && p.succession.heir === caller) return reply({ result: await relay.succession.status() }); - // A plain member reaches their own invites when the owner opened the - // invite tree (memberInvites); the invite methods keep them to their own. - const ownInvites = role === "member" && p.memberInvites.depth > 0 && (method === "createinvite" || method === "listinvites" || method === "revokeinvite"); - if (role === "owner") void relay.succession.seen(caller); - if (!ownInvites && !can(role, m.action)) { - const why = role === "moderator" ? "restricted: moderators cannot do that" : p.owner !== "" ? "restricted: not the relay owner" : s.isLeased() ? "restricted: this is a temporary relay; claim it first" : "restricted: this relay is unclaimed"; - return reply({ error: why }, 403); - } - // Every method that changed something and answered 200 goes in the - // moderation log with who called it (audit.ts). deleterelay took the - // table with it. - const resp = await m.run(call); - const dryRun = method === "importconfig" && (params[1] as { dryRun?: unknown } | undefined)?.dryRun === true; - if (resp.status === 200 && !m.reads && !dryRun && method !== "deleterelay") { - const { target, detail } = detailOf(method, params); - relay.audit.record(t, caller, method, target, detail); - } - return resp; + const role = s.roleOf(caller); + const outranks = (pk: string) => role !== "owner" && (s.isOwner(pk) || s.roleOf(pk) === "moderator"); + const str = (i: number) => (typeof params[i] === "string" ? (params[i] as string) : ""); + const num = (i: number) => (Number.isInteger(params[i]) ? (params[i] as number) : parseInt(str(i), 10)); + const hex64 = (v: string) => /^[0-9a-f]{64}$/.test(v); + const call: Call = { relay, req, s, p, t, caller, role, method, params, str, num, hex64, reply, outranks }; + if (m.action === "open") return m.run(call); + // The heir may read the succession status: a member, with no console otherwise. + if (method === "successionstatus" && p.succession && p.succession.heir === caller) return reply({ result: await relay.succession.status() }); + // A plain member reaches their own invites when the owner opened the + // invite tree (memberInvites); the invite methods keep them to their own. + const ownInvites = role === "member" && p.memberInvites.depth > 0 && (method === "createinvite" || method === "listinvites" || method === "revokeinvite"); + if (role === "owner") void relay.succession.seen(caller); + if (!ownInvites && !can(role, m.action)) { + const why = role === "moderator" ? "restricted: moderators cannot do that" : p.owner !== "" ? "restricted: not the relay owner" : s.isLeased() ? "restricted: this is a temporary relay; claim it first" : "restricted: this relay is unclaimed"; + return reply({ error: why }, 403); + } + // Every method that changed something and answered 200 goes in the + // moderation log with who called it (audit.ts). deleterelay took the + // table with it. + const resp = await m.run(call); + const dryRun = method === "importconfig" && (params[1] as { dryRun?: unknown } | undefined)?.dryRun === true; + if (resp.status === 200 && !m.reads && !dryRun && method !== "deleterelay") { + const { target, detail } = detailOf(method, params); + relay.audit.record(t, caller, method, target, detail); + } + return resp; + }, () => new Response(JSON.stringify({ error: "restricted: relay operation in progress; retry" }), { status: 429, headers: { ...cors, "retry-after": "1" } })); } diff --git a/src/relay.ts b/src/relay.ts index d44be07..0d1290a 100644 --- a/src/relay.ts +++ b/src/relay.ts @@ -18,7 +18,7 @@ import { Settings, isReplaceable, isProtected, featureOn } from "./settings.ts"; import { blobBytes, type Blob } from "./blossom.ts"; import { DIGEST_DAYS, digestText, notify, fuelLow, fuelText } from "./notify.ts"; import { Succession } from "./succession.ts"; -import { isGated, route } from "./routes.ts"; +import { isGated, isManagementRequest, route } from "./routes.ts"; import { guestPass, readGate, writeGate } from "./gates.ts"; import { Fuel, fuelConfig, acceptReceipt, type Fetcher, type LnurlParams } from "./fuel.ts"; import { Identity } from "./identity.ts"; @@ -35,6 +35,7 @@ import { groupFacts, handleGroupEvent, isGroupManagement, isNIP43Request } from import { markView, notePresence, viewsTick } from "./views.ts"; import { KIND_VANISH, KIND_AUTH, KIND_REPORT, KIND_NOSTR_CONNECT, KIND_GROUP_MEMBERS, KIND_GROUP_PINS, KIND_RELAY_DISCOVERY, KIND_MARMOT_GROUP } from "./kinds.ts"; import { marmotPrincipal } from "./marmot.ts"; +import { RepositoryAccess } from "./repository-access.ts"; export interface Env { RELAY: DurableObjectNamespace; @@ -127,8 +128,7 @@ export class Relay extends DurableObject { succession = new Succession(this); // A job round in flight, so overlapping alarms do not run two. private working = false; - graspBusy = false; - graspControls = 0; + readonly repositoryAccess = new RepositoryAccess(); // Presence (views.ts): who wrote lately, in memory; the sockets are asked // directly. A broadcast is at most one per PRESENCE_THROTTLE_S. presenceActive = new Map(); @@ -449,7 +449,8 @@ export class Relay extends DurableObject { // teardown deletes everything this relay holds and returns the name to // unclaimed. Every socket is closed. Nothing is recoverable afterwards. - async teardown() { + async teardown(): Promise { + if (!this.repositoryAccess.owned) return this.repositoryAccess.run("teardown", () => this.teardown(), () => { throw new Error("relay operation in progress; retry teardown"); }); await forgetSites(this); await forgetDomains(this); for (const ws of this.ctx.getWebSockets()) { @@ -528,22 +529,24 @@ export class Relay extends DurableObject { // holder "" lets anyone claim; a pubkey reserves the claim. Returns "" or // a reason. async lease(name: string, host: string, until: number, holder: string): Promise { - if (!this.settings.isUnclaimed()) return "taken"; - if (this.slug !== name) { - this.slug = name; - await this.ctx.storage.put("slug", name); - } - const day = new Date(until * 1000).toISOString().slice(0, 10); - this.settings.update({ - lease: { until, holder }, - writes: "open", - reads: "open", - name: "", - description: `Temporary relay. Anyone can read and write here until ${day}; then everything on it is deleted. To keep it, claim it at https://${host}/ (sign once). Or claim a new name and pull from this one.`, - }); - this.settings.setRetention(null, LEASE_RETENTION_DAYS); - await this.ensureAlarm(until); - return ""; + return this.repositoryAccess.run("control", async () => { + if (!this.settings.isUnclaimed()) return "taken"; + if (this.slug !== name) { + this.slug = name; + await this.ctx.storage.put("slug", name); + } + const day = new Date(until * 1000).toISOString().slice(0, 10); + this.settings.update({ + lease: { until, holder }, + writes: "open", + reads: "open", + name: "", + description: `Temporary relay. Anyone can read and write here until ${day}; then everything on it is deleted. To keep it, claim it at https://${host}/ (sign once). Or claim a new name and pull from this one.`, + }); + this.settings.setRetention(null, LEASE_RETENTION_DAYS); + await this.ensureAlarm(until); + return ""; + }, () => "restricted: relay operation in progress; retry"); } // ---- forking: a new name, this relay's events pulled into it ---- @@ -580,14 +583,16 @@ export class Relay extends DurableObject { // adoptFrom is the forked side, reached over RPC only: a fresh lease // takes the people and starts pulling from the source. async adoptFrom(sourceURL: string, filter: PullFilter, people: { pubkey: string; name: string | null; note: string }[], sourceHost: string): Promise { - if (!this.settings.isLeased()) return "restricted: only a fresh lease can adopt"; - if (this.store.stats().events > 0) return "restricted: this lease already holds events"; - const day = new Date((this.settings.policy.lease?.until ?? 0) * 1000).toISOString().slice(0, 10); - this.settings.update({ description: `Forked from ${sourceHost}. Temporary until ${day} unless claimed; then everything on it is deleted. Claim it to keep it.` }); - const t = now(); - for (const m of people) this.settings.upsertMember(m.pubkey, { name: m.name, note: m.note, via: "forked" }, t, true); - const r = await this.addChecked({ kind: "pull", label: "pull", relays: [sourceURL], filter, every: 0, running: false, startedAt: 0, rounds: 0, failures: 0, relayIndex: 0, cursor: 0, stored: 0, skipped: 0, blobs: 0, sent: 0, refused: 0, last: null }); - return typeof r === "string" ? r : ""; + return this.repositoryAccess.run("control", async () => { + if (!this.settings.isLeased()) return "restricted: only a fresh lease can adopt"; + if (this.store.stats().events > 0) return "restricted: this lease already holds events"; + const day = new Date((this.settings.policy.lease?.until ?? 0) * 1000).toISOString().slice(0, 10); + this.settings.update({ description: `Forked from ${sourceHost}. Temporary until ${day} unless claimed; then everything on it is deleted. Claim it to keep it.` }); + const t = now(); + for (const m of people) this.settings.upsertMember(m.pubkey, { name: m.name, note: m.note, via: "forked" }, t, true); + const r = await this.addChecked({ kind: "pull", label: "pull", relays: [sourceURL], filter, every: 0, running: false, startedAt: 0, rounds: 0, failures: 0, relayIndex: 0, cursor: 0, stored: 0, skipped: 0, blobs: 0, sent: 0, refused: 0, last: null }); + return typeof r === "string" ? r : ""; + }, () => "restricted: relay operation in progress; retry"); } // ---- jobs: pulls, backfills, rebroadcasts, once or standing ---- @@ -760,16 +765,23 @@ export class Relay extends DurableObject { } async fetch(req: Request): Promise { - this.touch(); - const name = req.headers.get("x-relay-name"); - if (name && name !== this.slug) { - this.slug = name; - await this.ctx.storage.put("slug", name); - } const url = new URL(req.url); const completed = (response: Response) => featureOn(this.settings.policy, "grasp") ? graspCORS(response, req.method === "OPTIONS") : response; - // Relays claimed before identities existed get theirs on first contact. - if (this.settings.policy.owner && !this.identity.pubkey) await this.publishMembership(); + const name = req.headers.get("x-relay-name"); + const initializes = Boolean(name && name !== this.slug) || Boolean(this.settings.policy.owner && !this.identity.pubkey); + this.touch(); + if (initializes) { + const initialized = await this.repositoryAccess.run("control", async () => { + if (name && name !== this.slug) { + this.slug = name; + await this.ctx.storage.put("slug", name); + } + // Relays claimed before identities existed get theirs on first contact. + if (this.settings.policy.owner && !this.identity.pubkey) await this.publishMembership(); + return true; + }, () => false); + if (!initialized) return completed(new Response(JSON.stringify({ error: "restricted: relay operation in progress; retry" }), { status: 429, headers: { "content-type": "application/json", "access-control-allow-origin": "*", "retry-after": "1" } })); + } // The local custom-domain record wins over a cached edge mapping, so // changing a relay domain into a site never exposes the old relay door. const domainSite = this.settings.policy.customHosts?.find((h) => h.host === url.hostname)?.site; @@ -783,10 +795,10 @@ export class Relay extends DurableObject { if (site) return serveSite(this, req, site); if (upgrade) return this.acceptWebSocket(req); if (isGitPath(url)) return route(this, req, url); + // Management parses and verifies the request before acquiring authority. + if (isManagementRequest(req)) return completed(await route(this, req, url)); if (req.method !== "GET" && req.method !== "HEAD" && req.method !== "OPTIONS") { - if (this.graspBusy) return completed(new Response("restricted: Git transaction in progress; retry", { status: 429, headers: { "access-control-allow-origin": "*", "retry-after": "1" } })); - this.graspControls++; - try { return completed(await route(this, req, url)); } finally { this.graspControls--; } + return completed(await this.repositoryAccess.run("control", () => route(this, req, url), () => new Response(JSON.stringify({ error: "restricted: relay operation in progress; retry" }), { status: 429, headers: { "content-type": "application/json", "access-control-allow-origin": "*", "retry-after": "1" } }))); } return completed(await route(this, req, url)); } @@ -970,14 +982,15 @@ export class Relay extends DurableObject { // acceptAny routes the special kinds (zap receipts, NIP-56 reports) and // falls back to the ordinary write path. Callers broadcast when stored. async acceptAny(e: Event, conn: ConnState): Promise<{ ok: boolean; msg: string; stored: boolean }> { - if (this.graspBusy) return { ok: false, msg: "restricted: Git transaction in progress; retry the event", stored: false }; - if (e.kind === 9735) { - const r = await acceptReceipt(this, e, conn.host); - if (r) return r; - } - if (e.kind === KIND_REPORT) return this.acceptReport(e, conn.host); - if (isGroupManagement(e.kind) && (hasTag(e, "h") || isNIP43Request(e.kind))) return this.acceptGroup(e, conn); - return this.accept(e, conn); + return this.repositoryAccess.run("event", async () => { + if (e.kind === 9735) { + const r = await acceptReceipt(this, e, conn.host); + if (r) return r; + } + if (e.kind === KIND_REPORT) return this.acceptReport(e, conn.host); + if (isGroupManagement(e.kind) && (hasTag(e, "h") || isNIP43Request(e.kind))) return this.acceptGroup(e, conn); + return this.accept(e, conn); + }, () => ({ ok: false, msg: "restricted: relay operation in progress; retry the event", stored: false })); } // acceptGroup handles NIP-29 joins, leaves and moderation: the common gate, @@ -1023,6 +1036,7 @@ export class Relay extends DurableObject { // accept runs the write-side rules and stores the event. conn is null for // host-side publishes (the dashboard), which skip client policy. accept(e: Event, conn: ConnState | null): { ok: boolean; msg: string; stored: boolean } { + if (!this.repositoryAccess.owned) return this.repositoryAccess.sync("event", () => this.accept(e, conn), () => ({ ok: false, msg: "restricted: relay operation in progress; retry the event", stored: false })); const p = this.settings.policy; const t = now(); const no = (msg: string) => ({ ok: false, msg, stored: false }); @@ -1087,74 +1101,72 @@ export class Relay extends DurableObject { } async alarm() { - if (this.graspBusy) { await this.ctx.storage.setAlarm(Date.now() + 1000); return; } - this.graspControls++; - try { - this.touch(); - const t = now(); - // A lease that has run out is wiped whole: the name is free again. - if (this.settings.leaseExpired(t)) { - await this.teardown(); - return; - } - const graspAt = await graspTick(this); - await this.syncSites(); - await queueMirrors(this); - if (await this.jobsTick()) { - await this.ctx.storage.setAlarm(Date.now() + 250); - return; - } - this.flushUsage(); - this.fuel.chargeStorage(t, this.eventBytes(), this.mediaBytes()); - this.store.drain(); - this.sweepRetention(t); - await viewsTick(this, t); - await this.publishDiscovery(); - // Fuel notice: once when it turns low, then once a day while it stays low. - if (this.settings.policy.notify.fuel) { - const low = fuelLow(this.fuelStatus()); - const last = (await this.ctx.storage.get("fuel-low-at")) ?? 0; - if (low && t - last >= 86400) { - await this.ctx.storage.put("fuel-low-at", t); - await notify(this, "fuel", fuelText(this, this.fuelStatus()), "fuel on " + this.slug); - } else if (!low && last) await this.ctx.storage.delete("fuel-low-at"); - } - // Succession: the dead-man's switch, checked once a day. - await this.succession.tick(t); - // ---- digest: one message a week on how the relay is doing ---- - if (this.settings.policy.notify.digest && this.settings.policy.owner !== "") { - const last = (await this.ctx.storage.get("lastDigest")) ?? 0; - if (last === 0) await this.ctx.storage.put("lastDigest", t); - else if (t - last >= DIGEST_DAYS * 86400 - 3600) { - await this.ctx.storage.put("lastDigest", t); - await notify(this, "digest", await digestText(this, last, t), "the week on " + this.slug); + return this.repositoryAccess.run("alarm", async () => { + this.touch(); + const t = now(); + // A lease that has run out is wiped whole: the name is free again. + if (this.settings.leaseExpired(t)) { + await this.teardown(); + return; } - } - // ---- end digest ---- - const next = this.store.sweepExpired(t); - if (await this.syncSites()) { - await this.ctx.storage.setAlarm(Date.now() + 250); - return; - } - // ---- dumps: a scheduled JSONL of everything, into R2 (dumps.ts) ---- - if (dumpDue(this, t)) { - try { - await writeDump(this, t); - } catch (err) { - console.log("dump failed: " + (err instanceof Error ? err.message : String(err))); + const graspAt = await graspTick(this); + await this.syncSites(); + await queueMirrors(this); + if (await this.jobsTick()) { + await this.ctx.storage.setAlarm(Date.now() + 250); + return; } - } - // ---- end dumps ---- - let at = t + 86400; - if (this.sql.exec(`SELECT 1 FROM site_mirror_queue LIMIT 1`).toArray().length) at = Math.min(at, t + 60); - if (next > 0 && next < at) at = next; - const lease = this.settings.policy.lease; - if (this.settings.isLeased() && lease && lease.until < at) at = lease.until; - const run = await this.nextJobRun(); - if (run > 0 && run < at) at = Math.max(run, t + 1); - if (graspAt && graspAt < at) at = graspAt; - await this.ctx.storage.setAlarm(at * 1000 + 500); - } finally { this.graspControls--; } + this.flushUsage(); + this.fuel.chargeStorage(t, this.eventBytes(), this.mediaBytes()); + this.store.drain(); + this.sweepRetention(t); + await viewsTick(this, t); + await this.publishDiscovery(); + // Fuel notice: once when it turns low, then once a day while it stays low. + if (this.settings.policy.notify.fuel) { + const low = fuelLow(this.fuelStatus()); + const last = (await this.ctx.storage.get("fuel-low-at")) ?? 0; + if (low && t - last >= 86400) { + await this.ctx.storage.put("fuel-low-at", t); + await notify(this, "fuel", fuelText(this, this.fuelStatus()), "fuel on " + this.slug); + } else if (!low && last) await this.ctx.storage.delete("fuel-low-at"); + } + // Succession: the dead-man's switch, checked once a day. + await this.succession.tick(t); + // ---- digest: one message a week on how the relay is doing ---- + if (this.settings.policy.notify.digest && this.settings.policy.owner !== "") { + const last = (await this.ctx.storage.get("lastDigest")) ?? 0; + if (last === 0) await this.ctx.storage.put("lastDigest", t); + else if (t - last >= DIGEST_DAYS * 86400 - 3600) { + await this.ctx.storage.put("lastDigest", t); + await notify(this, "digest", await digestText(this, last, t), "the week on " + this.slug); + } + } + // ---- end digest ---- + const next = this.store.sweepExpired(t); + if (await this.syncSites()) { + await this.ctx.storage.setAlarm(Date.now() + 250); + return; + } + // ---- dumps: a scheduled JSONL of everything, into R2 (dumps.ts) ---- + if (dumpDue(this, t)) { + try { + await writeDump(this, t); + } catch (err) { + console.log("dump failed: " + (err instanceof Error ? err.message : String(err))); + } + } + // ---- end dumps ---- + let at = t + 86400; + if (this.sql.exec(`SELECT 1 FROM site_mirror_queue LIMIT 1`).toArray().length) at = Math.min(at, t + 60); + if (next > 0 && next < at) at = next; + const lease = this.settings.policy.lease; + if (this.settings.isLeased() && lease && lease.until < at) at = lease.until; + const run = await this.nextJobRun(); + if (run > 0 && run < at) at = Math.max(run, t + 1); + if (graspAt && graspAt < at) at = graspAt; + await this.ctx.storage.setAlarm(at * 1000 + 500); + }, async () => { await this.ctx.storage.setAlarm(Date.now() + 1000); }); } // sweepRetention applies the owner's keep-for rules. Returns how many diff --git a/src/repository-access.ts b/src/repository-access.ts new file mode 100644 index 0000000..c14f8e2 --- /dev/null +++ b/src/repository-access.ts @@ -0,0 +1,37 @@ +// One live relay operation owns repository authority across awaits. Async +// context carries the owner token; the active lease grants admission. This +// is neither a durable lock nor authority to collect retained Git objects. +import { AsyncLocalStorage } from "node:async_hooks"; + +type Kind = "git" | "control" | "alarm" | "event" | "teardown"; +type Lease = { kind: Kind; holders: number }; + +export class RepositoryAccess { + private readonly context = new AsyncLocalStorage(); + private active?: Lease; + + get busy() { return this.active !== undefined; } + get owned() { return this.active !== undefined && this.context.getStore() === this.active; } + get blocked() { return this.busy && !this.owned; } + get kind() { return this.active?.kind; } + + async run(kind: Kind, work: () => Promise | T, refused: () => Promise | T): Promise { + if (this.blocked) return refused(); + const lease = this.active ??= { kind, holders: 0 }; + lease.holders++; + try { return await this.context.run(lease, work); } + finally { this.release(lease); } + } + + sync(kind: Kind, work: () => T, refused: () => T): T { + if (this.blocked) return refused(); + const lease = this.active ??= { kind, holders: 0 }; + lease.holders++; + try { return this.context.run(lease, work); } + finally { this.release(lease); } + } + + private release(lease: Lease) { + if (--lease.holders === 0 && this.active === lease) this.active = undefined; + } +} diff --git a/src/routes.ts b/src/routes.ts index fec8da8..7265e07 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -42,6 +42,7 @@ const is = (...paths: string[]) => (url: URL) => paths.includes(url.pathname); const under = (prefix: string) => (url: URL) => url.pathname.startsWith(prefix); const get = (when: (url: URL) => boolean) => (url: URL, req: Request) => req.method === "GET" && when(url); const post = (when: (url: URL) => boolean) => (url: URL, req: Request) => req.method === "POST" && when(url); +export const isManagementRequest = (req: Request) => req.method === "POST" && (req.headers.get("content-type")?.includes("application/nostr+json+rpc") ?? false); export const ROUTES: Route[] = [ { when: isGitPath, gated: true, answer: grasp }, @@ -51,7 +52,7 @@ export const ROUTES: Route[] = [ answer: (relay, _, url) => Response.json(nip11(relay, url.host), { headers: { "content-type": "application/nostr+json", ...CORS } }), }, // NIP-86 management, by the content type. - { when: (_, req) => req.method === "POST" && (req.headers.get("content-type")?.includes("application/nostr+json+rpc") ?? false), answer: manage }, + { when: (_, req) => isManagementRequest(req), answer: manage }, // The HTTP bridge (bridge.ts). { when: post(is("/events", "/query", "/count")), gated: true, answer: bridge }, // NIP-05 names, under the read rule for whoever asks. diff --git a/test/helpers/relay.ts b/test/helpers/relay.ts index af83a2c..04d41da 100644 --- a/test/helpers/relay.ts +++ b/test/helpers/relay.ts @@ -21,8 +21,14 @@ export async function rpc(host: string, sk: Uint8Array | null, method: string, . const payload = { method, params }; const headers: Record = { "content-type": "application/nostr+json+rpc" }; if (sk) headers.authorization = await nip98(sk, url, "POST", payload); - const resp = await SELF.fetch(url, { method: "POST", headers, body: JSON.stringify(payload) }); - return { status: resp.status, ...(await resp.json()) }; + // Background alarms may own admission between management calls. Retry only + // this transient refusal; quota, rate and inventory cooldown errors surface. + for (let attempt = 0; ; attempt++) { + const resp = await SELF.fetch(url, { method: "POST", headers, body: JSON.stringify(payload) }); + const result = { status: resp.status, ...(await resp.json()) }; + if (result.status !== 429 || result.error !== "restricted: relay operation in progress; retry" || attempt >= 20) return result; + await sleep(50); + } } // info reads the NIP-11 document. diff --git a/test/object/exposure.test.ts b/test/object/exposure.test.ts index 3fba1ee..b3c565c 100644 --- a/test/object/exposure.test.ts +++ b/test/object/exposure.test.ts @@ -81,6 +81,17 @@ function doors(f: Fixture): { path: string; host?: string; method?: string; gate const leaks = (text: string, secrets: string[]) => secrets.filter((s) => text.includes(s)); describe("the read rule at every door", () => { + it("keeps Git storage inventory owner-only at the management door", async () => { + const host = "exposure-git-storage.bind.ws"; + const owner = generateSecretKey(); + const stranger = generateSecretKey(); + await rpc(host, owner, "claim"); + expect((await rpc(host, null, "gitstorage", pk(owner), "missing")).status).toBe(401); + expect((await rpc(host, stranger, "gitstorage", pk(owner), "missing")).status).toBe(403); + const methods = (await rpc(host, owner, "supportedmethods")).result as string[]; + expect(methods).toContain("gitstorage"); + }); + it("shows a stranger nothing of a member, her note or her file", async () => { const f = await seed("exposure-stranger.bind.ws"); for (const d of doors(f)) { diff --git a/test/object/git-storage.test.ts b/test/object/git-storage.test.ts new file mode 100644 index 0000000..05ab70d --- /dev/null +++ b/test/object/git-storage.test.ts @@ -0,0 +1,194 @@ +// Owner-only inventory reports compare a bounded physical listing with the +// repository root and the durable reservation ledger. They never mutate R2. +import { env, runInDurableObject } from "cloudflare:test"; +import { describe, expect, it } from "vitest"; +import { generateSecretKey } from "nostr-tools/pure"; +import { npubEncode } from "nostr-tools/nip19"; +import { encodePack } from "ntig"; +import { KIND_REPO, KIND_REPO_STATE } from "../../src/kinds.ts"; +import { gitRepositoryPath } from "../../src/grasp-policy.ts"; +import { repository } from "../../src/grasp-state.ts"; +import { gitRepository } from "../../src/grasp.ts"; +import type { Relay } from "../../src/relay.ts"; +import { ev, nip98, pk, rpc } from "../helpers/relay.ts"; +import { WS } from "../helpers/ws.ts"; + +const encoder = new TextEncoder(); +const objectID = async (type: string, bytes: Uint8Array) => { + const head = encoder.encode(`${type} ${bytes.length}\0`); + const input = new Uint8Array(head.length + bytes.length); + input.set(head); input.set(bytes, head.length); + return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-1", input)), (b) => b.toString(16).padStart(2, "0")).join(""); +}; +async function tinyPack() { + const blob = encoder.encode("inventory\n"); + const blobID = await objectID("blob", blob); + const tree = new Uint8Array([...encoder.encode("100644 README\0"), ...Uint8Array.from(blobID.match(/../g)!, (x) => parseInt(x, 16))]); + const treeID = await objectID("tree", tree); + const commit = encoder.encode(`tree ${treeID}\nauthor inventory 1 +0000\ncommitter inventory 1 +0000\n\ninitial\n`); + const commitID = await objectID("commit", commit); + return { commitID, pack: await encodePack([{ type: "blob", data: blob }, { type: "tree", data: tree }, { type: "commit", data: commit }]) }; +} +async function seed(host: string, format = 1) { + const owner = generateSecretKey(); + const stranger = generateSecretKey(); + const moderator = generateSecretKey(); + const identifier = "inventory"; + await rpc(host, owner, "claim"); + await rpc(host, owner, "applypreset", "grasp"); + await rpc(host, owner, "setmember", pk(moderator), { role: "moderator" }); + const path = gitRepositoryPath(npubEncode(pk(owner)), identifier); + const c = await WS.connect(host); + const announcement = ev(owner, KIND_REPO, "", [["d", identifier], ["clone", `https://${host}${path}`], ["relays", `wss://${host}`], ["maintainers", pk(owner)]]); + expect((await c.ok(announcement)).ok).toBe(true); + c.ws.close(); + const pack = await tinyPack(); + await runInDurableObject(env.RELAY.getByName(host.split(".")[0]), async (relay) => { + const repo = repository(relay, pk(owner), identifier)!; + await relay.repositoryAccess.run("control", async () => { + const wal = await gitRepository(relay, repo); + await wal.commit({ id: "inventory-initial", updates: [{ name: "refs/heads/main", old: null, new: pack.commitID }], pack: pack.pack }); + if (format === 2) await wal.checkpoint(); + }, () => Promise.reject(new Error("repository access unexpectedly refused during fixture setup"))); + }); + return { owner, stranger, moderator, identifier }; +} + +async function scan(relay: Relay, host: string, owner: Uint8Array, identifier: string) { + const url = `http://${host}/`; + const payload = { method: "gitstorage", params: [pk(owner), identifier] }; + const authorization = await nip98(owner, url, "POST", payload); + return relay.fetch(new Request(url, { method: "POST", headers: { authorization, "content-type": "application/nostr+json+rpc" }, body: JSON.stringify(payload) })); +} + +function proxyBucket(relay: Relay, overrides: Record) { + const original = relay.media; + const calls: string[] = []; + const observed = new Proxy(original, { get(target, name) { + calls.push(String(name)); + if (name in overrides) return overrides[name as string]; + if (name !== "get" && name !== "list") throw new Error(`unexpected R2 method ${String(name)}`); + const value = Reflect.get(target, name, target); + return typeof value === "function" ? value.bind(target) : value; + } }); + Object.defineProperty(relay, "media", { value: observed, configurable: true }); + return { calls, restore: () => Object.defineProperty(relay, "media", { value: original, configurable: true }) }; +} + +describe("Git storage inventory management", () => { + it.each([1, 2])("returns a complete format-%i report only to the owner", async (format) => { + const host = `git-storage-owner-${format}.bind.ws`; + const f = await seed(host, format); + const report = await rpc(host, f.owner, "gitstorage", pk(f.owner), f.identifier); + expect(report.status, JSON.stringify(report)).toBe(200); + expect(report.result.inventory.format).toBe(format); + expect(report.result.inventory.sequence).toBe(1); + expect(report.result.inventory.listed.keys).toBeGreaterThanOrEqual(3); + expect(report.result.inventory.listed.bytes).toBeGreaterThan(0); + expect(report.result.inventory.live.keys).toBe(report.result.inventory.listed.keys); + expect(report.result.reservations.keys).toBe(report.result.inventory.listed.keys); + expect(report.result.reservationMinusListedBytes).toBe(0); + expect(report.result.operations.gets).toBeGreaterThan(0); + expect(report.result.operations.lists).toBeGreaterThan(0); + + expect((await rpc(host, null, "gitstorage", pk(f.owner), f.identifier)).status).toBe(401); + expect((await rpc(host, f.stranger, "gitstorage", pk(f.owner), f.identifier)).status).toBe(403); + expect((await rpc(host, f.moderator, "gitstorage", pk(f.owner), f.identifier)).status).toBe(403); + expect((await rpc(host, f.owner, "gitstorage", "not-a-pubkey", f.identifier)).status).toBe(400); + expect((await rpc(host, f.owner, "gitstorage", pk(f.owner), "")).status).toBe(400); + expect((await rpc(host, f.owner, "gitstorage", pk(f.owner), "../data")).status).toBe(404); + expect((await rpc(host, f.owner, "gitstorage", pk(f.owner), f.identifier)).status).toBe(429); + }); + + it("uses only R2 get and list for a successful owner scan and releases its control scope", async () => { + const host = "git-storage-methods.bind.ws"; + const f = await seed(host); + const result = await runInDurableObject(env.RELAY.getByName(host.split(".")[0]), async (relay) => { + const bucket = proxyBucket(relay, {}); + try { + const response = await scan(relay, host, f.owner, f.identifier); + expect(response.status).toBe(200); + const report = await response.json(); + expect(report.result.reservations.bytes).toBe(report.result.inventory.listed.bytes); + expect(report.result.inventory.authority).toBe(false); + expect(report.result.inventory.gcCandidate).toBe(false); + const before = bucket.calls.length; + expect((await scan(relay, host, f.owner, f.identifier)).status).toBe(429); + expect(bucket.calls).toHaveLength(before); + return { calls: bucket.calls, busy: relay.repositoryAccess.busy }; + } finally { bucket.restore(); } + }); + expect(result.calls.filter((name: string) => name === "get" || name === "list").length).toBe(result.calls.length); + expect(result.calls).toContain("get"); + expect(result.calls).toContain("list"); + expect(result.busy).toBe(false); + }); + + it("returns 503 without a report when R2 fails and releases the control scope", async () => { + const host = "git-storage-failure.bind.ws"; + const f = await seed(host); + await runInDurableObject(env.RELAY.getByName(host.split(".")[0]), async (relay) => { + const bucket = proxyBucket(relay, { get: async () => { throw new Error("provider failure"); } }); + try { + const response = await scan(relay, host, f.owner, f.identifier); + expect(response.status).toBe(503); + expect(await response.json()).toEqual({ error: "error: Git inventory unavailable; no complete report" }); + expect(relay.repositoryAccess.busy).toBe(false); + } finally { bucket.restore(); } + }); + }); + + it("returns 413 for an oversized listing page without leaving a lease", async () => { + const host = "git-storage-budget.bind.ws"; + const f = await seed(host); + await runInDurableObject(env.RELAY.getByName(host.split(".")[0]), async (relay) => { + const bucket = proxyBucket(relay, { list: async () => ({ objects: Array.from({ length: 10001 }, (_, i) => ({ key: `${relay.slug}/git/data/${i}`, size: 1 })), truncated: false, cursor: undefined }) }); + try { + const response = await scan(relay, host, f.owner, f.identifier); + expect(response.status).toBe(413); + expect(await response.json()).toEqual({ error: "restricted: Git inventory limit reached; no complete report" }); + expect(relay.repositoryAccess.busy).toBe(false); + } finally { bucket.restore(); } + }); + }); + + it("holds control admission across the first R2 read and refuses Git, event and control work", async () => { + const host = "git-storage-coordination.bind.ws"; + const f = await seed(host); + await runInDurableObject(env.RELAY.getByName(host.split(".")[0]), async (relay) => { + let entered!: () => void; + let release!: () => void; + const ready = new Promise((resolve) => { entered = resolve; }); + const blocked = new Promise((resolve) => { release = resolve; }); + const original = relay.media; + const bucket = proxyBucket(relay, { get: async (key: string, options?: R2GetOptions) => { + if (key.endsWith("/root.json")) { entered(); await blocked; } + return original.get(key, options); + } }); + const active = scan(relay, host, f.owner, f.identifier); + try { + await ready; + expect(relay.repositoryAccess.busy).toBe(true); + expect(relay.repositoryAccess.kind).toBe("control"); + const path = gitRepositoryPath(npubEncode(pk(f.owner)), f.identifier); + const git = await relay.fetch(new Request(`http://${host}${path}/info/refs?service=git-upload-pack`)); + expect(git.status).toBe(429); + const event = ev(f.owner, KIND_REPO_STATE, "", [["d", f.identifier], ["refs/heads/main", "a".repeat(40)]]); + const admitted = await relay.acceptAny(event, relay.virtualConn(host, pk(f.owner))); + expect(admitted.ok).toBe(false); + expect(admitted.msg).toContain("relay operation in progress"); + const control = await scan(relay, host, f.owner, f.identifier); + expect(control.status).toBe(429); + release(); + const response = await active; + expect(response.status).toBe(200); + await response.arrayBuffer(); + } finally { + release(); + await active; + bucket.restore(); + } + expect(relay.repositoryAccess.busy).toBe(false); + }); + }); +}); diff --git a/test/object/grasp-checkpoint.test.ts b/test/object/grasp-checkpoint.test.ts index bbea8b2..c85f736 100644 --- a/test/object/grasp-checkpoint.test.ts +++ b/test/object/grasp-checkpoint.test.ts @@ -7,6 +7,7 @@ import { npubEncode } from "nostr-tools/nip19"; import { encodePack, type WalRecord } from "ntig"; import { KIND_REPO } from "../../src/kinds.ts"; import { repository } from "../../src/grasp-state.ts"; +import { gitStorage } from "../../src/git-storage.ts"; import { gitRepository } from "../../src/grasp.ts"; import type { RepositoryAnnouncement } from "../../src/grasp-policy.ts"; import { ev, pk, rpc } from "../helpers/relay.ts"; @@ -51,7 +52,7 @@ describe("GRASP checkpoint integration", () => { connection.ws.close(); const fixture = await fixturePack(); - const measurements = await runInDurableObject(env.RELAY.getByName(host.split(".")[0]), async (relay) => { + const measurements = await runInDurableObject(env.RELAY.getByName(host.split(".")[0]), async (relay) => relay.repositoryAccess.run("control", async () => { const repo = repository(relay, pk(owner), identifier) as RepositoryAnnouncement | null; expect(repo).not.toBeNull(); const wal = await gitRepository(relay, repo!); @@ -102,8 +103,18 @@ describe("GRASP checkpoint integration", () => { return counts; }, {}); const retained = await inventory(relay, repo!, rebuilt); + const scan = await gitStorage(relay, pk(owner), identifier); + expect(scan.status).toBe(200); + if (!("result" in scan.body)) throw new Error("inventory did not complete"); + const report = scan.body.result; + if (!report) throw new Error("inventory report missing"); + expect(report.inventory.listed.bytes).toBe(retained.physicalBytes); + expect(report.inventory.live.bytes).toBe(retained.currentBytes); + expect(report.reservations.bytes).toBe(retained.reservedBytes); + expect(report.inventory.unknown.bytes).toBe(0); + console.info("runtime checkpoint inventory", JSON.stringify({ workload, physical: report.inventory.listed.bytes, live: report.inventory.live.bytes, ...report.operations, ...report.inventory.observed })); return { before, after, keyCount: keys.length, categories, sequence: cold.sequence, empty, oneCommit, retained }; - }); + }, () => { throw new Error("fixture admission refused"); })); console.info("checkpoint inventory", JSON.stringify({ workload, empty: measurements.empty, oneCommit: measurements.oneCommit, retained: measurements.retained })); console.info("checkpoint storage measurement", { diff --git a/test/object/grasp-coordination.test.ts b/test/object/grasp-coordination.test.ts index 25f675f..8bf4412 100644 --- a/test/object/grasp-coordination.test.ts +++ b/test/object/grasp-coordination.test.ts @@ -6,10 +6,51 @@ import { generateSecretKey } from "nostr-tools/pure"; import { npubEncode } from "nostr-tools/nip19"; import { KIND_REPO, KIND_REPO_STATE } from "../../src/kinds.ts"; import { gitRepositoryPath } from "../../src/grasp-policy.ts"; -import { ev, pk, rpc } from "../helpers/relay.ts"; +import { ev, nip98, pk, rpc } from "../helpers/relay.ts"; import { WS } from "../helpers/ws.ts"; describe("GRASP coordination", () => { + it("keeps admission free while a management body is incomplete", async () => { + const host = "grasp-management-body.bind.ws"; + const owner = generateSecretKey(); + await rpc(host, owner, "claim"); + await rpc(host, owner, "applypreset", "grasp"); + const path = gitRepositoryPath(npubEncode(pk(owner)), "body"); + const connection = await WS.connect(host); + expect((await connection.ok(ev(owner, KIND_REPO, "", [["d", "body"], ["clone", `https://${host}${path}`], ["relays", `wss://${host}`]]))).ok).toBe(true); + connection.ws.close(); + await runInDurableObject(env.RELAY.getByName("grasp-management-body"), async (relay) => { + const url = `http://${host}/`; + const payload = { method: "setpolicy", params: [{ name: "body completed" }] }; + const authorization = await nip98(owner, url, "POST", payload); + let controller!: ReadableStreamDefaultController; + const body = new ReadableStream({ start(value) { controller = value; } }); + const active = relay.fetch(new Request(url, { method: "POST", headers: { authorization, "content-type": "application/nostr+json+rpc" }, body })); + let closed = false; + try { + await Promise.resolve(); + expect(relay.repositoryAccess.busy).toBe(false); + const git = await relay.fetch(new Request(`http://${host}${path}`)); + expect(git.status).toBe(200); + await git.arrayBuffer(); + const admitted = await relay.acceptAny(ev(owner, 1, "while the body waits"), relay.virtualConn(host, pk(owner))); + expect(admitted.ok).toBe(true); + expect(relay.settings.policy.name).not.toBe("body completed"); + controller.enqueue(new TextEncoder().encode(JSON.stringify(payload))); + controller.close(); + closed = true; + const response = await active; + expect(response.status).toBe(200); + await response.arrayBuffer(); + expect(relay.settings.policy.name).toBe("body completed"); + expect(relay.repositoryAccess.busy).toBe(false); + } finally { + if (!closed) { controller.enqueue(new TextEncoder().encode(JSON.stringify(payload))); controller.close(); } + await active; + } + }); + }); + it.each([ { mode: "http", outcome: "success" }, { mode: "http", outcome: "failure" }, { mode: "alarm", outcome: "success" }, { mode: "alarm", outcome: "failure" }, @@ -58,8 +99,8 @@ describe("GRASP coordination", () => { const active = mode === "http" ? relay.fetch(request()) : relay.alarm(); try { await atRead; - expect(relay.graspBusy).toBe(mode === "http"); - expect(relay.graspControls).toBe(mode === "alarm" ? 1 : 0); + expect(relay.repositoryAccess.busy).toBe(true); + expect(relay.repositoryAccess.kind).toBe(mode === "http" ? "git" : "alarm"); const before = gets; const otherBefore = otherOperations; const refused = await relay.fetch(request()); @@ -69,27 +110,18 @@ describe("GRASP coordination", () => { const admission = await relay.acceptAny(state, relay.virtualConn(host, pk(owner))); expect(gets).toBe(before); expect(otherOperations).toBe(otherBefore); - if (mode === "http") { - expect(admission.ok).toBe(false); - expect(admission.msg).toContain("Git transaction in progress"); - const management = await relay.fetch(new Request(`http://${host}/`, { method: "POST", body: "{}" })); - expect(management.status).toBe(429); - await management.arrayBuffer(); - await relay.alarm(); - expect(gets).toBe(before); - expect(relay.graspBusy).toBe(true); - expect(relay.graspControls).toBe(0); - } else { - // Controls blocks Git admission, but event writes can still alter - // authority while alarm work awaits R2. It is not a general lock. - expect(admission.ok).toBe(true); - expect(relay.sql.exec("SELECT id FROM events WHERE id=?", state.id).toArray()).toHaveLength(1); - expect(relay.graspControls).toBe(1); - } + expect(admission.ok).toBe(false); + expect(admission.msg).toContain("relay operation in progress"); + const management = await relay.fetch(new Request(`http://${host}/`, { method: "POST", body: "{}" })); + expect(management.status).toBe(429); + await management.arrayBuffer(); + if (mode === "http") await relay.alarm(); + expect(gets).toBe(before); + expect(relay.repositoryAccess.busy).toBe(true); + expect(relay.repositoryAccess.kind).toBe(mode === "http" ? "git" : "alarm"); release(); const response = await active; - expect(relay.graspBusy).toBe(false); - expect(relay.graspControls).toBe(0); + expect(relay.repositoryAccess.busy).toBe(false); const completedGets = gets; if (response) { expect(response.status).toBe(outcome === "failure" ? 503 : 200); diff --git a/test/object/grasp.test.ts b/test/object/grasp.test.ts index 598457a..bf21889 100644 --- a/test/object/grasp.test.ts +++ b/test/object/grasp.test.ts @@ -276,11 +276,10 @@ describe("GRASP", () => { const stub = env.RELAY.getByName("grasp-pr-checkpoint"); await runInDurableObject(stub, async (relay) => { - relay.graspBusy = true; - try { + await relay.repositoryAccess.run("git", async () => { const wal = await gitRepository(relay, storedRepository(relay, pk(owner), "correction")!); expect((await wal.checkpoint()).changed).toBe(true); - } finally { relay.graspBusy = false; } + }, () => { throw new Error("Git scope unexpectedly refused"); }); }); const metadata = await runInDurableObject(stub, async (relay) => { const bucket = relay.media; @@ -305,15 +304,14 @@ describe("GRASP", () => { const requestId = "hidden-pr-correction"; expect(await (await receiveSettled(path, host, null, next.commitID, ref, next.pack, requestId)).text()).toContain(`ok ${ref}`); const sequence = await runInDurableObject(stub, async (relay) => { - relay.graspBusy = true; - try { + return relay.repositoryAccess.run("git", async () => { const wal = await gitRepository(relay, storedRepository(relay, pk(owner), "correction")!); for (let i = 0; i < 130; i++) await wal.commit({ id: `later-${i}`, updates: [{ name: `refs/tags/later-${i}`, old: null, new: first.commitID }] }); const snapshot = await wal.load(); expect(snapshot.records).toHaveLength(1); expect(snapshot.records[0].id).not.toBe(requestId); return snapshot.sequence; - } finally { relay.graspBusy = false; } + }, () => { throw new Error("Git scope unexpectedly refused"); }); }); // Pending work for another repository does not reload this one's packs. const other = await WS.connect(host); @@ -387,76 +385,86 @@ describe("GRASP", () => { const path = gitRepositoryPath(npubEncode(pk(owner)), "promotion"); const requestId = "promotion-recovery"; const stub = env.RELAY.getByName(`grasp-promotion-${mode}`); - await runInDurableObject(stub, async (relay) => { - const bucket = relay.media; - let published = false; - let failed = false; - const observed = new Proxy(bucket, { get(target, name) { - if (name === "get") return (key: string, options?: R2GetOptions) => { - if (published && key.endsWith("/root.json")) { failed = true; throw new Error("publication succeeded before promotion read failed"); } - return target.get(key, options); - }; - if (name === "put") return async (...args: unknown[]) => { - const result = await Reflect.apply(target.put, target, args); - if (String(args[0]).endsWith("/root.json") && result) published = true; - return result; - }; - const value = Reflect.get(target, name, target); - return typeof value === "function" ? value.bind(target) : value; - } }); - Object.defineProperty(relay, "media", { value: observed, configurable: true }); - try { - const response = await relay.fetch(new Request(`http://${host}${path}/git-receive-pack`, { - method: "POST", - headers: { "content-type": "application/x-git-receive-pack-request", "X-Git-Request-Id": requestId }, - body: concat(packet(`${"0".repeat(40)} ${pack.commitID} refs/heads/main\0report-status\n`), flush(), pack.pack), - })); - expect(await response.text()).not.toContain("ok refs/heads/main"); - expect(published).toBe(true); - expect(failed).toBe(true); - } finally { Reflect.deleteProperty(relay, "media"); } - const wal = await gitRepository(relay, storedRepository(relay, pk(owner), "promotion")!); - expect((await wal.load()).sequence).toBe(1); - expect(relay.sql.exec("SELECT id FROM grasp_pending WHERE id IN (?,?)", announcement.id, state.id).toArray()).toHaveLength(2); - }); - const replay = await runInDurableObject(stub, async (relay) => { - const bucket = relay.media; - let roots = 0; - const published: string[] = []; - const broadcast = relay.broadcast.bind(relay); - Object.defineProperty(relay, "broadcast", { configurable: true, value: (event: Parameters[0]) => { - published.push(event.id); - broadcast(event); - } }); - const observed = new Proxy(bucket, { get(target, name) { - if (name === "get") return (key: string, options?: R2GetOptions) => { - // The replay loads the WAL, then promotion loads it again. Change - // eligibility only after promotion's initial candidate check. - if (key.endsWith("/root.json") && ++roots === 2) { - if (mode === "expired") relay.sql.exec("UPDATE events SET expires=1 WHERE id=?", pr.id); - else relay.settings.setEvent(pr.id, "hide"); + const replay = await runInDurableObject(stub, async (relay, context) => { + await context.storage.deleteAlarm(); + const deadline = Date.now() + 5000; + while (relay.repositoryAccess.busy && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 10)); + return relay.repositoryAccess.run("git", async () => { + await context.storage.deleteAlarm(); + // Both phases share one owner so an alarm cannot heal the injected + // interruption before the identical HTTP retry proves recovery. + { + const bucket = relay.media; + let published = false; + let failed = false; + const observed = new Proxy(bucket, { get(target, name) { + if (name === "get") return (key: string, options?: R2GetOptions) => { + if (published && key.endsWith("/root.json")) { failed = true; throw new Error("publication succeeded before promotion read failed"); } + return target.get(key, options); + }; + if (name === "put") return async (...args: unknown[]) => { + const result = await Reflect.apply(target.put, target, args); + if (String(args[0]).endsWith("/root.json") && result) published = true; + return result; + }; + const value = Reflect.get(target, name, target); + return typeof value === "function" ? value.bind(target) : value; + } }); + Object.defineProperty(relay, "media", { value: observed, configurable: true }); + try { + const response = await relay.fetch(new Request(`http://${host}${path}/git-receive-pack`, { + method: "POST", + headers: { "content-type": "application/x-git-receive-pack-request", "X-Git-Request-Id": requestId }, + body: concat(packet(`${"0".repeat(40)} ${pack.commitID} refs/heads/main\0report-status\n`), flush(), pack.pack), + })); + expect(await response.text()).not.toContain("ok refs/heads/main"); + expect(published).toBe(true); + expect(failed).toBe(true); + } finally { Reflect.deleteProperty(relay, "media"); } + const wal = await gitRepository(relay, storedRepository(relay, pk(owner), "promotion")!); + expect((await wal.load()).sequence).toBe(1); + expect(relay.sql.exec("SELECT id FROM grasp_pending WHERE id IN (?,?)", announcement.id, state.id).toArray()).toHaveLength(2); + } + { + const bucket = relay.media; + let roots = 0; + const published: string[] = []; + const broadcast = relay.broadcast.bind(relay); + Object.defineProperty(relay, "broadcast", { configurable: true, value: (event: Parameters[0]) => { + published.push(event.id); + broadcast(event); + } }); + const observed = new Proxy(bucket, { get(target, name) { + if (name === "get") return (key: string, options?: R2GetOptions) => { + // The replay loads the WAL, then promotion loads it again. Change + // eligibility only after promotion's initial candidate check. + if (key.endsWith("/root.json") && ++roots === 2) { + if (mode === "expired") relay.sql.exec("UPDATE events SET expires=1 WHERE id=?", pr.id); + else relay.settings.setEvent(pr.id, "hide"); + } + return target.get(key, options); + }; + const value = Reflect.get(target, name, target); + return typeof value === "function" ? value.bind(target) : value; + } }); + Object.defineProperty(relay, "media", { value: observed, configurable: true }); + try { + const response = await relay.fetch(new Request(`http://${host}${path}/git-receive-pack`, { + method: "POST", + headers: { "content-type": "application/x-git-receive-pack-request", "X-Git-Request-Id": requestId }, + body: concat(packet(`${"0".repeat(40)} ${pack.commitID} refs/heads/main\0report-status\n`), flush(), pack.pack), + })); + expect(roots).toBeGreaterThanOrEqual(2); + expect(published).toContain(announcement.id); + expect(published).toContain(state.id); + expect(published).not.toContain(pr.id); + return await response.text(); + } finally { + Reflect.deleteProperty(relay, "media"); + Reflect.deleteProperty(relay, "broadcast"); } - return target.get(key, options); - }; - const value = Reflect.get(target, name, target); - return typeof value === "function" ? value.bind(target) : value; - } }); - Object.defineProperty(relay, "media", { value: observed, configurable: true }); - try { - const response = await relay.fetch(new Request(`http://${host}${path}/git-receive-pack`, { - method: "POST", - headers: { "content-type": "application/x-git-receive-pack-request", "X-Git-Request-Id": requestId }, - body: concat(packet(`${"0".repeat(40)} ${pack.commitID} refs/heads/main\0report-status\n`), flush(), pack.pack), - })); - expect(roots).toBeGreaterThanOrEqual(2); - expect(published).toContain(announcement.id); - expect(published).toContain(state.id); - expect(published).not.toContain(pr.id); - return await response.text(); - } finally { - Reflect.deleteProperty(relay, "media"); - Reflect.deleteProperty(relay, "broadcast"); - } + } + }, () => { throw new Error("promotion fixture did not settle"); }); }); expect(replay).toContain("ok refs/heads/main"); await runInDurableObject(stub, async (relay) => { @@ -493,16 +501,30 @@ describe("GRASP", () => { await rpc(host, owner, "setpolicy", { features: { grasp: true } }); const event = repository(owner, host, "fenced"); await runInDurableObject(env.RELAY.getByName("grasp-fence"), async (relay) => { - relay.graspBusy = true; + let entered!: () => void; + let release!: () => void; + const ready = new Promise((resolve) => { entered = resolve; }); + const hold = new Promise((resolve) => { release = resolve; }); + const active = relay.repositoryAccess.run("git", async () => { + entered(); + await hold; + }, () => { throw new Error("Git scope unexpectedly refused"); }); try { + await ready; + expect(relay.repositoryAccess.busy).toBe(true); + expect(relay.repositoryAccess.kind).toBe("git"); const result = await relay.acceptAny(event, relay.virtualConn(host, pk(owner))); expect(result.ok).toBe(false); - expect(result.msg).toContain("Git transaction in progress"); + expect(result.msg).toContain("relay operation in progress"); const response = await relay.fetch(new Request(`http://${host}/`, { method: "POST", body: "{}" })); expect(response.status).toBe(429); await response.text(); expect(relay.sql.exec("SELECT 1 FROM events WHERE id=?", event.id).toArray()).toEqual([]); - } finally { relay.graspBusy = false; } + } finally { + release(); + await active; + expect(relay.repositoryAccess.busy).toBe(false); + } }); }); diff --git a/test/unit/repository-access.test.ts b/test/unit/repository-access.test.ts new file mode 100644 index 0000000..f9f41b0 --- /dev/null +++ b/test/unit/repository-access.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from "vitest"; +import { RepositoryAccess } from "../../src/repository-access.ts"; + +const latch = () => { + let release!: () => void; + const promise = new Promise((resolve) => { release = resolve; }); + return { promise, release }; +}; +const refused = () => "refused"; + +describe("Repository admission", () => { + it("keeps unrelated operations out across awaits and permits owned nested work", async () => { + const access = new RepositoryAccess(); + const entered = latch(); + const finish = latch(); + const active = access.run("git", async () => { + expect(access.owned).toBe(true); + expect(access.sync("event", () => "nested", refused)).toBe("nested"); + entered.release(); + await finish.promise; + expect(await access.run("control", () => "nested async", refused)).toBe("nested async"); + expect(access.kind).toBe("git"); + return "done"; + }, refused); + await entered.promise; + expect(access.blocked).toBe(true); + expect(access.sync("event", () => "unexpected", refused)).toBe("refused"); + expect(await access.run("alarm", () => "unexpected", refused)).toBe("refused"); + finish.release(); + expect(await active).toBe("done"); + expect(access.busy).toBe(false); + }); + + it("releases synchronous and asynchronous owners after failures", async () => { + const access = new RepositoryAccess(); + expect(() => access.sync("event", () => { throw new Error("sync"); }, refused)).toThrow("sync"); + expect(access.busy).toBe(false); + await expect(access.run("git", async () => { throw new Error("async"); }, refused)).rejects.toThrow("async"); + expect(access.busy).toBe(false); + }); + + it("retains an entered child until it settles even when the parent returns", async () => { + const access = new RepositoryAccess(); + const finish = latch(); + let child!: Promise; + await access.run("control", () => { + child = access.run("event", async () => { await finish.promise; return "child"; }, refused); + return "parent"; + }, refused); + expect(access.blocked).toBe(true); + finish.release(); + expect(await child).toBe("child"); + expect(access.busy).toBe(false); + }); + + it("never lets a stale async context borrow a different active owner", async () => { + const access = new RepositoryAccess(); + const resume = latch(); + let stale!: Promise; + await access.run("control", () => { + stale = resume.promise.then(() => access.run("event", () => "unexpected", refused)); + return "original"; + }, refused); + const finish = latch(); + const active = access.run("git", async () => { await finish.promise; return "current"; }, refused); + resume.release(); + expect(await stale).toBe("refused"); + finish.release(); + await active; + expect(access.busy).toBe(false); + }); +}); diff --git a/vendor/README.md b/vendor/README.md index ae86f38..89be2c3 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -1,15 +1,15 @@ # Vendored dependencies -`ntig-0.2.1.tgz` is the Git engine and conditional R2 WAL used by GRASP. -The lockfile pins the archive integrity. `ntig-source.tar.gz` preserves +`ntig-0.3.0.tgz` is the Git engine and conditional R2 WAL used by GRASP. +The lockfile pins the archive integrity. `ntig-source-0.3.0.tar.gz` preserves the complete source and tests for the same build; neither artifact depends on a sibling checkout or a public package registry publication. | Fact | Value | |---|---| -| Source commit | `de3dc0b2a9151973d555658f3e75b0c5669426e8` | -| Package SHA-256 | `0f2ceab406cd40935ec96ba53a0a03835de2e8611792f4a0c137d596c81a2f05` | -| Source archive SHA-256 | `24d9b27856d034e88662168a156f7ff01302012e85809381ff98fb7f373021d1` | +| Source commit | `caa8258e6cf6ec3220b89312d66860258e096f0f` | +| Package SHA-256 | `c210d4f864d85fdb1fd3f371e4af48eeb2d2803e00dacaac7014ce84019dbe45` | +| Source archive SHA-256 | `326e41622649dc020b068f621453d7ba4da525f43e9af7b8005a588ce119dc9f` | | Source branch | `main` in [FelineStateMachine/ntig](https://github.com/FelineStateMachine/ntig) | | License | MIT, included in both archives | | Supplied package toolchain | Node 22.22.3, npm 10.9.8 | @@ -19,20 +19,26 @@ on a sibling checkout or a public package registry publication. Rebuilding the preserved source with Node 26.8.1 and npm 11.19.0 produces identical tar entries and metadata. The uncompressed tar SHA-256 is -`f1ad28f92b7ac0ebad4487d3cdd6cabb1a7477f965e3ce883dae47c00a4f9804`; +`b26512be07bd0dce30d69b290365ed138f7a56059be105dc4c9c1e7081734eba`; gzip bytes can differ across toolchains. The supplied package checksum above and the lockfile pin the exact installed archive. The source's `docs/INTEGRATION.md` describes the exported contracts, failure semantics, cost counters and current limits. Backend work stays in that -repository; a dependency update replaces both archives and the lockfile +repository; a dependency update records versioned archives and the lockfile integrity after its checks and bindws's integration checks pass. New and existing repositories remain in format 1, whose 128-transaction limit also stops timed ref deletion. Bindws hides expired unknown PR refs -even when physical cleanup cannot advance. Installing 0.2.1 does not migrate +even when physical cleanup cannot advance. Installing 0.3.0 does not migrate roots. The source's `docs/CHECKPOINTS.md` describes the explicit one-way `checkpoint()` upgrade: every reader and writer must be upgraded first, and 0.1.x cannot read a format-2 root. Bindws exposes no migration endpoint or scheduled migration. Retained packs, receipts, manifests and orphan writes remain charged until relay teardown. + +The prior `ntig-0.2.1.tgz` and `ntig-source.tar.gz` remain as the preserved +0.2.1 package and source. The 0.3.0 release adds bounded read-only inventory +and an R2 listing adapter; it does not migrate repositories or collect data. +Its `docs/INVENTORY.md` defines report classes, limits and the distinction +between current-root references and deletion authority. diff --git a/vendor/ntig-0.3.0.tgz b/vendor/ntig-0.3.0.tgz new file mode 100644 index 0000000..a5ddd4a Binary files /dev/null and b/vendor/ntig-0.3.0.tgz differ diff --git a/vendor/ntig-source-0.3.0.tar.gz b/vendor/ntig-source-0.3.0.tar.gz new file mode 100644 index 0000000..1471af0 Binary files /dev/null and b/vendor/ntig-source-0.3.0.tar.gz differ