diff --git a/.env.example b/.env.example
index 068eb79..de4b192 100644
--- a/.env.example
+++ b/.env.example
@@ -7,6 +7,12 @@ HYPERSNAP_GRPC_TLS=false
# Optional complete authorization metadata values for authenticated proxies.
SNAPCHAIN_GRPC_AUTHORIZATION=
HYPERSNAP_GRPC_AUTHORIZATION=
+# Optional x-api-key metadata values for hosted providers such as Neynar.
+SNAPCHAIN_GRPC_API_KEY=
+HYPERSNAP_GRPC_API_KEY=
+# Minimum delay between GetEvents request starts. Use 250ms (4 RPS) for Neynar Starter.
+SNAPCHAIN_RPC_MIN_INTERVAL_MS=0
+HYPERSNAP_RPC_MIN_INTERVAL_MS=0
SNAPCHAIN_SOURCE_MODE=verified
# Keep derived unless a dedicated verified Hyper-write source is implemented.
HYPERSNAP_SOURCE_MODE=derived
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..69e9af2
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,8 @@
+* text=auto eol=lf
+
+*.png binary
+*.jpg binary
+*.jpeg binary
+*.gif binary
+*.webp binary
+*.ico binary
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000..c2a4461
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,26 @@
+version: 2
+
+updates:
+ - package-ecosystem: npm
+ directory: /
+ schedule:
+ interval: weekly
+ day: monday
+ time: "06:00"
+ timezone: Etc/UTC
+ open-pull-requests-limit: 5
+ versioning-strategy: increase-if-necessary
+ groups:
+ production-dependencies:
+ dependency-type: production
+ development-dependencies:
+ dependency-type: development
+
+ - package-ecosystem: github-actions
+ directory: /
+ schedule:
+ interval: weekly
+ day: monday
+ time: "06:30"
+ timezone: Etc/UTC
+ open-pull-requests-limit: 5
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 97222ce..a647cf0 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -12,6 +12,20 @@ concurrency:
cancel-in-progress: true
jobs:
+ dependency-review:
+ if: github.event_name == 'pull_request'
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ steps:
+ - name: Check out source
+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+
+ - name: Review dependency changes
+ uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5
+ with:
+ fail-on-severity: moderate
+
validate:
runs-on: ubuntu-latest
timeout-minutes: 30
@@ -34,6 +48,9 @@ jobs:
- name: Install locked dependencies
run: pnpm install --frozen-lockfile
+ - name: Publication and dependency safety
+ run: pnpm security:check
+
- name: Install Playwright Chromium
run: pnpm exec playwright install --with-deps chromium
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
new file mode 100644
index 0000000..daef1b3
--- /dev/null
+++ b/.github/workflows/codeql.yml
@@ -0,0 +1,38 @@
+name: CodeQL
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+ schedule:
+ - cron: "23 4 * * 2"
+ workflow_dispatch:
+
+permissions:
+ contents: read
+ security-events: write
+
+concurrency:
+ group: codeql-${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ analyze:
+ name: Analyze JavaScript and TypeScript
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ steps:
+ - name: Check out source
+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+
+ - name: Initialize CodeQL
+ uses: github/codeql-action/init@f3712979fa5f215279b101dd0a2e3bdfb4353324 # v3
+ with:
+ languages: javascript-typescript
+ build-mode: none
+
+ - name: Analyze
+ uses: github/codeql-action/analyze@f3712979fa5f215279b101dd0a2e3bdfb4353324 # v3
+ with:
+ category: /language:javascript-typescript
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml
index d4de4d0..f87aa78 100644
--- a/.github/workflows/deploy.yml
+++ b/.github/workflows/deploy.yml
@@ -27,6 +27,7 @@ jobs:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
+ - run: pnpm security:check
- run: pnpm exec playwright install --with-deps chromium
- run: pnpm lint
- run: pnpm typecheck
@@ -68,6 +69,10 @@ jobs:
if: env.CLOUDFLARE_READY == 'true'
run: pnpm install --frozen-lockfile
+ - name: Verify signed Mini App release metadata
+ if: env.CLOUDFLARE_READY == 'true'
+ run: pnpm --filter @snapmeter/dashboard verify:miniapp:release
+
- name: Apply production D1 migrations
if: env.CLOUDFLARE_READY == 'true'
env:
diff --git a/.gitignore b/.gitignore
index 231fe78..74fe9c7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -9,6 +9,15 @@ coverage/
*.db
*.db-shm
*.db-wal
+*.db-journal
+*.sqlite
+*.sqlite-*
+*.sqlite3
+*.sqlite3-*
+*.pem
+*.key
+*.p12
+*.pfx
*.log
playwright-report/
test-results/
diff --git a/AGENTS.md b/AGENTS.md
index c4c2aec..fef5a5f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -23,6 +23,7 @@ The workspace uses Node.js 24+, pnpm 11.19, TypeScript, Vitest, Playwright, and
pnpm install --frozen-lockfile
pnpm lint
pnpm typecheck
+pnpm security:check
pnpm test
pnpm build
pnpm test:e2e
@@ -31,7 +32,7 @@ pnpm collector doctor|run|status|backfill
pnpm --filter @snapmeter/dashboard run deploy
```
-Run all five quality commands before a release. For a focused change, run the affected package test first, then the complete gates. Inspect mobile captures at 390x844 and verify no horizontal overflow, source ordering, reduced motion, offline/stale states, and real pulse behavior.
+Run all six quality commands before a release. For a focused change, run the affected package test first, then the complete gates. Inspect mobile captures at 390x844 and verify no horizontal overflow, source ordering, reduced motion, offline/stale states, and real pulse behavior.
## Non-negotiable data rules
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..5627429
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,53 @@
+# Contributing to SnapMeter
+
+Thank you for helping improve SnapMeter. Contributions should preserve the
+project's metric integrity, privacy boundary, and reproducible build.
+
+## Before opening a change
+
+- Read `AGENTS.md`, `docs/metrics.md`, `docs/security.md`, and the document for
+ the surface you intend to change.
+- Open a public issue for behavior or design discussion, but use GitHub's
+ private vulnerability-reporting form for security findings.
+- Never attach credentials, `.env` files, databases, logs, raw node events,
+ cast contents, signatures, or production screenshots containing private
+ operator data.
+
+## Development setup
+
+Follow `docs/local-reconstruction.md`. A deterministic `?demo=1` dashboard and
+the full test suite require no production credentials or database.
+
+Create a topic branch, keep the patch focused, and add tests for behavior
+changes. Do not regenerate or replace pinned upstream protocol files without
+following the source-upgrade procedure in `docs/upstream-sources.md`.
+
+## Required checks
+
+Run these commands with Node.js 24 and pnpm 11.19.0:
+
+```text
+pnpm install --frozen-lockfile
+pnpm lint
+pnpm typecheck
+pnpm security:check
+pnpm test
+pnpm build
+pnpm test:e2e
+```
+
+Inspect responsive behavior, reduced motion, offline/stale states, and source
+quality claims when the dashboard changes. A successful page load does not
+prove that either source is live.
+
+## Pull requests and licensing
+
+Explain the problem, the integrity/security impact, the tests run, and any
+deployment or migration implications. Keep secrets and production data out of
+the PR description and CI logs.
+
+By submitting a contribution, you agree that your SnapMeter-authored
+contribution is licensed under the repository's MIT license. Do not submit
+third-party material unless redistribution is permitted and its exact source,
+license, and notice requirements are included. The vendored Snapchain
+protobufs are separately identified in `THIRD_PARTY_NOTICES.md`.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..1b853b5
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 ael-dev3
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/LICENSES/GPL-3.0-only.txt b/LICENSES/GPL-3.0-only.txt
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSES/GPL-3.0-only.txt
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/README.md b/README.md
index 14f95c8..0da6d95 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
[Open SnapMeter](https://snapmeter.ael-dev3.workers.dev)
-The public origin, API, authenticated ingest, D1 persistence, WebSocket hydration, real pulse fan-out, and duplicate suppression were smoke-tested after deployment. The collector is not connected to upstream nodes yet, so production honestly reports both sources as disconnected; use `?demo=1` only for the clearly labelled seeded preview.
+The public origin, API, authenticated ingest, D1 persistence, WebSocket hydration, real pulse fan-out, and duplicate suppression were smoke-tested after deployment. Source availability changes independently of the website, so the dashboard always renders the latest authenticated health state instead of promising that either upstream node is live. Use `?demo=1` only for the clearly labelled seeded preview.
## Source quality
@@ -36,25 +36,30 @@ Action time comes from confirmed shard-chunk time when available. Collector rece
## Quick start
-Requirements: Node.js 24 or later, pnpm 11.19, and reachable private Snapchain-compatible gRPC endpoints.
+A clean checkout can reproduce the dashboard, deterministic demo, tests, and production bundle without credentials, a database dump, or a node snapshot. Requirements are Git, Node.js 24 or later, and pnpm 11.19.0.
```powershell
git clone https://github.com/ael-dev3/SnapMeter.git
Set-Location SnapMeter
-Copy-Item .env.example .env
-./scripts/bootstrap.ps1
-pnpm collector doctor
-pnpm collector run
+pnpm install --frozen-lockfile
+pnpm dev
```
-In a second terminal, start the local dashboard:
+Open the URL printed by Vite with `?demo=1`, normally `http://127.0.0.1:5173/?demo=1`. Demo mode is deterministic, synthetic, clearly labelled, and does not contact a collector or require private data.
+
+To connect the collector, copy the environment template only after the demo works, keep the resulting file untracked, and configure one or two private Snapchain-compatible gRPC endpoints:
```powershell
-pnpm dev
+Copy-Item .env.example .env
+./scripts/bootstrap.ps1
+./scripts/run-collector.ps1 -EnvFile .env -Mode doctor
+./scripts/run-collector.ps1 -EnvFile .env -Mode run
```
The convenience endpoint defaults are `127.0.0.1:3383` for Snapchain and `127.0.0.1:4383` for Hypersnap. Upstream Hypersnap also listens on internal port `3383`; `4383` is only the documented host remap when both nodes share one machine.
+The complete clean-room procedure, including local D1 migration, optional upstream-node checkouts, storage layout, validation, and the boundary around intentionally excluded private data, is in [Local reconstruction](docs/local-reconstruction.md).
+
## Architecture
```text
@@ -79,6 +84,8 @@ SNAPCHAIN_GRPC_URL=127.0.0.1:3383
HYPERSNAP_GRPC_URL=127.0.0.1:4383
SNAPCHAIN_GRPC_TLS=false
HYPERSNAP_GRPC_TLS=false
+SNAPCHAIN_GRPC_API_KEY=
+SNAPCHAIN_RPC_MIN_INTERVAL_MS=0
SNAPMETER_INGEST_URL=
SNAPMETER_INGEST_SECRET=
SNAPMETER_DATA_DIR=C:\ProgramData\SnapMeter
@@ -86,11 +93,13 @@ SNAPMETER_DATA_DIR=C:\ProgramData\SnapMeter
After deployment, set `SNAPMETER_INGEST_URL` to the smoke-tested origin plus `/api/v1/ingest/batch` and set the secret locally to the value stored with Wrangler. Never commit either value.
+For a hosted Neynar Snapchain source, use `SNAPCHAIN_GRPC_URL=snapchain-grpc-api.neynar.com:443`, enable `SNAPCHAIN_GRPC_TLS=true`, place the Neynar credential in `SNAPCHAIN_GRPC_API_KEY`, and set `SNAPCHAIN_RPC_MIN_INTERVAL_MS=250` to pace shared two-shard replay below the Starter-plan request ceiling. Set `HYPERSNAP_SOURCE_MODE=unavailable` when no separate Hypersnap endpoint is connected. Keep the API key only in the ignored local environment file.
+
```powershell
-pnpm collector doctor # endpoints, shards, storage, clock, ingest auth, cursors, disk
-pnpm collector run # continuous collection
-pnpm collector status # last local health snapshot
-pnpm collector backfill # bounded reconciliation; never creates live pulses
+./scripts/run-collector.ps1 -EnvFile .env -Mode doctor # endpoints, shards, storage, clock, ingest auth, cursors, disk
+./scripts/run-collector.ps1 -EnvFile .env -Mode run # continuous collection
+./scripts/run-collector.ps1 -EnvFile .env -Mode status # last local health snapshot
+./scripts/run-collector.ps1 -EnvFile .env -Mode backfill # bounded reconciliation; never creates live pulses
```
Snapchain's default HubEvent retention is only three days. An exact 30-day cold start requires a node configured with at least 31 days of event retention or a trusted prior history. Otherwise SnapMeter exposes partial history until enough prospective data accumulates.
@@ -136,6 +145,7 @@ Do not publish a URL until all release smoke tests pass. Full creation, migratio
```powershell
pnpm lint
pnpm typecheck
+pnpm security:check
pnpm test
pnpm build
pnpm test:e2e
@@ -143,13 +153,20 @@ pnpm test:e2e
Pull requests run the quality gates. Default-branch deployment is conditional on the required Cloudflare repository secrets. Operational and security checks are documented in [Troubleshooting](docs/troubleshooting.md) and [Security](docs/security.md).
+## License
+
+SnapMeter-authored source, documentation, and assets are released under the [MIT License](LICENSE), copyright 2026 ael-dev3. Vendored Snapchain protocol definitions retain their upstream `GPL-3.0` license; see [Third-party notices](THIRD_PARTY_NOTICES.md) and the included license text. Dependency packages retain their own licenses. No license grants rights to third-party names or trademarks.
+
## Documentation
+- [Local reconstruction without private data](docs/local-reconstruction.md)
- [Architecture](docs/architecture.md)
- [Metric definitions and integrity policy](docs/metrics.md)
- [Data sources and source modes](docs/data-sources.md)
- [Pinned upstream sources](docs/upstream-sources.md)
- [Windows runbook](docs/windows-runbook.md)
- [Cloudflare deployment](docs/deployment.md)
+- [Farcaster Mini App release](docs/farcaster-miniapp.md)
- [Security model](docs/security.md)
+- [Private vulnerability reporting](SECURITY.md)
- [Troubleshooting](docs/troubleshooting.md)
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..b88ea16
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,37 @@
+# Security policy
+
+## Supported version
+
+Security fixes are applied to the latest commit on `main`. Older commits and
+operator-modified deployments are not supported independently.
+
+## Report a vulnerability privately
+
+Do not open a public issue, discussion, pull request, or log paste for a
+suspected vulnerability or exposed credential. Use GitHub's **Report a
+vulnerability** form in this repository's Security tab. Include the affected
+commit, impact, reproduction steps, and a minimal proof of concept with all
+credentials and personal data removed.
+
+If private vulnerability reporting is unavailable, open a public issue that
+contains only a request for a private contact channel. Do not include technical
+details until a private channel is established.
+
+## Sensitive material
+
+SnapMeter intentionally excludes production and local secrets, RPC
+credentials, `.env*` and `.dev.vars*` files, Cloudflare tokens, SQLite state,
+logs, raw node data, snapshots, and retry payloads from source control. The
+Farcaster Mini App `accountAssociation`, Worker hostname, and D1 database ID are
+public identifiers, not authorization credentials.
+
+If a credential may have been exposed, revoke or rotate it first. Removing it
+from the latest commit is not sufficient because Git history, forks, caches,
+logs, and notifications may retain it. See [the security model](docs/security.md)
+for rotation and incident-response guidance.
+
+## Disclosure expectations
+
+Please allow time to reproduce, assess, and prepare a coordinated fix before
+publishing details. We will acknowledge valid reports through the private
+GitHub report and keep the report updated as the issue is triaged and fixed.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
new file mode 100644
index 0000000..86bae5d
--- /dev/null
+++ b/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,45 @@
+# Third-party notices
+
+SnapMeter-authored material is licensed under the repository's [MIT License](LICENSE). The following files are exceptions and retain their upstream license.
+
+## Snapchain protocol definitions
+
+The files below were copied from the `farcasterxyz/snapchain` `snapchain-proto` crate at commit [`6152402aea2dbe732fb73076f674b038bfd4aee5`](https://github.com/farcasterxyz/snapchain/tree/6152402aea2dbe732fb73076f674b038bfd4aee5). That crate declares `GPL-3.0`; the files are redistributed under `GPL-3.0-only`, not MIT:
+
+- `packages/protocol/proto/upstream/snapchain-6152402/blocks.proto`
+- `packages/protocol/proto/upstream/snapchain-6152402/hub_event.proto`
+- `packages/protocol/proto/upstream/snapchain-6152402/message.proto`
+- `packages/protocol/proto/upstream/snapchain-6152402/onchain_event.proto`
+- `packages/protocol/proto/upstream/snapchain-6152402/request_response.proto`
+- `packages/protocol/proto/upstream/snapchain-6152402/rpc.proto`
+- `packages/protocol/proto/upstream/snapchain-6152402/username_proof.proto`
+
+`hub_event.proto` differs from the pinned upstream file only by removal of trailing whitespace. The other listed files are byte-for-byte copies at the time of this notice. The complete license is included at [`LICENSES/GPL-3.0-only.txt`](LICENSES/GPL-3.0-only.txt).
+
+The locally authored aggregate loader `packages/protocol/proto/snapchain-6152402.proto` records the source pin and imports the files above; consumers must account for the upstream license when redistributing a combined work.
+
+## Optional upstream nodes
+
+Snapchain and Hypersnap node source, binaries, container images, databases, and snapshots are not included in this repository. If you obtain either project separately, its own license and notices govern it. The exact source commits SnapMeter inspected are recorded in [`docs/upstream-sources.md`](docs/upstream-sources.md).
+
+## Package dependencies
+
+Third-party packages installed from `pnpm-lock.yaml` are not relicensed by SnapMeter. Their own package metadata and license files govern them. A source checkout intentionally does not include `node_modules`.
+
+The production build generates a combined `THIRD_PARTY_LICENSES.txt` from the exact modules Vite bundles into the public browser assets and Cloudflare Worker. That file is served with the deployed application. The post-build verifier fails when either environment's inventory is missing, the combined copy is stale, or a reviewed attribution is absent.
+
+The published `@farcaster/quick-auth` 0.0.8 package declares MIT but its package allowlist omits a license file. At the exact upstream [0.0.8 version-bump commit](https://github.com/farcasterxyz/quick-auth/tree/79e064d75c3d03ca797401d49e8e8cc33a3bdfc9), the repository's available MIT notice is [`Copyright (c) 2025 Farcaster`](https://github.com/farcasterxyz/quick-auth/blob/79e064d75c3d03ca797401d49e8e8cc33a3bdfc9/hono-cloudflare-worker/LICENSE). The generator supplies that reviewed full text and provenance instead of silently emitting an empty Quick Auth section.
+
+The locked Mini App dependency graph includes `rpc-websockets@9.3.9`
+(`LGPL-3.0-only`) through optional Solana support in
+`@farcaster/miniapp-core`. SnapMeter does not use Solana or that RPC package:
+the client loads only the Mini App host bridge, and the production bundle
+verifier fails if the RPC implementation appears in a browser artifact. The
+package may nevertheless be installed into an ignored local `node_modules`
+directory by pnpm; its included license governs that copy.
+
+`text-encoding-utf-8@1.0.2`, another package in that optional transitive path,
+omits an SPDX identifier from its package metadata. Its distributed
+`LICENSE.md` dedicates its original material to the public domain and notes
+that some algorithms/comments derive from the WHATWG Encoding Standard. It is
+likewise excluded from SnapMeter's production browser bundle.
diff --git a/apps/collector/src/cli.ts b/apps/collector/src/cli.ts
index 2226c62..ea3018a 100644
--- a/apps/collector/src/cli.ts
+++ b/apps/collector/src/cli.ts
@@ -5,7 +5,7 @@ import { CollectorRuntime } from "./collector.js";
import { CollectorDatabase } from "./database.js";
import { runDoctor } from "./doctor.js";
import { acquireProcessLock } from "./lock.js";
-import { createLogger } from "./logger.js";
+import { createLogger, redact, sensitiveEnvironmentValues } from "./logger.js";
const command = process.argv[2] ?? "help";
@@ -16,12 +16,15 @@ async function main(): Promise {
}
assertSupportedNode();
const config = loadConfig();
+ const secrets = [
+ config.ingestSecret ?? "",
+ config.endpoints.snapchain.authorization ?? "",
+ config.endpoints.snapchain.apiKey ?? "",
+ config.endpoints.hypersnap.authorization ?? "",
+ config.endpoints.hypersnap.apiKey ?? ""
+ ];
const logger = createLogger({
- secrets: [
- config.ingestSecret ?? "",
- config.endpoints.snapchain.authorization ?? "",
- config.endpoints.hypersnap.authorization ?? ""
- ],
+ secrets,
minimumLevel: process.env.SNAPMETER_LOG_LEVEL === "debug" ? "debug" : "info"
});
const database = new CollectorDatabase(config.databasePath);
@@ -44,12 +47,12 @@ async function main(): Promise {
retentionDays: config.retentionDays
}
};
- process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
+ process.stdout.write(`${JSON.stringify(redact(report, secrets), null, 2)}\n`);
return;
}
if (command === "doctor") {
const report = await runDoctor({ config, database });
- process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
+ process.stdout.write(`${JSON.stringify(redact(report, secrets), null, 2)}\n`);
if (!report.ok) process.exitCode = 1;
return;
}
@@ -79,8 +82,15 @@ function assertSupportedNode(): void {
}
}
-function endpointSummary(endpoint: { url: string; tls: boolean; sourceMode: string; authorization?: string }): Record {
- return { url: endpoint.url, tls: endpoint.tls, sourceMode: endpoint.sourceMode, authorizationConfigured: Boolean(endpoint.authorization) };
+function endpointSummary(endpoint: { url: string; tls: boolean; sourceMode: string; authorization?: string; apiKey?: string; getEventsMinIntervalMs: number }): Record {
+ return {
+ url: endpoint.url,
+ tls: endpoint.tls,
+ sourceMode: endpoint.sourceMode,
+ authorizationConfigured: Boolean(endpoint.authorization),
+ apiKeyConfigured: Boolean(endpoint.apiKey),
+ getEventsMinIntervalMs: endpoint.getEventsMinIntervalMs
+ };
}
function fileSize(path: string): number | null {
@@ -115,7 +125,10 @@ function printHelp(): void {
}
void main().catch((error: unknown) => {
- const message = error instanceof Error ? error.message : String(error);
- process.stderr.write(`${JSON.stringify({ level: "error", event: "collector.fatal", message })}\n`);
+ createLogger({
+ write: (line) => process.stderr.write(`${line}\n`),
+ secrets: sensitiveEnvironmentValues(process.env),
+ minimumLevel: "error"
+ }).error("collector.fatal", { error });
process.exitCode = 1;
});
diff --git a/apps/collector/src/collector.test.ts b/apps/collector/src/collector.test.ts
index 48059ed..f6106f6 100644
--- a/apps/collector/src/collector.test.ts
+++ b/apps/collector/src/collector.test.ts
@@ -25,6 +25,7 @@ class FakeRpc implements CollectorRpc {
shardInfos: [{ shardId: 7, maxHeight: 100, blockDelay: 0, mempoolSize: 0xffff_ffff }]
};
readonly subscriptions: Array<{ emit(event: RawHubEvent): void; end(): void }> = [];
+ readonly subscribeFromIds: Array = [];
subscribeCalls = 0;
getEventsCalls: Array<{ shard: number; startId: string; stopId?: string }> = [];
@@ -41,29 +42,35 @@ class FakeRpc implements CollectorRpc {
return { events: [mergeEvent("1", "1"), mergeEvent("2", "2"), ...(stopId ? [mergeEvent(stopId, "3")] : [])] };
}
- subscribe(_shard: number, _fromId: string, onEvent: (event: RawHubEvent) => void, _onError: (error: Error) => void): RpcSubscription {
+ subscribe(_shard: number, _fromId: string | undefined, onEvent: (event: RawHubEvent) => void, _onError: (error: Error) => void): RpcSubscription {
this.subscribeCalls += 1;
+ this.subscribeFromIds.push(_fromId);
let finish: (() => void) | undefined;
const done = new Promise((resolve) => { finish = resolve; });
const control = { emit: onEvent, end: () => finish?.() };
this.subscriptions.push(control);
// Simulates a subscription event racing with initial historical replay.
onEvent(mergeEvent("3", "3"));
- return { cancel: control.end, done };
+ return { cancel: control.end, ready: Promise.resolve(), done };
}
close(): void {}
}
class LiveOnlyRpc extends FakeRpc {
- override async getEvents(shard: number, startId: string, _token?: Uint8Array, stopId?: string) {
+ override async getEvents(
+ shard: number,
+ startId: string,
+ _token?: Uint8Array,
+ stopId?: string
+ ): Promise<{ events: RawHubEvent[]; nextPageToken?: Uint8Array }> {
this.getEventsCalls.push({ shard, startId, stopId });
return { events: [] };
}
override subscribe(
_shard: number,
- _fromId: string,
+ _fromId: string | undefined,
onEvent: (event: RawHubEvent) => void,
_onError: (error: Error) => void
): RpcSubscription {
@@ -72,7 +79,167 @@ class LiveOnlyRpc extends FakeRpc {
const done = new Promise((resolve) => { finish = resolve; });
const control = { emit: onEvent, end: () => finish?.() };
this.subscriptions.push(control);
- return { cancel: control.end, done };
+ return { cancel: control.end, ready: Promise.resolve(), done };
+ }
+}
+
+class PageFailureRpc implements CollectorRpc {
+ readonly info: NodeInfo = {
+ version: "fake-snapchain/1",
+ numShards: 1,
+ shardInfos: [{ shardId: 7, maxHeight: 100, blockDelay: 0, mempoolSize: 0 }]
+ };
+ readonly subscribeFromIds: Array = [];
+ readonly getEventsCalls: Array<{ startId: string; pageToken?: Uint8Array }> = [];
+ #getEventsCount = 0;
+
+ async getInfo(): Promise {
+ return this.info;
+ }
+
+ async getEvent(): Promise {
+ return mergeEvent("1", "1");
+ }
+
+ async getEvents(_shard: number, startId: string, pageToken?: Uint8Array) {
+ this.#getEventsCount += 1;
+ this.getEventsCalls.push({ startId, pageToken });
+ if (this.#getEventsCount === 1) {
+ return {
+ events: Array.from({ length: 500 }, (_, index) => mergeEvent(String(index + 1), String(index + 1))),
+ nextPageToken: new Uint8Array([1])
+ };
+ }
+ if (this.#getEventsCount === 2) throw new Error("transient second-page failure");
+ return { events: [] };
+ }
+
+ subscribe(
+ _shard: number,
+ fromId: string | undefined,
+ onEvent: (event: RawHubEvent) => void,
+ _onError: (error: Error) => void
+ ): RpcSubscription {
+ this.subscribeFromIds.push(fromId);
+ if (this.subscribeFromIds.length === 1) onEvent(mergeEvent("999", "999"));
+ let finish: (() => void) | undefined;
+ const done = new Promise((resolve) => { finish = resolve; });
+ return { cancel: () => finish?.(), ready: Promise.resolve(), done };
+ }
+
+ close(): void {}
+}
+
+class ReadyGateRpc extends LiveOnlyRpc {
+ #resolveReady: (() => void) | undefined;
+ #onEvent: ((event: RawHubEvent) => void) | undefined;
+
+ receiveMetadata(): void {}
+
+ emitFirst(event: RawHubEvent): void {
+ this.#onEvent?.(event);
+ this.#resolveReady?.();
+ }
+
+ override subscribe(
+ _shard: number,
+ fromId: string | undefined,
+ onEvent: (event: RawHubEvent) => void,
+ _onError: (error: Error) => void
+ ): RpcSubscription {
+ this.subscribeCalls += 1;
+ this.subscribeFromIds.push(fromId);
+ this.#onEvent = onEvent;
+ let finish: (() => void) | undefined;
+ const done = new Promise((resolve) => { finish = resolve; });
+ const ready = new Promise((resolve) => { this.#resolveReady = resolve; });
+ const control = { emit: onEvent, end: () => finish?.() };
+ this.subscriptions.push(control);
+ return { cancel: control.end, ready, done };
+ }
+}
+
+class PreReadyFailureRpc extends LiveOnlyRpc {
+ override subscribe(
+ _shard: number,
+ fromId: string | undefined,
+ onEvent: (event: RawHubEvent) => void,
+ _onError: (error: Error) => void
+ ): RpcSubscription {
+ this.subscribeCalls += 1;
+ this.subscribeFromIds.push(fromId);
+ let finish: (() => void) | undefined;
+ const done = new Promise((resolve) => { finish = resolve; });
+ const control = { emit: onEvent, end: () => finish?.() };
+ this.subscriptions.push(control);
+ return {
+ cancel: control.end,
+ ready: this.subscribeCalls === 1 ? Promise.reject(new Error("pre-ready stream failure")) : Promise.resolve(),
+ done
+ };
+ }
+}
+
+class PendingSecondPageRpc extends LiveOnlyRpc {
+ override getEvents(
+ shard: number,
+ startId: string,
+ _token?: Uint8Array,
+ stopId?: string,
+ signal?: AbortSignal
+ ): Promise<{ events: RawHubEvent[]; nextPageToken?: Uint8Array }> {
+ this.getEventsCalls.push({ shard, startId, stopId });
+ if (this.getEventsCalls.length === 1) {
+ return Promise.resolve({
+ events: Array.from({ length: 500 }, (_, index) => mergeEvent(String(index + 1), String(index + 1))),
+ nextPageToken: new Uint8Array([1])
+ });
+ }
+ return new Promise((_resolve, reject) => {
+ const abort = (): void => {
+ const error = new Error("test GetEvents aborted");
+ error.name = "AbortError";
+ reject(error);
+ };
+ if (signal?.aborted) abort();
+ else signal?.addEventListener("abort", abort, { once: true });
+ });
+ }
+}
+
+class PendingDiscoveryRpc implements CollectorRpc {
+ getInfoCalls = 0;
+ receivedSignal: AbortSignal | undefined;
+ closed = false;
+
+ getInfo(signal?: AbortSignal): Promise {
+ this.getInfoCalls += 1;
+ this.receivedSignal = signal;
+ return new Promise((_resolve, reject) => {
+ const abort = (): void => {
+ const error = new Error("test GetInfo aborted");
+ error.name = "AbortError";
+ reject(error);
+ };
+ if (signal?.aborted) abort();
+ else signal?.addEventListener("abort", abort, { once: true });
+ });
+ }
+
+ async getEvent(): Promise {
+ return mergeEvent("1", "1");
+ }
+
+ async getEvents(): Promise<{ events: RawHubEvent[] }> {
+ return { events: [] };
+ }
+
+ subscribe(): RpcSubscription {
+ return { cancel() {}, ready: Promise.resolve(), done: Promise.resolve() };
+ }
+
+ close(): void {
+ this.closed = true;
}
}
@@ -124,6 +291,9 @@ describe("collector runtime integration", () => {
try {
await waitFor(() => database.getCursor("snapchain", 7) === "3");
expect(rpc.subscribeCalls).toBe(1);
+ expect(rpc.subscribeFromIds).toEqual([undefined]);
+ expect(rpc.getEventsCalls).toContainEqual({ shard: 7, startId: "2", stopId: "3" });
+ expect(rpc.getEventsCalls).not.toContainEqual({ shard: 7, startId: "0", stopId: "3" });
expect(database.loadActions("snapchain", 0)).toHaveLength(3);
expect(database.sourceHealth("snapchain")[0]).toMatchObject({ status: "partial", node: { shardCount: 99, coveredShards: 1, mempoolSize: null, historyComplete: false } });
await waitFor(() => delivered.length > 0);
@@ -174,12 +344,158 @@ describe("collector runtime integration", () => {
}
});
+ it("waits for first live data, then includes that readiness event in fixed-bound reconciliation", async () => {
+ const database = new CollectorDatabase(":memory:");
+ const rpc = new ReadyGateRpc();
+ rpc.info.numShards = 1;
+ const config = loadConfig({ HYPERSNAP_SOURCE_MODE: "unavailable" });
+ config.discoveryIntervalMs = 10_000;
+ const runtime = new CollectorRuntime({
+ config,
+ database,
+ rpcFactory: () => rpc,
+ logger: createLogger({ write() {} })
+ });
+ const running = runtime.run();
+ try {
+ await waitFor(() => rpc.subscribeCalls === 1);
+ expect(rpc.subscribeFromIds).toEqual([undefined]);
+ rpc.receiveMetadata();
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(rpc.getEventsCalls).toEqual([]);
+ rpc.emitFirst(mergeEvent("999", "999"));
+ await waitFor(() => database.getCursor("snapchain", 7) === "999");
+ expect(database.hasEvent("snapchain", 7, "999")).toBe(true);
+ expect(rpc.getEventsCalls.some((call) => call.stopId === "999")).toBe(true);
+ } finally {
+ runtime.stop();
+ rpc.emitFirst(mergeEvent("1000", "1000"));
+ await running;
+ database.close();
+ }
+ });
+
+ it("retries without historical replay when the live stream fails before ready", async () => {
+ const database = new CollectorDatabase(":memory:");
+ const rpc = new PreReadyFailureRpc();
+ rpc.info.numShards = 1;
+ const config = loadConfig({ HYPERSNAP_SOURCE_MODE: "unavailable" });
+ config.discoveryIntervalMs = 10_000;
+ const runtime = new CollectorRuntime({
+ config,
+ database,
+ rpcFactory: () => rpc,
+ logger: createLogger({ write() {} }),
+ random: () => 0
+ });
+ const running = runtime.run();
+ try {
+ await waitFor(() => rpc.subscribeCalls >= 2);
+ expect(rpc.subscribeFromIds.slice(0, 2)).toEqual([undefined, undefined]);
+ expect(rpc.getEventsCalls).toHaveLength(1);
+ expect(database.sourceHealth("snapchain")[0]?.node.reconnectCount).toBe(1);
+ } finally {
+ runtime.stop();
+ await running;
+ database.close();
+ }
+ });
+
+ it("stops promptly while a later replay page is pending and starts no further pages", async () => {
+ const database = new CollectorDatabase(":memory:");
+ const rpc = new PendingSecondPageRpc();
+ rpc.info.numShards = 1;
+ const config = loadConfig({ HYPERSNAP_SOURCE_MODE: "unavailable" });
+ config.discoveryIntervalMs = 10_000;
+ const runtime = new CollectorRuntime({
+ config,
+ database,
+ rpcFactory: () => rpc,
+ logger: createLogger({ write() {} })
+ });
+ const running = runtime.run();
+ try {
+ await waitFor(() => rpc.getEventsCalls.length === 2);
+ runtime.stop();
+ await Promise.race([
+ running,
+ new Promise((_resolve, reject) => setTimeout(() => reject(new Error("runtime shutdown timed out")), 500))
+ ]);
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(rpc.getEventsCalls).toHaveLength(2);
+ } finally {
+ runtime.stop();
+ await running;
+ database.close();
+ }
+ });
+
+ it("stops promptly while source discovery GetInfo is pending", async () => {
+ const database = new CollectorDatabase(":memory:");
+ const rpc = new PendingDiscoveryRpc();
+ const config = loadConfig({ HYPERSNAP_SOURCE_MODE: "unavailable" });
+ const runtime = new CollectorRuntime({
+ config,
+ database,
+ rpcFactory: () => rpc,
+ logger: createLogger({ write() {} })
+ });
+ const running = runtime.run();
+ try {
+ await waitFor(() => rpc.getInfoCalls === 1);
+ expect(rpc.receivedSignal).toBeDefined();
+ runtime.stop();
+ await Promise.race([
+ running,
+ new Promise((_resolve, reject) => setTimeout(() => reject(new Error("runtime shutdown timed out")), 500))
+ ]);
+ expect(rpc.receivedSignal?.aborted).toBe(true);
+ expect(rpc.getInfoCalls).toBe(1);
+ expect(rpc.closed).toBe(true);
+ } finally {
+ runtime.stop();
+ await running;
+ database.close();
+ }
+ });
+
+ it("resumes initial replay from the last completed page without checkpointing a racing live event", async () => {
+ const database = new CollectorDatabase(":memory:");
+ const rpc = new PageFailureRpc();
+ const config = loadConfig({ HYPERSNAP_SOURCE_MODE: "unavailable" });
+ config.discoveryIntervalMs = 10_000;
+ config.pulseIntervalMs = 10;
+ const runtime = new CollectorRuntime({
+ config,
+ database,
+ rpcFactory: () => rpc,
+ logger: createLogger({ write() {} }),
+ random: () => 0
+ });
+ const running = runtime.run();
+ try {
+ await waitFor(() => rpc.subscribeFromIds.length >= 2);
+ expect(rpc.getEventsCalls.slice(0, 3).map((call) => call.startId)).toEqual(["0", "0", "500"]);
+ expect(rpc.subscribeFromIds.slice(0, 2)).toEqual([undefined, undefined]);
+ expect(database.getCursor("snapchain", 7)).toBe("500");
+ expect(database.hasEvent("snapchain", 7, "999")).toBe(true);
+ } finally {
+ runtime.stop();
+ await running;
+ database.close();
+ }
+ });
+
it("backfill scans from zero when a durable cursor exists while normal run resumes it", async () => {
const database = new CollectorDatabase(":memory:");
const rpc = new LiveOnlyRpc();
rpc.info.numShards = 1;
database.checkpointCursor("snapchain", 7, "500", Date.now());
- const config = loadConfig({ HYPERSNAP_SOURCE_MODE: "unavailable" });
+ const config = loadConfig({
+ HYPERSNAP_SOURCE_MODE: "unavailable",
+ SNAPMETER_INGEST_URL: "https://example.test/api/v1/ingest/batch",
+ SNAPMETER_INGEST_SECRET: "backfill-test-secret-with-32-characters"
+ });
const runtime = new CollectorRuntime({
config,
database,
@@ -190,6 +506,10 @@ describe("collector runtime integration", () => {
await runtime.backfill();
expect(rpc.getEventsCalls[0]).toMatchObject({ shard: 7, startId: "0" });
expect(database.getCursor("snapchain", 7)).toBe("500");
+ const queued = database.dueOutbox(Number.MAX_SAFE_INTEGER);
+ expect(queued).toHaveLength(1);
+ const batch = JSON.parse(queued[0]!.payloadJson) as IngestBatch;
+ expect(new Set(batch.snapshots.map((snapshot) => snapshot.updatedAtMs))).toEqual(new Set([batch.sentAtMs]));
} finally {
database.close();
}
diff --git a/apps/collector/src/collector.ts b/apps/collector/src/collector.ts
index ae3f955..d2a1297 100644
--- a/apps/collector/src/collector.ts
+++ b/apps/collector/src/collector.ts
@@ -158,13 +158,14 @@ export class CollectorRuntime {
rpc.close();
}
}
- this.#database.cleanup(this.#now(), this.#config.retentionDays);
- const snapshots = sources().map((source) => buildMetricSnapshot(this.#database, this.#config, source, this.#now()));
+ const snapshotAtMs = this.#now();
+ this.#database.cleanup(snapshotAtMs, this.#config.retentionDays);
+ const snapshots = sources().map((source) => buildMetricSnapshot(this.#database, this.#config, source, snapshotAtMs));
enqueueIngestBatch(this.#database, this.#config, {
snapshots,
- comparisonSnapshots: [buildComparisonSnapshot(this.#database, snapshots, this.#now())],
+ comparisonSnapshots: [buildComparisonSnapshot(this.#database, snapshots, snapshotAtMs)],
health: this.#healthUpdates()
- }, this.#now());
+ }, snapshotAtMs);
await this.#dispatcher.drainOnce();
this.#logger.info("backfill.completed");
}
@@ -183,7 +184,7 @@ export class CollectorRuntime {
try {
while (!signal.aborted) {
try {
- const info = await rpc.getInfo();
+ const info = await rpc.getInfo(signal);
this.#updateInfo(source, info);
const shardIds = discoveredShardIds(info);
if (shardIds.length === 0) throw new Error("node reported zero discoverable shards");
@@ -210,6 +211,7 @@ export class CollectorRuntime {
this.#publishHealth(source);
await abortableDelay(this.#config.discoveryIntervalMs, signal);
} catch (error) {
+ if (signal.aborted) break;
discoveryFailures += 1;
const state = this.#state(source);
state.lastError = errorMessage(error);
@@ -241,7 +243,7 @@ export class CollectorRuntime {
const fromId = highestSeen;
subscription = rpc.subscribe(
shard,
- fromId,
+ undefined,
(event) => {
const eventId = rawEventId(event);
if (eventId) highestSeen = maxEventId(highestSeen, eventId);
@@ -250,6 +252,10 @@ export class CollectorRuntime {
(error) => { streamError = error; }
);
this.#subscriptions.add(subscription);
+ // A live-head stream must be established before historical replay so
+ // events created during enumeration are captured and then reconciled
+ // to the fixed highest-seen bound without requesting backlog twice.
+ await subscription.ready;
const state = this.#state(source);
state.connectedShards.add(shard);
state.replayingShards.add(shard);
@@ -260,15 +266,26 @@ export class CollectorRuntime {
rpc,
shard,
startId: fromId,
+ signal,
onEvent: (event) => {
const eventId = rawEventId(event);
if (eventId) highestSeen = maxEventId(highestSeen, eventId);
this.#handleEvent(source, mode, shard, event, true);
+ },
+ onPageProgress: ({ lastEventId }) => {
+ // Persist replay progress only. A concurrently observed live event
+ // is not a verified gap-free bound until fixed reconciliation ends.
+ if (compareEventIds(lastEventId, fromId) > 0) {
+ this.#database.checkpointCursor(source, shard, lastEventId, this.#now());
+ }
}
});
const catchupWatermark = maxEventId(initial.lastEventId, highestSeen);
if (compareEventIds(catchupWatermark, initial.lastEventId) > 0) {
- await this.#reconcileFixed(source, mode, shard, rpc, fromId, catchupWatermark);
+ // The initial scan already verified through initial.lastEventId.
+ // Resume inclusively there (dedupe is idempotent) and reconcile only
+ // the live tail instead of enumerating the entire backlog again.
+ await this.#reconcileFixed(source, mode, shard, rpc, initial.lastEventId, catchupWatermark, signal);
}
if (compareEventIds(catchupWatermark, fromId) > 0) {
this.#database.checkpointCursor(source, shard, catchupWatermark, this.#now());
@@ -286,7 +303,7 @@ export class CollectorRuntime {
const bound = highestSeen;
const cursor = this.#database.getCursor(source, shard);
if (compareEventIds(bound, cursor) > 0) {
- await this.#reconcileFixed(source, mode, shard, rpc, cursor, bound);
+ await this.#reconcileFixed(source, mode, shard, rpc, cursor, bound, signal);
this.#database.checkpointCursor(source, shard, bound, this.#now());
} else {
// Even an idle stream is checked at a fixed, already durable bound.
@@ -328,7 +345,8 @@ export class CollectorRuntime {
shard: number,
rpc: CollectorRpc,
startId: string,
- bound: string
+ bound: string,
+ signal: AbortSignal
): Promise {
const state = this.#state(source);
state.reconciliationState = "checking";
@@ -338,6 +356,7 @@ export class CollectorRuntime {
shard,
startId,
stopId: bound,
+ signal,
onEvent: (event) => this.#handleEvent(source, mode, shard, event, true)
});
state.reconciliationState = "ok";
diff --git a/apps/collector/src/config.test.ts b/apps/collector/src/config.test.ts
index f2492a6..60d1107 100644
--- a/apps/collector/src/config.test.ts
+++ b/apps/collector/src/config.test.ts
@@ -10,6 +10,8 @@ describe("collector configuration", () => {
SNAPCHAIN_GRPC_URL: "snap.example:443",
SNAPCHAIN_GRPC_TLS: "true",
SNAPCHAIN_GRPC_AUTHORIZATION: "Bearer private",
+ SNAPCHAIN_GRPC_API_KEY: "neynar-private",
+ SNAPCHAIN_RPC_MIN_INTERVAL_MS: "250",
HYPERSNAP_GRPC_URL: "[::1]:4383"
});
expect(config.dataDir).toBe(join(localAppData, "SnapMeter"));
@@ -17,6 +19,8 @@ describe("collector configuration", () => {
url: "snap.example:443",
tls: true,
authorization: "Bearer private",
+ apiKey: "neynar-private",
+ getEventsMinIntervalMs: 250,
sourceMode: "verified"
});
expect(config.endpoints.hypersnap.sourceMode).toBe("derived");
@@ -31,6 +35,26 @@ describe("collector configuration", () => {
})).toThrow(/at least 32/);
});
+ it("requires protected remote ingest and rejects URL credential channels", () => {
+ const secret = "test-secret-with-at-least-32-characters";
+ expect(loadConfig({
+ SNAPMETER_INGEST_URL: "http://127.0.0.1:5173/api/v1/ingest/batch",
+ SNAPMETER_INGEST_SECRET: secret
+ }).ingestUrl).toBe("http://127.0.0.1:5173/api/v1/ingest/batch");
+ expect(() => loadConfig({
+ SNAPMETER_INGEST_URL: "http://example.test/api/v1/ingest/batch",
+ SNAPMETER_INGEST_SECRET: secret
+ })).toThrow(/must use HTTPS/);
+ expect(() => loadConfig({
+ SNAPMETER_INGEST_URL: "https://user:password@example.test/api/v1/ingest/batch",
+ SNAPMETER_INGEST_SECRET: secret
+ })).toThrow(/must not contain credentials/);
+ expect(() => loadConfig({
+ SNAPMETER_INGEST_URL: "https://example.test/api/v1/ingest/batch?secret=value",
+ SNAPMETER_INGEST_SECRET: secret
+ })).toThrow(/query string or fragment/);
+ });
+
it("rejects verified Hypersnap without a dedicated verified-write adapter", () => {
expect(() => loadConfig({ HYPERSNAP_SOURCE_MODE: "verified" })).toThrow(/only implements derived or unavailable/);
});
@@ -41,6 +65,28 @@ describe("collector configuration", () => {
it("rejects schemes and invalid booleans in gRPC configuration", () => {
expect(() => loadConfig({ SNAPCHAIN_GRPC_URL: "http://localhost:3383" })).toThrow(/host:port/);
+ expect(() => loadConfig({ SNAPCHAIN_GRPC_URL: "user@localhost:3383" })).toThrow(/host:port/);
+ expect(() => loadConfig({ SNAPCHAIN_GRPC_URL: "localhost/path:3383" })).toThrow(/host:port/);
expect(() => loadConfig({ SNAPCHAIN_GRPC_TLS: "sometimes" })).toThrow(/true or false/);
});
+
+ it("never sends RPC credentials over a non-loopback plaintext endpoint", () => {
+ expect(() => loadConfig({
+ SNAPCHAIN_GRPC_URL: "snap.example:3383",
+ SNAPCHAIN_GRPC_API_KEY: "private-key"
+ })).toThrow(/GRPC_TLS must be true/);
+ expect(loadConfig({
+ SNAPCHAIN_GRPC_URL: "127.0.0.2:3383",
+ SNAPCHAIN_GRPC_API_KEY: "local-key"
+ }).endpoints.snapchain.apiKey).toBe("local-key");
+ expect(() => loadConfig({
+ SNAPCHAIN_GRPC_AUTHORIZATION: "Bearer value\nInjected: value"
+ })).toThrow(/control characters/);
+ });
+
+ it("defaults RPC pacing to zero and rejects invalid minimum intervals", () => {
+ expect(loadConfig({}).endpoints.snapchain.getEventsMinIntervalMs).toBe(0);
+ expect(() => loadConfig({ SNAPCHAIN_RPC_MIN_INTERVAL_MS: "-1" })).toThrow(/SNAPCHAIN_RPC_MIN_INTERVAL_MS/);
+ expect(() => loadConfig({ HYPERSNAP_RPC_MIN_INTERVAL_MS: "2.5" })).toThrow(/HYPERSNAP_RPC_MIN_INTERVAL_MS/);
+ });
});
diff --git a/apps/collector/src/config.ts b/apps/collector/src/config.ts
index 797ff63..35094a1 100644
--- a/apps/collector/src/config.ts
+++ b/apps/collector/src/config.ts
@@ -6,8 +6,10 @@ export interface RpcEndpointConfig {
url: string;
tls: boolean;
authorization?: string;
+ apiKey?: string;
sourceMode: SourceMode;
timeoutMs: number;
+ getEventsMinIntervalMs: number;
}
export interface CollectorConfig {
@@ -35,12 +37,13 @@ export interface EnvironmentLike {
}
const DEFAULT_LOCAL_DATA = join(homedir(), "AppData", "Local");
+const MAX_CREDENTIAL_LENGTH = 8 * 1024;
export function loadConfig(env: EnvironmentLike = process.env): CollectorConfig {
const localAppData = clean(env.LOCALAPPDATA) ?? DEFAULT_LOCAL_DATA;
const dataDir = resolve(clean(env.SNAPMETER_DATA_DIR) ?? join(localAppData, "SnapMeter"));
const ingestUrl = optionalHttpUrl(env.SNAPMETER_INGEST_URL, "SNAPMETER_INGEST_URL");
- const ingestSecret = clean(env.SNAPMETER_INGEST_SECRET);
+ const ingestSecret = optionalCredential(env.SNAPMETER_INGEST_SECRET, "SNAPMETER_INGEST_SECRET");
if ((ingestUrl === undefined) !== (ingestSecret === undefined)) {
throw new Error("SNAPMETER_INGEST_URL and SNAPMETER_INGEST_SECRET must be configured together");
}
@@ -81,10 +84,18 @@ function endpoint(
timeoutMs: number
): RpcEndpointConfig {
const url = clean(env[`${prefix}_GRPC_URL`]) ?? defaultUrl;
- if (url.includes("://") || !/^(?:\[[^\]]+\]|[^:\s]+):\d{1,5}$/.test(url)) {
+ const endpointMatch = /^(?:\[([^\]\s]+)\]|([^:\s]+)):(\d{1,5})$/.exec(url);
+ const host = endpointMatch?.[1] ?? endpointMatch?.[2] ?? "";
+ if (
+ url.length > 512
+ || url.includes("://")
+ || endpointMatch === null
+ || /[/\\@?#]/.test(host)
+ || hasControlCharacters(host)
+ ) {
throw new Error(`${prefix}_GRPC_URL must be host:port without a scheme`);
}
- const port = Number(url.slice(url.lastIndexOf(":") + 1));
+ const port = Number(endpointMatch[3]);
if (port < 1 || port > 65_535) throw new Error(`${prefix}_GRPC_URL has an invalid port`);
const sourceMode = sourceModeValue(env[`${prefix}_SOURCE_MODE`], defaultMode, `${prefix}_SOURCE_MODE`);
if (prefix === "HYPERSNAP" && sourceMode === "verified") {
@@ -93,12 +104,26 @@ function endpoint(
if (prefix === "SNAPCHAIN" && sourceMode === "derived") {
throw new Error("SNAPCHAIN_SOURCE_MODE must be verified or unavailable; canonical Snapchain merges are not a derived source");
}
+ const tls = booleanValue(env[`${prefix}_GRPC_TLS`], false, `${prefix}_GRPC_TLS`);
+ const authorization = optionalCredential(env[`${prefix}_GRPC_AUTHORIZATION`], `${prefix}_GRPC_AUTHORIZATION`);
+ const apiKey = optionalCredential(env[`${prefix}_GRPC_API_KEY`], `${prefix}_GRPC_API_KEY`);
+ if (!tls && !isLoopbackHost(host) && (authorization !== undefined || apiKey !== undefined)) {
+ throw new Error(`${prefix}_GRPC_TLS must be true when credentials are configured for a non-loopback endpoint`);
+ }
return {
url,
- tls: booleanValue(env[`${prefix}_GRPC_TLS`], false, `${prefix}_GRPC_TLS`),
- authorization: clean(env[`${prefix}_GRPC_AUTHORIZATION`]),
+ tls,
+ authorization,
+ apiKey,
sourceMode,
- timeoutMs
+ timeoutMs,
+ getEventsMinIntervalMs: integer(
+ env[`${prefix}_RPC_MIN_INTERVAL_MS`],
+ 0,
+ 0,
+ 3_600_000,
+ `${prefix}_RPC_MIN_INTERVAL_MS`
+ )
};
}
@@ -118,10 +143,39 @@ function optionalHttpUrl(value: string | undefined, name: string): string | unde
} catch {
throw new Error(`${name} must be an absolute HTTP(S) URL`);
}
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`${name} must use HTTP(S)`);
+ if (parsed.username || parsed.password) throw new Error(`${name} must not contain credentials`);
+ if (parsed.search || parsed.hash) throw new Error(`${name} must not contain a query string or fragment`);
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLoopbackHost(parsed.hostname))) {
+ throw new Error(`${name} must use HTTPS except for an explicit loopback development endpoint`);
+ }
return parsed.toString();
}
+function optionalCredential(value: string | undefined, name: string): string | undefined {
+ const normalized = clean(value);
+ if (normalized === undefined) return undefined;
+ if (normalized.length > MAX_CREDENTIAL_LENGTH || hasControlCharacters(normalized)) {
+ throw new Error(`${name} contains unsupported control characters or is too long`);
+ }
+ return normalized;
+}
+
+function isLoopbackHost(value: string): boolean {
+ const host = value.replace(/^\[|\]$/g, "").toLowerCase();
+ if (host === "localhost" || host === "::1" || host === "0:0:0:0:0:0:0:1") return true;
+ const ipv4 = /^(\d{1,3})(?:\.(\d{1,3})){3}$/.exec(host);
+ if (!ipv4 || Number(ipv4[1]) !== 127) return false;
+ return host.split(".").every((part) => Number(part) <= 255);
+}
+
+function hasControlCharacters(value: string): boolean {
+ for (let index = 0; index < value.length; index += 1) {
+ const code = value.charCodeAt(index);
+ if (code <= 31 || code === 127) return true;
+ }
+ return false;
+}
+
function booleanValue(value: string | undefined, fallback: boolean, name: string): boolean {
const normalized = clean(value)?.toLowerCase();
if (normalized === undefined) return fallback;
diff --git a/apps/collector/src/database.test.ts b/apps/collector/src/database.test.ts
index 1031f0a..0118fb4 100644
--- a/apps/collector/src/database.test.ts
+++ b/apps/collector/src/database.test.ts
@@ -86,6 +86,7 @@ describe("collector SQLite state", () => {
try {
const first = new CollectorDatabase(path);
const firstCollectorId = first.collectorId;
+ const firstPseudonym = first.actorDayPseudonym("snapchain", "2026-08-13", "42");
record(first, action("snapchain", "42", "500"), "500", 9);
first.checkpointCursor("snapchain", 9, "500", NOW);
first.recordHistoryCoverage("snapchain", 9, NOW - 31 * 86_400_000);
@@ -94,6 +95,7 @@ describe("collector SQLite state", () => {
const second = new CollectorDatabase(path);
try {
expect(second.collectorId).toBe(firstCollectorId);
+ expect(second.actorDayPseudonym("snapchain", "2026-08-13", "42")).toBe(firstPseudonym);
expect(second.getCursor("snapchain", 9)).toBe("500");
expect(second.historyCoverageStart("snapchain", [9], 1)).toBe(NOW - 31 * 86_400_000);
expect(record(second, action("snapchain", "42", "500"), "500", 9).duplicate).toBe(true);
@@ -136,12 +138,17 @@ describe("collector SQLite state", () => {
seeded.close();
const legacy = new DatabaseSync(path);
- legacy.exec("DROP TABLE history_coverage; DELETE FROM schema_migrations WHERE version = 2;");
+ legacy.exec(`
+ DROP TABLE history_coverage;
+ DROP TABLE collector_secrets;
+ DELETE FROM schema_migrations WHERE version >= 2;
+ UPDATE collector_metadata SET value = '1' WHERE key = 'schema_version';
+ `);
legacy.close();
const upgraded = new CollectorDatabase(path);
try {
- expect(upgraded.status().schemaVersion).toBe(2);
+ expect(upgraded.status().schemaVersion).toBe(3);
expect(upgraded.loadActions("snapchain", 0).map((item) => item.fid)).toEqual(["77"]);
expect(upgraded.getCursor("snapchain", 3)).toBe("700");
upgraded.recordHistoryCoverage("snapchain", 3, NOW - 31 * 86_400_000);
@@ -154,4 +161,120 @@ describe("collector SQLite state", () => {
if (resolved.startsWith(resolve(tmpdir()))) rmSync(resolved, { recursive: true, force: true });
}
});
+
+ it("transactionally provisions a 32-byte local pseudonym key when upgrading version 2", () => {
+ const directory = mkdtempSync(join(tmpdir(), "snapmeter-key-migration-test-"));
+ const path = join(directory, "state.sqlite3");
+ try {
+ const seeded = new CollectorDatabase(path);
+ seeded.close();
+
+ const legacy = new DatabaseSync(path);
+ legacy.exec(`
+ DROP TABLE collector_secrets;
+ DELETE FROM schema_migrations WHERE version = 3;
+ UPDATE collector_metadata SET value = '2' WHERE key = 'schema_version';
+ `);
+ legacy.close();
+
+ const upgraded = new CollectorDatabase(path);
+ expect(upgraded.status().schemaVersion).toBe(3);
+ expect(upgraded.actorDayPseudonym("snapchain", "2026-08-13", "77")).toMatch(/^[0-9a-f]{64}$/);
+ expect(() => upgraded.setMetadata("actor_pseudonym_key_v1", "attacker-controlled"))
+ .toThrow(/unsupported runtime metadata key/);
+ upgraded.close();
+
+ const inspected = new DatabaseSync(path);
+ const row = inspected.prepare(
+ "SELECT value FROM collector_secrets WHERE name = 'actor_pseudonym_key_v1'"
+ ).get() as { value: Uint8Array };
+ const migration = inspected.prepare("SELECT COUNT(*) AS total FROM schema_migrations WHERE version = 3")
+ .get() as { total: number };
+ inspected.close();
+ expect(row.value).toBeInstanceOf(Uint8Array);
+ expect(row.value).toHaveLength(32);
+ expect(Number(migration.total)).toBe(1);
+ } finally {
+ const resolved = resolve(directory);
+ if (resolved.startsWith(resolve(tmpdir()))) rmSync(resolved, { recursive: true, force: true });
+ }
+ });
+
+ it("provisions a distinct pseudonym key for each independently initialized database", () => {
+ const left = new CollectorDatabase(":memory:");
+ const right = new CollectorDatabase(":memory:");
+ try {
+ expect(left.actorDayPseudonym("snapchain", "2026-08-13", "77"))
+ .not.toBe(right.actorDayPseudonym("snapchain", "2026-08-13", "77"));
+ } finally {
+ left.close();
+ right.close();
+ }
+ });
+
+ it("preserves version-2 queued actor state and outbox bytes across the key migration", () => {
+ const directory = mkdtempSync(join(tmpdir(), "snapmeter-key-outbox-migration-test-"));
+ const path = join(directory, "state.sqlite3");
+ const payload = JSON.stringify({ schemaVersion: 1, batchId: "frozen-version-2-payload", actorDays: [{ fidHash: "a".repeat(64) }] });
+ try {
+ const seeded = new CollectorDatabase(path);
+ record(seeded, action("snapchain", "99", "999"), "999", 2);
+ seeded.close();
+
+ const legacy = new DatabaseSync(path);
+ legacy.prepare("INSERT INTO outbox(batch_id, payload_json, created_at_ms, next_attempt_at_ms) VALUES (?, ?, ?, ?)")
+ .run("frozen-version-2-payload", payload, NOW, NOW);
+ legacy.prepare("UPDATE actor_days SET queued_batch_id=? WHERE source='snapchain' AND day='2026-08-13' AND fid='99'")
+ .run("frozen-version-2-payload");
+ legacy.exec(`
+ DROP TABLE collector_secrets;
+ DELETE FROM schema_migrations WHERE version = 3;
+ UPDATE collector_metadata SET value = '2' WHERE key = 'schema_version';
+ `);
+ legacy.close();
+
+ const upgraded = new CollectorDatabase(path);
+ expect(upgraded.status().schemaVersion).toBe(3);
+ expect(upgraded.dueOutbox(NOW)[0]?.payloadJson).toBe(payload);
+ expect(upgraded.pendingActorDays()).toEqual([]);
+ upgraded.close();
+
+ const inspected = new DatabaseSync(path);
+ const queued = inspected.prepare(
+ "SELECT queued_batch_id FROM actor_days WHERE source='snapchain' AND day='2026-08-13' AND fid='99'"
+ ).get() as { queued_batch_id: string };
+ inspected.close();
+ expect(queued.queued_batch_id).toBe("frozen-version-2-payload");
+ } finally {
+ const resolved = resolve(directory);
+ if (resolved.startsWith(resolve(tmpdir()))) rmSync(resolved, { recursive: true, force: true });
+ }
+ });
+
+ it.each(["missing", "malformed", "unexpected"] as const)("fails closed when existing version-3 pseudonym key state is %s", (state) => {
+ const directory = mkdtempSync(join(tmpdir(), `snapmeter-key-${state}-test-`));
+ const path = join(directory, "state.sqlite3");
+ try {
+ const seeded = new CollectorDatabase(path);
+ seeded.close();
+ const corrupted = new DatabaseSync(path);
+ if (state === "missing") {
+ corrupted.exec("DELETE FROM collector_secrets WHERE name='actor_pseudonym_key_v1'");
+ } else if (state === "malformed") {
+ corrupted.exec("PRAGMA ignore_check_constraints=ON");
+ corrupted.prepare("UPDATE collector_secrets SET value=? WHERE name='actor_pseudonym_key_v1'")
+ .run(new Uint8Array(31));
+ } else {
+ corrupted.exec("PRAGMA ignore_check_constraints=ON");
+ corrupted.prepare("INSERT INTO collector_secrets(name, value) VALUES ('unexpected_key', ?)")
+ .run(new Uint8Array(32));
+ }
+ corrupted.close();
+ expect(() => new CollectorDatabase(path)).toThrow(/actor pseudonym key is missing or invalid/);
+ expect(() => rmSync(directory, { recursive: true, force: true })).not.toThrow();
+ } finally {
+ const resolved = resolve(directory);
+ if (resolved.startsWith(resolve(tmpdir()))) rmSync(resolved, { recursive: true, force: true });
+ }
+ });
});
diff --git a/apps/collector/src/database.ts b/apps/collector/src/database.ts
index 7775561..c22382c 100644
--- a/apps/collector/src/database.ts
+++ b/apps/collector/src/database.ts
@@ -1,6 +1,6 @@
import { mkdirSync } from "node:fs";
import { dirname } from "node:path";
-import { randomUUID } from "node:crypto";
+import { createHmac, randomBytes, randomUUID } from "node:crypto";
import { DatabaseSync, type StatementSync } from "node:sqlite";
import type {
ActionFamily,
@@ -45,6 +45,7 @@ export interface OutboxRow {
attemptCount: number;
nextAttemptAtMs: number;
createdAtMs: number;
+ lastError: string | null;
}
export interface DatabaseStatus {
@@ -60,18 +61,35 @@ export interface DatabaseStatus {
lastCloudAckAtMs: number | null;
}
-const SCHEMA_VERSION = 2;
+const SCHEMA_VERSION = 3;
+const ACTOR_PSEUDONYM_KEY_NAME = "actor_pseudonym_key_v1";
+const ACTOR_PSEUDONYM_KEY_BYTES = 32;
+const ACTOR_PSEUDONYM_DOMAIN = "snapmeter-actor-day-v2\0";
+const MUTABLE_RUNTIME_METADATA = new Set([
+ "collector_started_at_ms",
+ "collector_stopped_at_ms",
+ "collector_heartbeat_at_ms",
+ "doctor_last_write_at_ms"
+]);
+
export class CollectorDatabase {
readonly #database: DatabaseSync;
+ readonly #actorPseudonymKey: Uint8Array;
constructor(readonly path: string) {
if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true });
this.#database = new DatabaseSync(path);
- this.#database.exec("PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON; PRAGMA synchronous=FULL;");
- if (path !== ":memory:") this.#database.exec("PRAGMA journal_mode=WAL;");
- this.#migrate();
- if (!this.getMetadata("collector_id")) this.setMetadata("collector_id", randomUUID());
- this.setMetadata("schema_version", String(SCHEMA_VERSION));
+ try {
+ this.#database.exec("PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON; PRAGMA synchronous=FULL;");
+ if (path !== ":memory:") this.#database.exec("PRAGMA journal_mode=WAL;");
+ this.#migrate();
+ if (!this.#getMetadata("collector_id")) this.#setMetadata("collector_id", randomUUID());
+ this.#setMetadata("schema_version", String(SCHEMA_VERSION));
+ this.#actorPseudonymKey = this.#loadActorPseudonymKey();
+ } catch (error) {
+ try { this.#database.close(); } catch { /* preserve the initialization error */ }
+ throw error;
+ }
}
close(): void {
@@ -79,11 +97,19 @@ export class CollectorDatabase {
}
get collectorId(): string {
- const collectorId = this.getMetadata("collector_id");
+ const collectorId = this.#getMetadata("collector_id");
if (!collectorId) throw new Error("collector id is missing");
return collectorId;
}
+ actorDayPseudonym(source: Source, day: string, fid: string): string {
+ const message = JSON.stringify([source, day, fid]);
+ return createHmac("sha256", this.#actorPseudonymKey)
+ .update(ACTOR_PSEUDONYM_DOMAIN)
+ .update(message)
+ .digest("hex");
+ }
+
recordEvent(event: RecordedEvent): RecordEventResult {
assertEventId(event.eventId);
if (!Number.isSafeInteger(event.shard) || event.shard < 0) throw new Error("invalid shard index");
@@ -337,7 +363,7 @@ export class CollectorDatabase {
dueOutbox(nowMs: number, limit = 20): OutboxRow[] {
return (this.#prepare(`
- SELECT id, batch_id, payload_json, attempt_count, next_attempt_at_ms, created_at_ms
+ SELECT id, batch_id, payload_json, attempt_count, next_attempt_at_ms, created_at_ms, last_error
FROM outbox
WHERE next_attempt_at_ms <= ?
ORDER BY id
@@ -348,15 +374,16 @@ export class CollectorDatabase {
payloadJson: String(row.payload_json),
attemptCount: Number(row.attempt_count),
nextAttemptAtMs: Number(row.next_attempt_at_ms),
- createdAtMs: Number(row.created_at_ms)
+ createdAtMs: Number(row.created_at_ms),
+ lastError: row.last_error === null ? null : String(row.last_error)
}));
}
acknowledgeOutbox(id: number, batchId: string, acknowledgedAtMs: number): void {
this.#transaction(() => {
this.#prepare("DELETE FROM outbox WHERE id = ? AND batch_id = ?").run(id, batchId);
- this.setMetadata("last_cloud_ack_at_ms", String(acknowledgedAtMs));
- this.setMetadata("last_cloud_batch_id", batchId);
+ this.#setMetadata("last_cloud_ack_at_ms", String(acknowledgedAtMs));
+ this.#setMetadata("last_cloud_batch_id", batchId);
});
}
@@ -424,7 +451,7 @@ export class CollectorDatabase {
SELECT MIN(action_at_ms) AS oldest, MAX(action_at_ms) AS newest FROM activity_actions
`).get() as SqlRow | undefined;
return {
- schemaVersion: Number(this.getMetadata("schema_version") ?? 0),
+ schemaVersion: Number(this.#getMetadata("schema_version") ?? 0),
collectorId: this.collectorId,
actions: this.#count("activity_actions"),
dedupeEvents: this.#count("event_dedupe"),
@@ -433,22 +460,49 @@ export class CollectorDatabase {
pendingOutbox: this.#count("outbox"),
oldestActionAtMs: range?.oldest === null || range?.oldest === undefined ? null : Number(range.oldest),
newestActionAtMs: range?.newest === null || range?.newest === undefined ? null : Number(range.newest),
- lastCloudAckAtMs: nullableInteger(this.getMetadata("last_cloud_ack_at_ms"))
+ lastCloudAckAtMs: nullableInteger(this.#getMetadata("last_cloud_ack_at_ms"))
};
}
- getMetadata(key: string): string | null {
+ setMetadata(key: string, value: string): void {
+ if (!MUTABLE_RUNTIME_METADATA.has(key)) throw new Error(`unsupported runtime metadata key: ${key}`);
+ this.#setMetadata(key, value);
+ }
+
+ #getMetadata(key: string): string | null {
const row = this.#prepare("SELECT value FROM collector_metadata WHERE key = ?").get(key) as { value?: unknown } | undefined;
return row?.value === undefined ? null : String(row.value);
}
- setMetadata(key: string, value: string): void {
+ #setMetadata(key: string, value: string): void {
this.#prepare(`
INSERT INTO collector_metadata(key, value) VALUES (?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value
`).run(key, value);
}
+ #loadActorPseudonymKey(): Uint8Array {
+ let rows: Array<{ name?: unknown; value?: unknown }>;
+ try {
+ rows = this.#prepare("SELECT name, value FROM collector_secrets").all() as Array<{
+ name?: unknown;
+ value?: unknown;
+ }>;
+ } catch {
+ throw new Error("actor pseudonym key is missing or invalid");
+ }
+ const row = rows[0];
+ if (
+ rows.length !== 1 ||
+ row?.name !== ACTOR_PSEUDONYM_KEY_NAME ||
+ !(row.value instanceof Uint8Array) ||
+ row.value.byteLength !== ACTOR_PSEUDONYM_KEY_BYTES
+ ) {
+ throw new Error("actor pseudonym key is missing or invalid");
+ }
+ return new Uint8Array(row.value);
+ }
+
#count(table: "activity_actions" | "event_dedupe" | "actor_days" | "minute_buckets" | "outbox"): number {
return numberColumn(this.#prepare(`SELECT COUNT(*) AS value FROM ${table}`).get(), "value");
}
@@ -490,6 +544,15 @@ export class CollectorDatabase {
this.#prepare("INSERT INTO schema_migrations(version, applied_at_ms) VALUES (2, ?)").run(Date.now());
});
}
+ if (current < 3) {
+ this.#transaction(() => {
+ this.#database.exec(MIGRATION_3);
+ this.#prepare("INSERT INTO collector_secrets(name, value) VALUES (?, ?)")
+ .run(ACTOR_PSEUDONYM_KEY_NAME, randomBytes(ACTOR_PSEUDONYM_KEY_BYTES));
+ this.#loadActorPseudonymKey();
+ this.#prepare("INSERT INTO schema_migrations(version, applied_at_ms) VALUES (3, ?)").run(Date.now());
+ });
+ }
}
}
@@ -655,3 +718,10 @@ const MIGRATION_2 = `
PRIMARY KEY (source, shard)
) STRICT;
`;
+
+const MIGRATION_3 = `
+ CREATE TABLE collector_secrets (
+ name TEXT PRIMARY KEY CHECK (name IN ('actor_pseudonym_key_v1')),
+ value BLOB NOT NULL CHECK (typeof(value) = 'blob' AND length(value) = 32)
+ ) STRICT;
+`;
diff --git a/apps/collector/src/delivery.test.ts b/apps/collector/src/delivery.test.ts
index 44618ba..06ff847 100644
--- a/apps/collector/src/delivery.test.ts
+++ b/apps/collector/src/delivery.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it, vi } from "vitest";
import { verifyIngestSignature, type IngestBatch } from "@snapmeter/contracts";
import { DAY_MS, type ActivityRecord } from "@snapmeter/metrics";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { DatabaseSync } from "node:sqlite";
import { loadConfig } from "./config.js";
import { CollectorDatabase } from "./database.js";
import {
@@ -9,19 +13,18 @@ import {
PulseAccumulator,
buildComparisonSnapshot,
buildMetricSnapshot,
- enqueueIngestBatch,
- hashFid
+ enqueueIngestBatch
} from "./delivery.js";
import { createLogger } from "./logger.js";
const NOW = Date.UTC(2026, 7, 13, 12);
const SECRET = "a-long-private-ingest-secret-for-tests";
-function config() {
+function config(ingestSecret = SECRET) {
return loadConfig({
LOCALAPPDATA: "C:\\tmp",
SNAPMETER_INGEST_URL: "https://example.test/api/v1/ingest/batch",
- SNAPMETER_INGEST_SECRET: SECRET
+ SNAPMETER_INGEST_SECRET: ingestSecret
});
}
@@ -52,11 +55,58 @@ describe("pulse and batch delivery", () => {
expect(JSON.stringify(packet)).not.toContain('"fid"');
});
- it("HMAC-hashes actor IDs deterministically across sources and separates keys", () => {
- expect(hashFid(SECRET, "123")).toBe(hashFid(SECRET, "123"));
- expect(hashFid(SECRET, "123")).not.toBe(hashFid("different-secret", "123"));
- expect(hashFid(SECRET, "123")).not.toContain("123");
- expect(hashFid(SECRET, "123")).toHaveLength(64);
+ it("domain-separates local actor pseudonyms by source and UTC day", () => {
+ const database = new CollectorDatabase(":memory:");
+ try {
+ const snapchain = database.actorDayPseudonym("snapchain", "2026-08-13", "123");
+ expect(snapchain).toBe(database.actorDayPseudonym("snapchain", "2026-08-13", "123"));
+ expect(snapchain).not.toBe(database.actorDayPseudonym("hypersnap", "2026-08-13", "123"));
+ expect(snapchain).not.toBe(database.actorDayPseudonym("snapchain", "2026-08-14", "123"));
+ expect(snapchain).not.toContain("123");
+ expect(snapchain).toMatch(/^[0-9a-f]{64}$/);
+ } finally {
+ database.close();
+ }
+ });
+
+ it("keeps queued actor pseudonyms stable while retries use the rotated transport secret", async () => {
+ const database = new CollectorDatabase(":memory:");
+ try {
+ record(database, action("snapchain", "123", "123"), "123");
+ const day = "2026-08-13";
+ const expected = database.actorDayPseudonym("snapchain", day, "123");
+ const beforeSecret = "transport-secret-before-rotation-123";
+ const afterSecret = "transport-secret-after-rotation-4567";
+ const beforeRotation = enqueueIngestBatch(database, config(beforeSecret), {}, NOW);
+ expect(beforeRotation?.actorDays).toContainEqual({ source: "snapchain", day, fidHash: expected });
+
+ const rotated = config(afterSecret);
+ expect(database.actorDayPseudonym("snapchain", day, "123")).toBe(expected);
+ const fetcher = vi.fn(async (_input: string | URL | Request, init?: RequestInit) => {
+ const headers = new Headers(init?.headers);
+ const timestamp = headers.get("x-snapmeter-timestamp") as string;
+ const nonce = headers.get("x-snapmeter-nonce") as string;
+ const signature = headers.get("x-snapmeter-signature") as string;
+ const body = String(init?.body);
+ expect(JSON.parse(body)).toMatchObject({
+ actorDays: [{ source: "snapchain", day, fidHash: expected }]
+ });
+ await expect(verifyIngestSignature(afterSecret, timestamp, nonce, body, signature)).resolves.toBe(true);
+ await expect(verifyIngestSignature(beforeSecret, timestamp, nonce, body, signature)).resolves.toBe(false);
+ return Response.json({ ok: true, batchId: nonce, duplicate: false, acceptedAtMs: NOW + 1 });
+ });
+ const dispatcher = new OutboxDispatcher(
+ database,
+ rotated,
+ createLogger({ write() {} }),
+ fetcher,
+ () => NOW,
+ () => 0.5
+ );
+ await expect(dispatcher.drainOnce()).resolves.toEqual({ acknowledged: 1, failed: 0 });
+ } finally {
+ database.close();
+ }
});
it("builds an exact overlap comparison and stays under the Worker record budget", () => {
@@ -115,6 +165,94 @@ describe("pulse and batch delivery", () => {
}
});
+ it("does not persist or log an untrusted ingest error body", async () => {
+ const database = new CollectorDatabase(":memory:");
+ try {
+ const leaked = "Bearer should-never-be-stored";
+ const lines: string[] = [];
+ const batch = enqueueIngestBatch(database, config(), {}, NOW);
+ expect(batch).not.toBeNull();
+ const dispatcher = new OutboxDispatcher(
+ database,
+ config(),
+ createLogger({ write: (line) => lines.push(line) }),
+ async () => new Response(`upstream diagnostics ${leaked}`, { status: 503 }),
+ () => NOW,
+ () => 0.5
+ );
+ await expect(dispatcher.drainOnce()).resolves.toEqual({ acknowledged: 0, failed: 1 });
+ const stored = database.dueOutbox(NOW + 60_000)[0];
+ expect(stored).toBeDefined();
+ expect(stored?.lastError).toBe("ingest returned HTTP 503");
+ expect(JSON.stringify(lines)).not.toContain(leaked);
+ } finally {
+ database.close();
+ }
+ });
+
+ it("rejects oversized successful ingest acknowledgements", async () => {
+ const database = new CollectorDatabase(":memory:");
+ try {
+ const batch = enqueueIngestBatch(database, config(), {}, NOW);
+ expect(batch).not.toBeNull();
+ const dispatcher = new OutboxDispatcher(
+ database,
+ config(),
+ createLogger({ write() {} }),
+ async () => new Response("x".repeat(16 * 1024 + 1), { status: 200 }),
+ () => NOW,
+ () => 0.5
+ );
+ await expect(dispatcher.drainOnce()).resolves.toEqual({ acknowledged: 0, failed: 1 });
+ expect(database.status().pendingOutbox).toBe(1);
+ } finally {
+ database.close();
+ }
+ });
+
+ it("never exposes the local pseudonym key through status, delivery, outbox, or logs", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "snapmeter-key-exposure-test-"));
+ const path = join(directory, "state.sqlite3");
+ let database: CollectorDatabase | undefined = new CollectorDatabase(path);
+ try {
+ record(database, action("snapchain", "321", "321"), "321");
+ const batch = enqueueIngestBatch(database, config(), {}, NOW);
+ expect(batch).not.toBeNull();
+ const lines: string[] = [];
+ const dispatcher = new OutboxDispatcher(
+ database,
+ config(),
+ createLogger({ write: (line) => lines.push(line) }),
+ async () => new Response("untrusted failure body", { status: 503 }),
+ () => NOW,
+ () => 0.5
+ );
+ await expect(dispatcher.drainOnce()).resolves.toEqual({ acknowledged: 0, failed: 1 });
+ const publicSurfaces = JSON.stringify({
+ status: database.status(),
+ batch,
+ outbox: database.dueOutbox(Number.MAX_SAFE_INTEGER),
+ logs: lines
+ });
+ expect(publicSurfaces).not.toContain("actor_pseudonym_key_v1");
+ expect(publicSurfaces).not.toContain('"fid":"321"');
+
+ database.close();
+ database = undefined;
+ const inspected = new DatabaseSync(path);
+ const row = inspected.prepare(
+ "SELECT value FROM collector_secrets WHERE name = 'actor_pseudonym_key_v1'"
+ ).get() as { value: Uint8Array };
+ inspected.close();
+ expect(publicSurfaces).not.toContain(Buffer.from(row.value).toString("base64url"));
+ expect(publicSurfaces).not.toContain(Buffer.from(row.value).toString("hex"));
+ } finally {
+ database?.close();
+ const resolved = resolve(directory);
+ if (resolved.startsWith(resolve(tmpdir()))) rmSync(resolved, { recursive: true, force: true });
+ }
+ });
+
it("builds metrics from at least 31 days of local reconstruction", () => {
const database = new CollectorDatabase(":memory:");
try {
diff --git a/apps/collector/src/delivery.ts b/apps/collector/src/delivery.ts
index 02d8fbd..494a4a6 100644
--- a/apps/collector/src/delivery.ts
+++ b/apps/collector/src/delivery.ts
@@ -1,4 +1,4 @@
-import { createHmac, randomUUID } from "node:crypto";
+import { randomUUID } from "node:crypto";
import {
IngestBatchSchema,
IngestResponseSchema,
@@ -156,7 +156,7 @@ export function enqueueIngestBatch(
const collectorId = database.collectorId;
const actorDays = actorRows.map(({ value, fid }) => ({
...value,
- fidHash: hashFid(config.ingestSecret as string, fid)
+ fidHash: database.actorDayPseudonym(value.source, value.day, fid)
}));
const batch: IngestBatch = {
schemaVersion: SCHEMA_VERSION,
@@ -209,11 +209,6 @@ export function buildComparisonSnapshot(
};
}
-export function hashFid(secret: string, fid: string): string {
- if (!secret) throw new Error("actor-day hashing requires the ingest secret");
- return createHmac("sha256", secret).update("snapmeter-actor-day-v1\0").update(fid).digest("hex");
-}
-
const ACTION_FAMILIES: readonly ActionFamily[] = [
"cast",
"reaction",
@@ -272,8 +267,11 @@ export class OutboxDispatcher {
body: row.payloadJson,
signal: AbortSignal.timeout(15_000)
});
- const body = await response.text();
- if (!response.ok) throw new Error(`ingest returned HTTP ${response.status}: ${body.slice(0, 200)}`);
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => undefined);
+ throw new Error(`ingest returned HTTP ${response.status}`);
+ }
+ const body = await boundedResponseText(response);
const parsed = IngestResponseSchema.parse(JSON.parse(body));
if (parsed.batchId !== row.batchId) throw new Error("ingest acknowledgement batch id did not match");
this.database.acknowledgeOutbox(row.id, row.batchId, parsed.acceptedAtMs);
@@ -298,6 +296,39 @@ export class OutboxDispatcher {
}
}
+async function boundedResponseText(response: Response, maximumBytes = 16 * 1024): Promise {
+ const advertised = response.headers.get("content-length");
+ if (advertised !== null && (!/^\d+$/.test(advertised) || Number(advertised) > maximumBytes)) {
+ await response.body?.cancel().catch(() => undefined);
+ throw new Error("ingest response was too large");
+ }
+ if (!response.body) return "";
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ while (true) {
+ const result = await reader.read();
+ if (result.done) break;
+ total += result.value.byteLength;
+ if (total > maximumBytes) {
+ await reader.cancel().catch(() => undefined);
+ throw new Error("ingest response was too large");
+ }
+ chunks.push(result.value);
+ }
+ const bytes = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ try {
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
+ } catch {
+ throw new Error("ingest response was not valid UTF-8");
+ }
+}
+
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
diff --git a/apps/collector/src/doctor.test.ts b/apps/collector/src/doctor.test.ts
index 20ded22..3fbbc99 100644
--- a/apps/collector/src/doctor.test.ts
+++ b/apps/collector/src/doctor.test.ts
@@ -69,7 +69,7 @@ function fakeRpc(): CollectorRpc {
}),
getEvent: async () => ({ id: "10" }),
getEvents: async () => ({ events: [] }),
- subscribe: () => ({ cancel() {}, done: Promise.resolve() }),
+ subscribe: () => ({ cancel() {}, ready: Promise.resolve(), done: Promise.resolve() }),
close() {}
};
}
diff --git a/apps/collector/src/logger.test.ts b/apps/collector/src/logger.test.ts
index 597737c..276be9b 100644
--- a/apps/collector/src/logger.test.ts
+++ b/apps/collector/src/logger.test.ts
@@ -1,14 +1,32 @@
import { describe, expect, it } from "vitest";
-import { createLogger } from "./logger.js";
+import { createLogger, sensitiveEnvironmentValues } from "./logger.js";
describe("structured logging", () => {
it("redacts sensitive fields and configured secrets", () => {
const lines: string[] = [];
const logger = createLogger({ write: (line) => lines.push(line), now: () => 0, secrets: ["private-value"] });
- logger.info("test", { authorization: "Bearer private-value", nested: { message: "failure private-value", token: "abc" } });
+ logger.info("test", {
+ authorization: "Bearer private-value",
+ apiKey: "neynar-key",
+ actorPseudonymKey: "pseudonym-private-value",
+ hash_key: "hash-private-value",
+ nested: { message: "failure private-value", token: "abc" }
+ });
const record = JSON.parse(lines[0] as string) as Record;
expect(record.authorization).toBe("[REDACTED]");
expect(JSON.stringify(record)).not.toContain("private-value");
+ expect(JSON.stringify(record)).not.toContain("neynar-key");
expect(JSON.stringify(record)).not.toContain("abc");
+ expect(JSON.stringify(record)).not.toContain("pseudonym-private-value");
+ expect(JSON.stringify(record)).not.toContain("hash-private-value");
+ });
+
+ it("collects only sensitive environment values for fatal-error scrubbing", () => {
+ expect(sensitiveEnvironmentValues({
+ SNAPMETER_INGEST_SECRET: " secret-value ",
+ SNAPCHAIN_GRPC_API_KEY: "api-key-value",
+ SNAPCHAIN_GRPC_URL: "public.example:443"
+ })).toEqual(expect.arrayContaining([" secret-value ", "secret-value", "api-key-value"]));
+ expect(sensitiveEnvironmentValues({ SNAPCHAIN_GRPC_URL: "public.example:443" })).toEqual([]);
});
});
diff --git a/apps/collector/src/logger.ts b/apps/collector/src/logger.ts
index 9210047..e7bc319 100644
--- a/apps/collector/src/logger.ts
+++ b/apps/collector/src/logger.ts
@@ -15,7 +15,7 @@ export interface LoggerOptions {
}
const LEVELS: Record = { debug: 10, info: 20, warn: 30, error: 40 };
-const SENSITIVE_KEY = /(?:authorization|cookie|password|secret|signature|token)/i;
+const SENSITIVE_KEY = /(?:api[_-]?key|authorization|cookie|hash[_-]?key|password|pseudonym(?:[_-]?key)?|secret|signature|token)/i;
export function createLogger(options: LoggerOptions = {}): Logger {
const write = options.write ?? ((line: string) => process.stdout.write(`${line}\n`));
@@ -50,6 +50,17 @@ export function redact(value: unknown, secrets: readonly string[] = [], key = ""
return value;
}
+export function sensitiveEnvironmentValues(environment: Record): string[] {
+ const values = new Set();
+ for (const [key, value] of Object.entries(environment)) {
+ if (!SENSITIVE_KEY.test(key) || !value) continue;
+ values.add(value);
+ const trimmed = value.trim();
+ if (trimmed) values.add(trimmed);
+ }
+ return [...values];
+}
+
function scrub(value: string, secrets: readonly string[]): string {
let result = value;
for (const secret of secrets) {
diff --git a/apps/collector/src/reconcile.test.ts b/apps/collector/src/reconcile.test.ts
index 198812f..7b31c50 100644
--- a/apps/collector/src/reconcile.test.ts
+++ b/apps/collector/src/reconcile.test.ts
@@ -9,7 +9,7 @@ function fakeRpc(pages: Array<{ events: Array; nextPageToken
getInfo: async () => ({ version: "test", numShards: 1, shardInfos: [{ shardId: 0, maxHeight: 1, blockDelay: 0, mempoolSize: 0 }] }),
getEvent: async () => ({}),
getEvents: async () => pages[index++] ?? { events: [] },
- subscribe: () => ({ cancel() {}, done: Promise.resolve() }),
+ subscribe: () => ({ cancel() {}, ready: Promise.resolve(), done: Promise.resolve() }),
close() {}
};
}
@@ -57,4 +57,50 @@ describe("GetEvents reconciliation", () => {
onEvent() {}
})).rejects.toThrow(/repeated a page token/);
});
+
+ it("reports durable progress after each completely processed page", async () => {
+ const progress: Array<{ pageCount: number; pageEventCount: number; eventCount: number; lastEventId: string }> = [];
+ const result = await reconcileEvents({
+ rpc: fakeRpc([
+ { events: [{ id: "1" }, { id: "2" }], nextPageToken: new Uint8Array([1]) },
+ { events: [{ id: "3" }] }
+ ]),
+ shard: 1,
+ startId: "0",
+ pageSize: 2,
+ onEvent() {},
+ onPageProgress: (page) => { progress.push(page); }
+ });
+
+ expect(result).toMatchObject({ pageCount: 2, eventCount: 3, lastEventId: "3" });
+ expect(progress).toEqual([
+ { pageCount: 1, pageEventCount: 2, eventCount: 2, lastEventId: "2" },
+ { pageCount: 2, pageEventCount: 1, eventCount: 3, lastEventId: "3" }
+ ]);
+ });
+
+ it("does not start another page after reconciliation is aborted", async () => {
+ const controller = new AbortController();
+ let calls = 0;
+ const rpc = fakeRpc([
+ { events: [{ id: "1" }, { id: "2" }], nextPageToken: new Uint8Array([1]) },
+ { events: [{ id: "3" }] }
+ ]);
+ const original = rpc.getEvents.bind(rpc);
+ rpc.getEvents = async (...args) => {
+ calls += 1;
+ return original(...args);
+ };
+
+ await expect(reconcileEvents({
+ rpc,
+ shard: 1,
+ startId: "0",
+ pageSize: 2,
+ signal: controller.signal,
+ onEvent() {},
+ onPageProgress: () => { controller.abort(); }
+ })).rejects.toMatchObject({ name: "AbortError" });
+ expect(calls).toBe(1);
+ });
});
diff --git a/apps/collector/src/reconcile.ts b/apps/collector/src/reconcile.ts
index fbeeda1..b362a3b 100644
--- a/apps/collector/src/reconcile.ts
+++ b/apps/collector/src/reconcile.ts
@@ -10,7 +10,16 @@ export interface ReconcileOptions {
stopId?: string;
pageSize?: number;
maxPages?: number;
+ signal?: AbortSignal;
onEvent(event: RawHubEvent): void;
+ onPageProgress?(progress: ReconcilePageProgress): void | Promise;
+}
+
+export interface ReconcilePageProgress {
+ pageCount: number;
+ pageEventCount: number;
+ eventCount: number;
+ lastEventId: string;
}
export interface ReconcileResult {
@@ -35,13 +44,16 @@ export async function reconcileEvents(options: ReconcileOptions): Promise();
while (pageCount < maxPages) {
- const response = await options.rpc.getEvents(options.shard, options.startId, token, options.stopId);
+ throwIfAborted(options.signal);
+ const response = await options.rpc.getEvents(options.shard, options.startId, token, options.stopId, options.signal);
+ throwIfAborted(options.signal);
pageCount += 1;
const rawEvents = Array.isArray(response.events) ? response.events : [];
if (rawEvents.length === 1 && rawEvents[0] === null) {
return { eventCount, pageCount, lastEventId, terminal: "null-sentinel" };
}
+ let pageEventCount = 0;
for (const event of rawEvents) {
if (!event) continue;
const eventId = rawEventId(event);
@@ -51,8 +63,11 @@ export async function reconcileEvents(options: ReconcileOptions): Promise= 0) continue;
options.onEvent(event);
eventCount += 1;
+ pageEventCount += 1;
lastEventId = maxEventId(lastEventId, eventId);
}
+ await options.onPageProgress?.({ pageCount, pageEventCount, eventCount, lastEventId });
+ throwIfAborted(options.signal);
if (options.stopId && compareEventIds(lastEventId, options.stopId) >= 0) {
return { eventCount, pageCount, lastEventId, terminal: "fixed-bound" };
@@ -74,6 +89,13 @@ export async function reconcileEvents(options: ReconcileOptions): Promise;
done: Promise;
}
export interface CollectorRpc {
- getInfo(): Promise;
- getEvent(shardIndex: number, id: string): Promise;
+ getInfo(signal?: AbortSignal): Promise;
+ getEvent(shardIndex: number, id: string, signal?: AbortSignal): Promise;
getEvents(
shardIndex: number,
startId: string,
pageToken?: Uint8Array,
- stopId?: string
+ stopId?: string,
+ signal?: AbortSignal
): Promise<{ events: Array; nextPageToken?: Uint8Array }>;
subscribe(
shardIndex: number,
- fromId: string,
+ fromId: string | undefined,
onEvent: (event: RawHubEvent) => void,
onError: (error: Error) => void
): RpcSubscription;
@@ -30,31 +32,32 @@ export const defaultRpcFactory: RpcFactory = (config) => new ProtocolRpcAdapter(
class ProtocolRpcAdapter implements CollectorRpc {
constructor(readonly client: SnapchainRpcClient) {}
- getInfo(): Promise {
- return this.client.getInfo();
+ getInfo(signal?: AbortSignal): Promise {
+ return this.client.getInfo(signal);
}
- getEvent(shardIndex: number, id: string): Promise {
- return this.client.getEvent(shardIndex, id);
+ getEvent(shardIndex: number, id: string, signal?: AbortSignal): Promise {
+ return this.client.getEvent(shardIndex, id, signal);
}
async getEvents(
shardIndex: number,
startId: string,
pageToken?: Uint8Array,
- stopId?: string
+ stopId?: string,
+ signal?: AbortSignal
): Promise<{ events: Array; nextPageToken?: Uint8Array }> {
- return this.client.getEvents(shardIndex, startId, pageToken, stopId);
+ return this.client.getEvents(shardIndex, startId, pageToken, stopId, signal);
}
subscribe(
shardIndex: number,
- fromId: string,
+ fromId: string | undefined,
onEvent: (event: RawHubEvent) => void,
onError: (error: Error) => void
): RpcSubscription {
const subscription = this.client.subscribe(shardIndex, fromId, onEvent, onError);
- return { cancel: subscription.cancel, done: subscription.done };
+ return { cancel: subscription.cancel, ready: subscription.ready, done: subscription.done };
}
close(): void {
diff --git a/apps/collector/vitest.config.ts b/apps/collector/vitest.config.ts
index dbb5274..aa7c4ae 100644
--- a/apps/collector/vitest.config.ts
+++ b/apps/collector/vitest.config.ts
@@ -3,6 +3,7 @@ import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
include: ["src/**/*.test.ts"],
- exclude: ["**/node_modules/**", "**/dist/**"]
+ exclude: ["**/node_modules/**", "**/dist/**"],
+ testTimeout: 20_000
}
});
diff --git a/apps/dashboard/e2e/dashboard.spec.ts b/apps/dashboard/e2e/dashboard.spec.ts
index 8f2fa9f..9a2b133 100644
--- a/apps/dashboard/e2e/dashboard.spec.ts
+++ b/apps/dashboard/e2e/dashboard.spec.ts
@@ -3,7 +3,13 @@ import { createDemoSummary } from "../src/data/demo";
async function mockLive(page: Page, statuses: [string, string] = ["live", "derived"]): Promise {
const summary = createDemoSummary();
+ const nowMs = Date.now();
summary.demo = false;
+ summary.generatedAtMs = nowMs;
+ summary.sources.snapchain.updatedAtMs = nowMs;
+ summary.sources.snapchain.lastCollectorAtMs = nowMs;
+ summary.sources.hypersnap.updatedAtMs = nowMs;
+ summary.sources.hypersnap.lastCollectorAtMs = nowMs;
summary.sources.snapchain.status = statuses[0] as typeof summary.sources.snapchain.status;
summary.sources.hypersnap.status = statuses[1] as typeof summary.sources.hypersnap.status;
await page.route("**/api/v1/summary", (route) => route.fulfill({ json: summary }));
@@ -85,7 +91,9 @@ test.describe("mobile portrait overview", () => {
});
await page.goto("/");
await expect(page.getByTestId("heartbeat-snapchain")).toHaveAttribute("data-pulse-id", "1");
- await expect(page.getByTestId("heartbeat-snapchain")).toContainText("24 qualifying events");
+ await expect(page.getByTestId("heartbeat-snapchain")).toContainText("24 qualifying actions");
+ await expect(page.locator(".panel-glow")).toHaveCount(0);
+ await expect(page.getByTestId("heartbeat-snapchain").locator(".heartbeat-bloom")).toHaveCount(1);
});
test("retains a trustworthy snapshot and signals browser offline", async ({ page, context }) => {
diff --git a/apps/dashboard/index.html b/apps/dashboard/index.html
index 76179c5..0cee144 100644
--- a/apps/dashboard/index.html
+++ b/apps/dashboard/index.html
@@ -5,6 +5,20 @@
+
+
+
+
+
SnapMeter — Live protocol activity
diff --git a/apps/dashboard/package.json b/apps/dashboard/package.json
index 0bf78fe..1cca6a0 100644
--- a/apps/dashboard/package.json
+++ b/apps/dashboard/package.json
@@ -4,16 +4,21 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vite build",
- "deploy": "pnpm build && wrangler deploy",
+ "build": "pnpm verify:miniapp && vite build && node scripts/generate-third-party-licenses.mjs && pnpm verify:bundle",
+ "deploy": "pnpm verify:miniapp:release && pnpm build && wrangler deploy",
"dev": "vite",
"preview": "vite preview",
"test": "vitest run --config vitest.ui.config.ts",
"test:worker": "vitest run --config vitest.worker.config.ts --max-workers=1 --no-isolate",
"test:e2e": "playwright test --config playwright.config.ts",
- "typecheck": "tsc --noEmit"
+ "typecheck": "tsc --noEmit",
+ "verify:bundle": "node scripts/verify-client-bundle.mjs",
+ "verify:miniapp": "node scripts/verify-miniapp.mjs",
+ "verify:miniapp:release": "node scripts/verify-miniapp.mjs --require-association"
},
"dependencies": {
+ "@farcaster/miniapp-sdk": "0.3.0",
+ "@farcaster/quick-auth": "0.0.8",
"@snapmeter/contracts": "workspace:*",
"react": "19.2.8",
"react-dom": "19.2.8",
@@ -23,6 +28,7 @@
"@cloudflare/vite-plugin": "1.52.0",
"@cloudflare/vitest-pool-workers": "0.21.2",
"@cloudflare/workers-types": "5.20260813.1",
+ "@farcaster/miniapp-core": "0.6.0",
"@playwright/test": "1.62.1",
"@testing-library/dom": "10.4.1",
"@testing-library/jest-dom": "6.8.0",
@@ -33,6 +39,7 @@
"@vitejs/plugin-react": "6.0.5",
"jsdom": "26.1.0",
"typescript": "5.9.3",
+ "viem": "2.55.0",
"vite": "8.2.1",
"vitest": "4.1.10",
"wrangler": "4.122.0"
diff --git a/apps/dashboard/playwright.config.ts b/apps/dashboard/playwright.config.ts
index 2dd64c1..c226037 100644
--- a/apps/dashboard/playwright.config.ts
+++ b/apps/dashboard/playwright.config.ts
@@ -1,5 +1,11 @@
import { defineConfig, devices } from "@playwright/test";
+const e2ePort = process.env.SNAPMETER_E2E_PORT ?? "4173";
+if (!/^\d{4,5}$/.test(e2ePort) || Number(e2ePort) < 1_024 || Number(e2ePort) > 65_535) {
+ throw new Error("SNAPMETER_E2E_PORT must be a valid unprivileged TCP port");
+}
+const e2eBaseUrl = `http://127.0.0.1:${e2ePort}`;
+
export default defineConfig({
testDir: "./e2e",
fullyParallel: false,
@@ -8,15 +14,15 @@ export default defineConfig({
retries: process.env.CI ? 2 : 0,
reporter: process.env.CI ? "github" : "list",
use: {
- baseURL: "http://127.0.0.1:4173",
+ baseURL: e2eBaseUrl,
trace: "retain-on-failure"
},
projects: [
{ name: "chromium", use: { ...devices["Desktop Chrome"] } }
],
webServer: {
- command: "pnpm dev --host 127.0.0.1 --port 4173",
- url: "http://127.0.0.1:4173",
+ command: `pnpm dev --host 127.0.0.1 --port ${e2ePort}`,
+ url: e2eBaseUrl,
reuseExistingServer: false,
timeout: 120_000,
env: {
diff --git a/apps/dashboard/public/.well-known/farcaster.json b/apps/dashboard/public/.well-known/farcaster.json
new file mode 100644
index 0000000..d2543a9
--- /dev/null
+++ b/apps/dashboard/public/.well-known/farcaster.json
@@ -0,0 +1,35 @@
+{
+ "accountAssociation": {
+ "header": "eyJmaWQiOjUzOTg1NCwidHlwZSI6ImN1c3RvZHkiLCJrZXkiOiIweDdhOUU2OTY1RkNGMWFkMmNmYmZmNjdmMEMwYUExMDJGMERFYTIzZDQifQ",
+ "payload": "eyJkb21haW4iOiJzbmFwbWV0ZXIuYWVsLWRldjMud29ya2Vycy5kZXYifQ",
+ "signature": "5Gr9lK04ezDIgFvk6SSuBMFeJLQW/ZhKglNMXAFqjegpD30Jg/yzb62XSOkvSv7JrTVIV0UnpxBmtD2auuWJ3Bs="
+ },
+ "miniapp": {
+ "version": "1",
+ "name": "SnapMeter",
+ "homeUrl": "https://snapmeter.ael-dev3.workers.dev/?miniApp=true",
+ "iconUrl": "https://snapmeter.ael-dev3.workers.dev/images/miniapp/icon.png",
+ "splashImageUrl": "https://snapmeter.ael-dev3.workers.dev/images/miniapp/splash.png",
+ "splashBackgroundColor": "#07090C",
+ "subtitle": "Live Farcaster activity",
+ "description": "Compare live activity across Snapchain and Hypersnap with transparent source health and rolling Farcaster metrics.",
+ "screenshotUrls": [
+ "https://snapmeter.ael-dev3.workers.dev/images/miniapp/screenshot.png"
+ ],
+ "primaryCategory": "developer-tools",
+ "tags": [
+ "farcaster",
+ "snapchain",
+ "hypersnap",
+ "analytics",
+ "metrics"
+ ],
+ "heroImageUrl": "https://snapmeter.ael-dev3.workers.dev/images/miniapp/hero.png",
+ "tagline": "Watch the network breathe",
+ "ogTitle": "SnapMeter",
+ "ogDescription": "Live Snapchain and Hypersnap activity with transparent source health.",
+ "ogImageUrl": "https://snapmeter.ael-dev3.workers.dev/images/miniapp/og.png",
+ "noindex": false,
+ "canonicalDomain": "snapmeter.ael-dev3.workers.dev"
+ }
+}
diff --git a/apps/dashboard/public/_headers b/apps/dashboard/public/_headers
index 779cc98..ada78f5 100644
--- a/apps/dashboard/public/_headers
+++ b/apps/dashboard/public/_headers
@@ -2,8 +2,14 @@
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=()
- Cross-Origin-Opener-Policy: same-origin
- Content-Security-Policy: default-src 'self'; connect-src 'self' ws: wss:; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; font-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'
+ Content-Security-Policy: default-src 'self'; connect-src 'self' https://auth.farcaster.xyz ws: wss:; img-src 'self' data:; style-src 'self'; style-src-elem 'self'; style-src-attr 'unsafe-inline'; script-src 'self'; font-src 'self'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'self'; worker-src 'self'; manifest-src 'self'
+
+/.well-known/farcaster.json
+ Cache-Control: no-cache
+ Content-Type: application/json; charset=utf-8
+
+/images/miniapp/*
+ Cache-Control: public, max-age=86400
/api/*
Cache-Control: no-store
diff --git a/apps/dashboard/public/images/miniapp/embed.png b/apps/dashboard/public/images/miniapp/embed.png
new file mode 100644
index 0000000..aff95fc
Binary files /dev/null and b/apps/dashboard/public/images/miniapp/embed.png differ
diff --git a/apps/dashboard/public/images/miniapp/hero.png b/apps/dashboard/public/images/miniapp/hero.png
new file mode 100644
index 0000000..9b1782f
Binary files /dev/null and b/apps/dashboard/public/images/miniapp/hero.png differ
diff --git a/apps/dashboard/public/images/miniapp/icon.png b/apps/dashboard/public/images/miniapp/icon.png
new file mode 100644
index 0000000..bbc304e
Binary files /dev/null and b/apps/dashboard/public/images/miniapp/icon.png differ
diff --git a/apps/dashboard/public/images/miniapp/og.png b/apps/dashboard/public/images/miniapp/og.png
new file mode 100644
index 0000000..9b1782f
Binary files /dev/null and b/apps/dashboard/public/images/miniapp/og.png differ
diff --git a/apps/dashboard/public/images/miniapp/screenshot.png b/apps/dashboard/public/images/miniapp/screenshot.png
new file mode 100644
index 0000000..9d8471d
Binary files /dev/null and b/apps/dashboard/public/images/miniapp/screenshot.png differ
diff --git a/apps/dashboard/public/images/miniapp/splash.png b/apps/dashboard/public/images/miniapp/splash.png
new file mode 100644
index 0000000..25ca576
Binary files /dev/null and b/apps/dashboard/public/images/miniapp/splash.png differ
diff --git a/apps/dashboard/scripts/generate-third-party-licenses.mjs b/apps/dashboard/scripts/generate-third-party-licenses.mjs
new file mode 100644
index 0000000..79851ee
--- /dev/null
+++ b/apps/dashboard/scripts/generate-third-party-licenses.mjs
@@ -0,0 +1,145 @@
+import { readFileSync, rmSync, writeFileSync } from "node:fs";
+import { join, relative, resolve } from "node:path";
+import process from "node:process";
+
+export const NOTICE_FILE_NAME = "THIRD_PARTY_LICENSES.txt";
+export const ENVIRONMENT_NOTICE_PATH = join(".vite", "third-party-licenses.md");
+
+const dashboardRoot = resolve(import.meta.dirname, "..");
+const distRoot = join(dashboardRoot, "dist");
+const generatedDevVarsPath = join(distRoot, "snapmeter", ".dev.vars");
+const APACHE_ATTRIBUTIONS = new Map([
+ ["comlink", "Copyright 2019 Google LLC"]
+]);
+const REVIEWED_MISSING_LICENSE_TEXTS = new Map([
+ // @farcaster/quick-auth 0.0.8 declares MIT but its published `files` list
+ // omits LICENSE. This is the MIT text and Farcaster notice reviewed at the
+ // package's upstream 0.0.8 version-bump commit.
+ ["@farcaster/quick-auth", [
+ "Upstream notice source: https://github.com/farcasterxyz/quick-auth/blob/79e064d75c3d03ca797401d49e8e8cc33a3bdfc9/hono-cloudflare-worker/LICENSE",
+ "",
+ "MIT License",
+ "",
+ "Copyright (c) 2025 Farcaster",
+ "",
+ "Permission is hereby granted, free of charge, to any person obtaining a copy",
+ "of this software and associated documentation files (the \"Software\"), to deal",
+ "in the Software without restriction, including without limitation the rights",
+ "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
+ "copies of the Software, and to permit persons to whom the Software is",
+ "furnished to do so, subject to the following conditions:",
+ "",
+ "The above copyright notice and this permission notice shall be included in all",
+ "copies or substantial portions of the Software.",
+ "",
+ "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
+ "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
+ "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
+ "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
+ "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
+ "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
+ "SOFTWARE."
+ ].join("\n")]
+]);
+
+function normalized(value) {
+ return value.replaceAll("\r\n", "\n").trim();
+}
+
+function withRequiredAttributions(source) {
+ const completed = source.replace(
+ /^(## ([^\s]+) - [^\n]+\(([^)]+)\)\n)\n(?=## |$)/gmu,
+ (_match, heading, packageName, license) => {
+ const reviewedText = REVIEWED_MISSING_LICENSE_TEXTS.get(packageName);
+ if (license !== "MIT" || !reviewedText) {
+ throw new Error(`${packageName} (${license}) has no bundled license text and requires review`);
+ }
+ return `${heading}\n${reviewedText}\n\n`;
+ }
+ );
+ const attributed = completed.replace(
+ /^(## ([^\s]+) - [^\n]+\(Apache-2\.0\)\n)/gmu,
+ (_match, heading, packageName) => {
+ const attribution = APACHE_ATTRIBUTIONS.get(packageName);
+ if (!attribution) {
+ throw new Error(`Apache-2.0 dependency ${packageName} requires a reviewed attribution rule`);
+ }
+ return `${heading}\n${attribution}\n`;
+ }
+ );
+ const emptyLicenseEntry = attributed.match(
+ /^## ([^\s]+) - [^\n]+\(([^)]+)\)\n\n(?=## |$)/mu
+ );
+ if (emptyLicenseEntry) {
+ throw new Error(`${emptyLicenseEntry[1]} (${emptyLicenseEntry[2]}) has no bundled license text and requires review`);
+ }
+ return attributed;
+}
+
+function readEnvironmentNotice(environment) {
+ const path = join(distRoot, environment, ENVIRONMENT_NOTICE_PATH);
+ let source;
+ try {
+ source = readFileSync(path, "utf8");
+ } catch {
+ throw new Error(`missing Vite license inventory: ${relative(dashboardRoot, path)}`);
+ }
+ const content = normalized(source);
+ if (!content.startsWith("# Licenses\n")) {
+ throw new Error(`invalid Vite license inventory: ${relative(dashboardRoot, path)}`);
+ }
+ return withRequiredAttributions(content);
+}
+
+export function expectedThirdPartyNotice() {
+ const client = readEnvironmentNotice("client");
+ const worker = readEnvironmentNotice("snapmeter");
+ return [
+ "SnapMeter third-party redistribution notices",
+ "============================================",
+ "",
+ "This file is generated from the exact production modules bundled by Vite.",
+ "It covers both the public browser assets and the Cloudflare Worker bundle.",
+ "The source release and its separately vendored protocol notices are documented",
+ "in the repository root THIRD_PARTY_NOTICES.md.",
+ "",
+ "Browser bundle",
+ "--------------",
+ "",
+ client,
+ "",
+ "Cloudflare Worker bundle",
+ "------------------------",
+ "",
+ worker,
+ ""
+ ].join("\n");
+}
+
+export function writeThirdPartyNotice() {
+ try {
+ const notice = expectedThirdPartyNotice();
+ const clientPath = join(distRoot, "client", NOTICE_FILE_NAME);
+ const workerPath = join(distRoot, "snapmeter", NOTICE_FILE_NAME);
+ writeFileSync(clientPath, notice, "utf8");
+ writeFileSync(workerPath, notice, "utf8");
+ return { clientPath, workerPath };
+ } finally {
+ // Cloudflare's Vite build may materialize process.env secrets for local
+ // preview. It is not a deployment input and must not survive either a
+ // successful build or a failed notice-generation/review step.
+ rmSync(generatedDevVarsPath, { force: true });
+ }
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === resolve(import.meta.filename)) {
+ try {
+ const paths = writeThirdPartyNotice();
+ process.stdout.write(
+ `Third-party license notice generated for ${relative(dashboardRoot, paths.clientPath)} and ${relative(dashboardRoot, paths.workerPath)}.\n`
+ );
+ } catch (error) {
+ process.stderr.write(`Third-party license generation failed: ${error instanceof Error ? error.message : String(error)}\n`);
+ process.exitCode = 1;
+ }
+}
diff --git a/apps/dashboard/scripts/verify-client-bundle.mjs b/apps/dashboard/scripts/verify-client-bundle.mjs
new file mode 100644
index 0000000..675e855
--- /dev/null
+++ b/apps/dashboard/scripts/verify-client-bundle.mjs
@@ -0,0 +1,104 @@
+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
+import { join, relative, resolve } from "node:path";
+import process from "node:process";
+import {
+ expectedThirdPartyNotice,
+ NOTICE_FILE_NAME
+} from "./generate-third-party-licenses.mjs";
+
+const root = resolve(import.meta.dirname, "..");
+const clientRoot = join(root, "dist", "client");
+const workerRoot = join(root, "dist", "snapmeter");
+const forbidden = [
+ ["server-only ingest secret name", "SNAPMETER_INGEST_SECRET"],
+ ["server-only Snapchain credential name", "SNAPCHAIN_GRPC_API_KEY"],
+ ["server-only Hypersnap credential name", "HYPERSNAP_GRPC_API_KEY"],
+ ["Cloudflare deployment credential name", "CLOUDFLARE_API_TOKEN"],
+ ["unused LGPL RPC package", "rpc-websockets"],
+ ["unused RPC client implementation", "generate_request_id"],
+ ["unused Solana wallet implementation", "SolanaConnection"]
+];
+const forbiddenNoticeInventory = [
+ "rpc-websockets",
+ "text-encoding-utf-8",
+ "@solana/web3.js"
+];
+
+function files(directory) {
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
+ const path = join(directory, entry.name);
+ return entry.isDirectory() ? files(path) : [path];
+ });
+}
+
+const violations = [];
+const generatedDevVars = join(workerRoot, ".dev.vars");
+if (existsSync(generatedDevVars)) {
+ violations.push(`${relative(root, generatedDevVars)} must not survive a production build`);
+}
+for (const path of files(clientRoot)) {
+ const stats = statSync(path);
+ if (stats.size > 5 * 1024 * 1024) {
+ violations.push(`${relative(clientRoot, path)} exceeds the 5 MiB review limit`);
+ continue;
+ }
+ if (!/\.(?:html|js|json|mjs|css)$/u.test(path)) continue;
+ const content = readFileSync(path, "utf8");
+ for (const [label, marker] of forbidden) {
+ if (content.includes(marker)) violations.push(`${relative(clientRoot, path)} contains ${label}`);
+ }
+}
+
+let expectedNotice;
+try {
+ expectedNotice = expectedThirdPartyNotice();
+} catch (error) {
+ violations.push(error instanceof Error ? error.message : String(error));
+}
+
+if (expectedNotice !== undefined) {
+ for (const outputRoot of [clientRoot, workerRoot]) {
+ const noticePath = join(outputRoot, NOTICE_FILE_NAME);
+ let actualNotice;
+ try {
+ actualNotice = readFileSync(noticePath, "utf8");
+ } catch {
+ violations.push(`${relative(root, noticePath)} is missing`);
+ continue;
+ }
+ if (actualNotice !== expectedNotice) {
+ violations.push(`${relative(root, noticePath)} is stale or incomplete`);
+ }
+ }
+
+ const requiredInventory = [
+ "## @farcaster/miniapp-sdk - 0.3.0 (MIT)",
+ "## @farcaster/quick-auth - 0.0.8 (MIT)",
+ "## comlink - 4.4.2 (Apache-2.0)",
+ "## jose - 5.10.0 (MIT)",
+ "## react-dom - 19.2.8 (MIT)",
+ "## react - 19.2.8 (MIT)",
+ "## scheduler - 0.27.0 (MIT)",
+ "## zod - 4.4.3 (MIT)",
+ "Copyright 2019 Google LLC",
+ "Copyright (c) 2025 Farcaster"
+ ];
+ for (const marker of requiredInventory) {
+ if (!expectedNotice.includes(marker)) {
+ violations.push(`${NOTICE_FILE_NAME} is missing required notice marker: ${marker}`);
+ }
+ }
+ for (const marker of forbiddenNoticeInventory) {
+ if (expectedNotice.includes(`## ${marker} -`)) {
+ violations.push(`${NOTICE_FILE_NAME} unexpectedly includes unused dependency: ${marker}`);
+ }
+ }
+}
+
+if (violations.length > 0) {
+ process.stderr.write("Client bundle safety check failed:\n");
+ for (const violation of violations) process.stderr.write(`- ${violation}\n`);
+ process.exitCode = 1;
+} else {
+ process.stdout.write("Bundle safety check passed: no server credentials or unused wallet/RPC stack detected, and browser/Worker redistribution notices are current.\n");
+}
diff --git a/apps/dashboard/scripts/verify-miniapp.mjs b/apps/dashboard/scripts/verify-miniapp.mjs
new file mode 100644
index 0000000..16094ba
--- /dev/null
+++ b/apps/dashboard/scripts/verify-miniapp.mjs
@@ -0,0 +1,215 @@
+import { Buffer } from 'node:buffer'
+import { readFile } from 'node:fs/promises'
+import { dirname, join } from 'node:path'
+import process from 'node:process'
+import { fileURLToPath, URL } from 'node:url'
+import { TextDecoder } from 'node:util'
+import {
+ domainManifestSchema,
+ domainMiniAppConfigSchema,
+ miniAppEmbedNextSchema,
+} from '@farcaster/miniapp-core'
+import { verifyMessage } from 'viem'
+
+const APP_ORIGIN = 'https://snapmeter.ael-dev3.workers.dev'
+const APP_DOMAIN = 'snapmeter.ael-dev3.workers.dev'
+const LAUNCH_URL = `${APP_ORIGIN}/?miniApp=true`
+const requireAssociation = process.argv.includes('--require-association')
+const dashboardDir = join(dirname(fileURLToPath(import.meta.url)), '..')
+const publicDir = join(dashboardDir, 'public')
+const manifestPath = join(publicDir, '.well-known', 'farcaster.json')
+const htmlPath = join(dashboardDir, 'index.html')
+const headersPath = join(publicDir, '_headers')
+
+const expectedAssets = new Map([
+ [`${APP_ORIGIN}/images/miniapp/icon.png`, { width: 1024, height: 1024 }],
+ [`${APP_ORIGIN}/images/miniapp/splash.png`, { width: 200, height: 200 }],
+ [`${APP_ORIGIN}/images/miniapp/embed.png`, { width: 1200, height: 800 }],
+ [`${APP_ORIGIN}/images/miniapp/hero.png`, { width: 1200, height: 630 }],
+ [`${APP_ORIGIN}/images/miniapp/og.png`, { width: 1200, height: 630 }],
+ [`${APP_ORIGIN}/images/miniapp/screenshot.png`, { width: 1284, height: 2778 }],
+])
+
+function fail(message) {
+ throw new Error(`Mini App validation failed: ${message}`)
+}
+
+function assert(condition, message) {
+ if (!condition) fail(message)
+}
+
+function formatIssues(error) {
+ return error.issues
+ .map((issue) => `${issue.path.join('.') || ''}: ${issue.message}`)
+ .join('; ')
+}
+
+function exactObjectKeys(value, expected) {
+ return value !== null
+ && typeof value === 'object'
+ && !Array.isArray(value)
+ && Object.keys(value).sort().join('\0') === [...expected].sort().join('\0')
+}
+
+function decodeCanonicalBase64Url(value, label) {
+ assert(
+ typeof value === 'string' && value.length > 0 && /^[A-Za-z0-9_-]+$/.test(value),
+ `${label} must be canonical unpadded base64url`,
+ )
+ const bytes = Buffer.from(value, 'base64url')
+ assert(bytes.length > 0 && bytes.toString('base64url') === value, `${label} must be canonical unpadded base64url`)
+ return bytes
+}
+
+function decodeBase64UrlJson(value, label) {
+ try {
+ const bytes = decodeCanonicalBase64Url(value, label)
+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))
+ } catch {
+ fail(`${label} must contain base64url-encoded JSON`)
+ }
+}
+
+function decodeSignature(value) {
+ assert(typeof value === 'string' && value.length > 0, 'association signature must not be empty')
+ let bytes
+ if (/^[A-Za-z0-9_-]+$/.test(value)) {
+ bytes = Buffer.from(value, 'base64url')
+ assert(bytes.toString('base64url') === value, 'association signature is not canonical base64url')
+ }
+ else {
+ assert(
+ /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value),
+ 'association signature must be canonical base64url or padded base64',
+ )
+ bytes = Buffer.from(value, 'base64')
+ assert(bytes.toString('base64') === value, 'association signature is not canonical padded base64')
+ }
+ const legacyHex = bytes.toString('utf8')
+ if (/^0x[0-9a-fA-F]{130}$/.test(legacyHex)) bytes = Buffer.from(legacyHex.slice(2), 'hex')
+ assert(bytes.length === 65, 'association signature must contain a 65-byte ERC-191 signature')
+ return `0x${bytes.toString('hex')}`
+}
+
+export async function validateAccountAssociation(accountAssociation, miniapp, expectedDomain) {
+ assert(accountAssociation, 'accountAssociation is required for a release')
+
+ const candidate = {
+ accountAssociation,
+ miniapp,
+ }
+ const parsed = domainManifestSchema.safeParse(candidate)
+ if (!parsed.success) {
+ fail(`accountAssociation does not pass the official schema: ${formatIssues(parsed.error)}`)
+ }
+
+ const header = decodeBase64UrlJson(accountAssociation.header, 'accountAssociation.header')
+ const payload = decodeBase64UrlJson(accountAssociation.payload, 'accountAssociation.payload')
+ assert(exactObjectKeys(header, ['fid', 'type', 'key']), 'association header must contain only fid, type, and key')
+ assert(Number.isSafeInteger(header.fid) && header.fid > 0, 'association header must contain a positive integer fid')
+ assert(header.type === 'custody' || header.type === 'auth', 'association header type must be custody or auth')
+ assert(typeof header.key === 'string' && /^0x[0-9a-fA-F]{40}$/.test(header.key), 'association header must contain an Ethereum address')
+ assert(payload.domain === expectedDomain, `association payload domain must be exactly ${expectedDomain}`)
+ assert(exactObjectKeys(payload, ['domain']), 'association payload must contain only the domain field')
+
+ const signature = decodeSignature(accountAssociation.signature)
+ let verified
+ try {
+ verified = await verifyMessage({
+ address: header.key,
+ message: `${accountAssociation.header}.${accountAssociation.payload}`,
+ signature,
+ })
+ }
+ catch {
+ verified = false
+ }
+ assert(verified, 'association signature does not match its declared signing key')
+
+ return { header, payload }
+}
+
+async function readPngMetadata(filePath) {
+ const bytes = await readFile(filePath)
+ const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])
+ assert(bytes.subarray(0, 8).equals(signature), `${filePath} is not a PNG`)
+ assert(bytes.toString('ascii', 12, 16) === 'IHDR', `${filePath} has no PNG IHDR`)
+ const colorType = bytes[25]
+ return {
+ width: bytes.readUInt32BE(16),
+ height: bytes.readUInt32BE(20),
+ hasAlpha: colorType === 4 || colorType === 6,
+ }
+}
+
+const manifest = JSON.parse(await readFile(manifestPath, 'utf8'))
+assert(manifest.miniapp, 'manifest must use the modern miniapp property')
+assert(!('frame' in manifest), 'manifest must not include the legacy frame property')
+
+const configResult = domainMiniAppConfigSchema.safeParse(manifest.miniapp)
+if (!configResult.success) {
+ fail(`miniapp config does not pass the official schema: ${formatIssues(configResult.error)}`)
+}
+const config = configResult.data
+
+assert(config.version === '1', 'manifest version must be 1')
+assert(config.name === 'SnapMeter', 'manifest app name must be SnapMeter')
+assert(config.homeUrl === LAUNCH_URL, `manifest homeUrl must be ${LAUNCH_URL}`)
+assert(config.canonicalDomain === APP_DOMAIN, `canonicalDomain must be ${APP_DOMAIN}`)
+assert(typeof config.description === 'string' && config.description.length > 0, 'description is required for discovery')
+assert(config.noindex !== true, 'noindex must not disable discovery')
+assert(!('imageUrl' in config), 'deprecated manifest imageUrl must not be used')
+assert(!('buttonTitle' in config), 'deprecated manifest buttonTitle must not be used')
+
+if (manifest.accountAssociation) {
+ await validateAccountAssociation(manifest.accountAssociation, manifest.miniapp, APP_DOMAIN)
+}
+else if (requireAssociation) fail('accountAssociation is required for a release')
+
+const html = await readFile(htmlPath, 'utf8')
+assert(!/name=["']fc:frame["']/i.test(html), 'legacy fc:frame metadata must not be present')
+const metaMatch = html.match(//i)
+assert(metaMatch, 'index.html must contain a static fc:miniapp meta tag')
+const embed = JSON.parse(metaMatch[1])
+const embedResult = miniAppEmbedNextSchema.safeParse(embed)
+if (!embedResult.success) {
+ fail(`fc:miniapp embed does not pass the official schema: ${formatIssues(embedResult.error)}`)
+}
+assert(embed.version === '1', 'embed version must be 1')
+assert(embed.imageUrl === `${APP_ORIGIN}/images/miniapp/embed.png`, 'embed must use the canonical 3:2 image')
+assert(embed.button.action.type === 'launch_miniapp', 'embed must use launch_miniapp')
+assert(embed.button.action.url === LAUNCH_URL, `embed action URL must be ${LAUNCH_URL}`)
+assert(embed.button.action.name === 'SnapMeter', 'embed action name must be SnapMeter')
+
+const referencedAssets = new Set([
+ config.iconUrl,
+ config.splashImageUrl,
+ config.heroImageUrl,
+ config.ogImageUrl,
+ ...(config.screenshotUrls ?? []),
+ embed.imageUrl,
+ embed.button.action.splashImageUrl,
+])
+assert(referencedAssets.size === expectedAssets.size, 'manifest and embed must reference every release asset exactly once by URL')
+
+for (const [url, expected] of expectedAssets) {
+ assert(referencedAssets.has(url), `release metadata does not reference ${url}`)
+ const relativePath = new URL(url).pathname.replace(/^\//, '')
+ const actual = await readPngMetadata(join(publicDir, ...relativePath.split('/')))
+ assert(actual.width === expected.width && actual.height === expected.height, `${relativePath} must be ${expected.width}x${expected.height}, got ${actual.width}x${actual.height}`)
+ assert(!actual.hasAlpha, `${relativePath} must be opaque (RGB PNG, no alpha channel)`)
+}
+
+const headers = await readFile(headersPath, 'utf8')
+assert(!/Cross-Origin-Opener-Policy/i.test(headers), 'COOP must be omitted so the Farcaster host can embed the app')
+assert(!/frame-ancestors\s+'none'/i.test(headers), "CSP must not set frame-ancestors 'none'")
+assert(/connect-src[^;\r\n]*https:\/\/auth\.farcaster\.xyz/i.test(headers), 'CSP connect-src must allow auth.farcaster.xyz')
+assert(/style-src\s+'self'(?:;|\s)/i.test(headers), "CSP style-src must not allow inline style elements")
+assert(/style-src-elem\s+'self'/i.test(headers), "CSP style-src-elem must allow only bundled same-origin styles")
+assert(/style-src-attr\s+'unsafe-inline'/i.test(headers), "CSP style-src-attr must explicitly cover bounded React style attributes")
+assert(/frame-src\s+'none'/i.test(headers), "CSP must set frame-src 'none'")
+assert(/object-src\s+'none'/i.test(headers), "CSP must set object-src 'none'")
+
+process.stdout.write(
+ `Mini App metadata valid for ${APP_DOMAIN}${requireAssociation ? ' with account association' : manifest.accountAssociation ? ' (association present)' : ' (unsigned development manifest)'}.\n`,
+)
diff --git a/apps/dashboard/src/App.test.tsx b/apps/dashboard/src/App.test.tsx
index 8f1d25e..c6133c0 100644
--- a/apps/dashboard/src/App.test.tsx
+++ b/apps/dashboard/src/App.test.tsx
@@ -1,8 +1,10 @@
// @vitest-environment jsdom
-import { fireEvent, render, screen } from "@testing-library/react";
+import { fireEvent, render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import App from "./App";
+import { Analytics } from "./components/Analytics";
+import { createDemoSummary } from "./data/demo";
describe("SnapMeter dashboard", () => {
beforeEach(() => {
@@ -22,13 +24,21 @@ describe("SnapMeter dashboard", () => {
expect(screen.getByTestId("panel-snapchain")).toHaveTextContent("58,429");
expect(screen.getByTestId("panel-hypersnap")).toHaveTextContent("55,927");
expect(screen.getByTestId("panel-hypersnap")).toHaveTextContent("Derived");
+ expect(within(screen.getByTestId("panel-snapchain")).getByLabelText("SnapMeter Snapchain")).toHaveTextContent("SNAPMETER");
+ expect(within(screen.getByTestId("panel-hypersnap")).getByLabelText("SnapMeter Hypersnap")).toHaveTextContent("SNAPMETER");
+ expect(within(screen.getByTestId("panel-snapchain")).getByText("Rolling 24h DAU")).toBeVisible();
+ expect(within(screen.getByTestId("panel-hypersnap")).getByText("Observed rolling 24h DAU")).toBeVisible();
+ expect(screen.getAllByText(/unique active fids · shared utc window/i)).toHaveLength(2);
+ expect(screen.getByText(/shared rolling 24h · both sources · ending/i)).toBeInTheDocument();
+ expect(screen.getByText(/shared dau timeframe · both sources/i)).toBeInTheDocument();
expect(fetch).not.toHaveBeenCalled();
});
it("keeps demo heartbeats idle until a validated live pulse exists", () => {
render();
expect(screen.getByTestId("heartbeat-snapchain")).toHaveAttribute("data-pulse-id", "0");
- expect(screen.getAllByText("No live pulse received in this session")).toHaveLength(2);
+ expect(screen.getAllByText(/Last recorded action .* awaiting a live pulse/)).toHaveLength(2);
+ expect(screen.queryByText(/Last action · heartbeat/i)).not.toBeInTheDocument();
});
it("supports range selection and keyboard inspection of exact chart samples", async () => {
@@ -44,4 +54,12 @@ describe("SnapMeter dashboard", () => {
expect(screen.getAllByText("Snapchain").length).toBeGreaterThan(1);
expect(screen.getByTestId("comparison-chart").querySelector(".chart-tooltip")).toHaveAttribute("data-visible");
});
+
+ it("withholds action-mix comparison when source windows differ", () => {
+ const summary = createDemoSummary();
+ summary.sources.hypersnap.updatedAtMs += 1;
+ render();
+ expect(screen.getByText(/source windows end at different times/i)).toBeVisible();
+ expect(screen.queryByRole("group", { name: /qualifying action mix.*shared rolling 24 hour/i })).not.toBeInTheDocument();
+ });
});
diff --git a/apps/dashboard/src/App.tsx b/apps/dashboard/src/App.tsx
index 5496be2..7d088e8 100644
--- a/apps/dashboard/src/App.tsx
+++ b/apps/dashboard/src/App.tsx
@@ -1,5 +1,6 @@
import { Analytics } from "./components/Analytics";
import { ProtocolPanel } from "./components/ProtocolPanel";
+import { MiniAppProvider } from "./farcaster";
import { useLiveMetrics } from "./hooks/useLiveMetrics";
function TransportNotice({
@@ -26,7 +27,7 @@ function TransportNotice({
);
}
-export default function App(): React.JSX.Element {
+function Dashboard(): React.JSX.Element {
const { summary, transport, pulses, error, now, retry, demo } = useLiveMetrics();
return (
<>
@@ -69,3 +70,11 @@ export default function App(): React.JSX.Element {
>
);
}
+
+export default function App(): React.JSX.Element {
+ return (
+
+
+
+ );
+}
diff --git a/apps/dashboard/src/components/ActionMix.tsx b/apps/dashboard/src/components/ActionMix.tsx
index fcbef2f..3871a3f 100644
--- a/apps/dashboard/src/components/ActionMix.tsx
+++ b/apps/dashboard/src/components/ActionMix.tsx
@@ -6,7 +6,7 @@ const FAMILIES: ActionFamily[] = ["cast", "reaction", "link", "verification", "u
export function ActionMix({ snapchain, hypersnap }: { snapchain: SourceMetrics; hypersnap: SourceMetrics }): React.JSX.Element {
const maximum = Math.max(1, ...FAMILIES.flatMap((family) => [snapchain.actionCounts[family] ?? 0, hypersnap.actionCounts[family] ?? 0]));
return (
-