page-usage-board: a usage dashboard page (#844)

Adds @magpie-community/page-usage-board: a usage dashboard page with its
own zero-dependency local service (quota cards with expiry tiers, TTFT,
7x24 heatmap, optional remote attribution).

Reviewed at 8ca2562: the author's 80137b0 plus a maintainer merge of main
(registry entry re-appended after upstream's newer packages).
Since the 6b2625d review: [::1] in MAGPIE_ADDR stays IPv6 loopback (only
0.0.0.0/[::] map to 127.0.0.1), the config-dir test compares real paths
so it passes on macOS, and the registry-block test tolerates CRLF.

Run on mote at 8ca2562: packages/page-usage-board `bun test` 36 pass,
`node --test test/*.test.mjs` 36 pass; `bun scripts/check.mjs` all ok.
Not tried this round: the page in a live magpie window.
This commit is contained in:
orinsid
2026-11-10 10:36:04 +08:00
committed by GitHub
parent e9c7de3708
commit 545ed66e74
23 changed files with 4727 additions and 1 deletions
+1
View File
@@ -185,6 +185,7 @@ These add a page to magpie's window, in the app and in `magpie web`, under Plugi
| [nowledge-mem](packages/nowledge-mem) | Connection settings, recall and capture switches, a real connection test, and the scope of what is sent | None |
| [agent-office](packages/agent-office) | What are my agents doing: a real WebGL 3D office with six scenes, an isometric/2D office, grouped workbench, Today usage and recent conversations | no `magpie.read`; its host part reads local session files of Claude Code, Codex, Copilot CLI, Kimi Code, dsh, Gemini CLI, Qwen Code, Pi, omp, Qoder, WorkBuddy, CodeBuddy and Grok Build, including prompts, replies and tool commands (`text:false` keeps statuses and tool names only) |
| [page-usage-tree](packages/page-usage-tree) | Account usage: usage as provider -> account -> model, each level expandable, with per-account calls, errors and cost; adds the account layer Usage glance's `usage:summary` does not contain | none (its local service calls Magpie's local usage API) |
| [page-usage-board](packages/page-usage-board) | Full usage board: quota cards with expiry tiers, daily/per-provider charts, 24h cache-hit and token curves, optional remote attribution and account detail | none (the page reads nothing through the bridge; its local service reads your usage.jsonl, magpie's usage/quota API, and — for optional remote attribution — your magpie config's provider key to query the configured remote magpie) |
| [fingerprint](packages/fingerprint) | Numeric response fingerprints to investigate suspected model substitution across providers, with shared challenges, candidate rankings, local evidence and JSON export | none (its local service calls magpie’s gateway; sampling uses provider quota) |
| [chat](packages/chat) | Chat with magpie's models, your MCP servers, instructions and skills, by Magic_zero ([Magiczerowxy](https://github.com/Magiczerowxy)). Has a host part: a local service the page goes to | none (its service calls magpie's gateway) |
| [window-warmup](packages/window-warmup) | Window warmup: send one fixed short message ("hi", max_tokens 16) to a provider, account and model you pick, right after its quota window resets, daily at set times or every few hours, so the next subscription window opens early, by [YangHonghang](https://github.com/YangHonghang). Has a host part: a local service on 127.0.0.1 the page goes to | none; its service calls magpie's gateway and reads magpie's providers.json (keys only as sha256 fingerprints, plus key names and account models) and model cache. Each send uses the chosen account's quota |
+61
View File
@@ -0,0 +1,61 @@
# Copy to .env and edit as needed; run the board with `npm start` (or `node server.mjs`).
# Every variable is optional — commented-out lines show the built-in defaults.
# Listen port. Default 3455; 0 = let the OS pick. When the port is held the service
# retries for ~8s, then reuses a live instance of the same build, or fails with a clear
# error when a different build / a foreign process holds it. It never scans upward.
#PORT=3455
# Bind address. Keep the loopback default: the board page answers loopback binds and
# loopback Host names only — a non-loopback bind never serves the page (403).
#HOST=127.0.0.1
# Token for scripts that call the API (send it as the "x-dash-key" request header).
# Optional: when unset, every start generates a random token — not persisted, not logged,
# not in any URL. Set it EMPTY explicitly (PAGE_KEY=) to serve the API without a token.
# Never commit a real key: .env is git-ignored.
#PAGE_KEY=
# Extra Host names the API may be reached by behind a reverse proxy (comma-separated).
# The board page stays loopback-only regardless.
#ALLOWED_HOSTS=
# magpie's local gateway API and its bearer key (live quotas / KPIs).
# Resolution order: manifest options.gateway → GATEWAY → MAGPIE_GATEWAY →
# MAGPIE_ADDR (set by magpie's plugin host) → the 3425 default.
#GATEWAY=http://127.0.0.1:3425
#MAGPIE_KEY=
# magpie's config directory — explicit override only (magpie itself has no such
# env; the service follows the host's cwd, then XDG_CONFIG_HOME/magpie, then
# ~/.config/magpie, so portable installs need nothing here).
# usage.jsonl, plugin-providers.json and providers.json live there.
#MAGPIE_CONFIG_DIR=
# magpie's usage log — the only data source (no prompts or message bodies are read).
#USAGE_JSONL=
# Brand logos: the only source is magpie's own plugin-providers.json (data-URI icons,
# no downloads, no directory scanning). Default: the file next to usage.jsonl.
#MAGPIE_PROVIDERS_FILE=
# ---- Remote attribution: OPT-IN, OFF by default -------------------------------
# ATTRIBUTION=local (default) keeps all attribution on this machine's usage.jsonl.
# ATTRIBUTION=remote makes the service read this machine's magpie providers.json (or
# REMOTE_BASE/REMOTE_KEY below) and send that provider's key to the remote magpie's
# /v1/magpie/usage/requests — the key leaves this machine only toward that remote
# magpie. The equivalent manifest option is options.attribution: "remote".
#ATTRIBUTION=local
# Remote provider credentials (read only when ATTRIBUTION=remote). Default source: the
# preset remote-magpie / magpie-direct / magpie-cf provider in MAGPIE_PROVIDERS.
#MAGPIE_PROVIDERS=~/.config/magpie/providers.json
#REMOTE_BASE=
#REMOTE_KEY=
# Caller names kept for the remote charts. No default: empty means no filtering.
#REMOTE_CALLERS=
# Provider aliases counted as "remote" in the 24-hour split. Default: magpie's own three
# route names; override via manifest options.remoteProviders.
#REMOTE_PROVIDERS=magpie-direct,magpie-cf,remote-magpie
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 magpie-usage-board contributors
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.
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+24
View File
@@ -0,0 +1,24 @@
magpie usage board
Copyright 2026 magpie-usage-board contributors
This product includes third-party software and assets:
* Apache ECharts (static/echarts.min.js)
Copyright 2018-2026 Apache Software Foundation.
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. The full license
text ships with this distribution at LICENSES/Apache-2.0.txt and is also
available at https://www.apache.org/licenses/LICENSE-2.0
Provenance: custom build from the npm `echarts@5.5.1` package via
`build/echarts-entry.mjs` (see that file for the included components).
The bundle is byte-for-byte reproducible with `npm run build:echarts`
(scripts/build-echarts.mjs).
* Brand logos
Provider logos are not bundled with this package: at service startup the
server reads magpie's own `plugin-providers.json` (the registry magpie
maintains next to its usage.jsonl) and keeps only the data-URI icons it
already contains. No network downloads and no plugin-directory scanning
are involved. Product and company names and logos are trademarks or
registered trademarks of their respective owners, used solely to identify
the corresponding providers; they do not imply endorsement.
+193
View File
@@ -0,0 +1,193 @@
# magpie usage board
A usage dashboard page inside [magpie](https://usemagpie.ai)'s window, served by the plugin's
own zero-dependency local service.
**Most of this board repeats magpie's own Usage page** — the allowance cards, the
per-provider and per-model totals and the request list are all there already. Install this
page for the five things Usage does not show:
1. **Remote attribution by caller key** — traffic routed through a remote magpie, split by
which caller key caused it (opt-in; see *Remote attribution*).
2. **TTFT p50/p90 per provider** — latency quality next to the volume.
3. **A 7×24 heatmap** — when the calls actually happen, by weekday and hour.
4. **Direct-vs-remote split of the last 24 hours** — how much went out through a remote
magpie versus straight out of this machine.
5. **Expiry tiers on the quota cards** — how soon each allowance lapses, not just how much
is left.
Everything else is convenience around those: daily and per-provider charts, 24-hour
cache-hit and token curves, per-account detail for the remote side.
Where [`@magpie-community/page-usage`](https://github.com/magpie-community/plugins/tree/main/packages/usage)
is a bridge-only glance at magpie's summary totals, this page is the full board. Where
[`page-usage-tree`](https://github.com/magpie-community/plugins/tree/main/packages/page-usage-tree)
drills provider → account → model, this one puts quotas, costs and quality on one screen.
## What it answers
1. **Which providers were used** — local direct traffic plus traffic that landed on a remote
magpie (opt-in), merged under real provider names (daily chart, provider pies).
2. **How much** — calls, tokens, daily trend; the quota wall shows what is left and when it
lapses.
3. **How good** — TTFT P50/P90, per-account detail and error counts for the remote side.
The two accounting views (KPI ledger vs. provider charts) and the exit-alias rules are
documented in [`docs/data-semantics.md`](docs/data-semantics.md).
## How it works
Two layers, the same shape the community uses for host-part pages:
1. `index.mjs` is an OpenCode v1 plugin loaded by magpie's Bun host. When magpie calls its
`server()` entry it starts `server.mjs`, a zero-dependency Node 22+/Bun HTTP service on
`127.0.0.1:3455`.
2. `page/index.html` + `page/boot.js` is the hosted page. It asks the bridge for
`magpie.service` first: when `magpie web` runs on another machine it proxies the local
service under magpie's own origin, so **magpie's own key/auth is the outer gate** and the
page never leaves that origin. A desktop window has no service, so it falls back to
`http://127.0.0.1:3455/` — the port it read from `magpie.options.get()`, the same value
the service was started with. An 8-second `<meta refresh>` is the fallback if the boot
script is blocked.
The 8-second `<meta refresh>` is deliberate: an earlier all-script page could be declared dead
by the host after 10 seconds when the bridge handshake raced; the meta fallback still
navigates if `boot.js` never runs, and the window is wide enough for slow bridge handshakes
that `boot.js` resolves first.
### Why a local service (and its token)
magpie's bridge exposes a small set of reads — the bridge-only `usage` page uses just
`usage:summary`. This board needs quotas, per-provider/per-day totals, a 7×24 heatmap,
recent requests, TTFT and account detail; those are not in that summary. Like
[`page-usage-tree`](https://github.com/magpie-community/plugins/tree/main/packages/page-usage-tree),
it therefore runs a small local service that reads `usage.jsonl`.
That service is a separate origin on `127.0.0.1`, outside magpie's auth. The gate is the same
model the community [`page-usage-tree`](https://github.com/magpie-community/plugins/tree/main/packages/page-usage-tree)
uses: the board page is served only on a loopback bind **and** a loopback `Host` — any
non-loopback bind answers 403 for the page — and the service injects its token into the
served HTML (`window.__KEY__`), so nobody types it. `/api/*` (except the two anonymous
liveness routes below) checks the same token from the `x-dash-key` request header. There is
no `?key=` query authentication and no token cookie: a key must never reach a URL, where
proxy and browser-history logs would record it.
The token comes from the `PAGE_KEY` environment variable when you set one (for scripts that
call the API); otherwise every start generates a fresh random token that is never written to
disk and never appears in a log line or URL. When `magpie web` is remote, the page goes
through `magpie.service` and stays under magpie's origin, so magpie's key remains the outer
gate.
## Install
Requires Node 22+. Inside magpie (once the package is merged into the community registry):
```sh
magpie plugin add @magpie-community/page-usage-board
```
Standalone, from a checkout or the npm package:
```sh
npm start # or: node server.mjs
# [magpie-usage] listening on http://127.0.0.1:3455/
```
The board is local-only: the page answers loopback binds and loopback `Host` names, and a
non-loopback bind never serves it (403) — there is no remote-visitor auth channel. Scripts
that want the API set `PAGE_KEY` and send it as the `x-dash-key` request header. The service
reads `~/.config/magpie/usage.jsonl`.
## Configuration
| Variable | Default | Meaning |
|---|---|---|
| `PORT` | `3455` | Listen port; `0` = let the OS pick. When the port is held, the service retries for ~8s, then reuses a live instance of the **same build** (recognised anonymously via the build id on `/api/ping`) or fails with a clear error when a different build or a foreign process holds it. It never scans upward. |
| `HOST` | `127.0.0.1` | Bind address. Keep loopback: the board page answers loopback binds and loopback `Host` names only, and other local users of this machine can reach a loopback-bound board. |
| `PAGE_KEY` | generated | Optional token for scripts that call the API (sent as the `x-dash-key` header). When unset, every start generates a random token — not persisted, not logged, not in any URL. Set it **empty explicitly** (`PAGE_KEY=`) to serve the API without a token. |
| `ALLOWED_HOSTS` | empty | Comma-separated extra `Host` names the **API** may be reached by (e.g. behind a reverse proxy). The page stays loopback-only regardless. |
| `GATEWAY` | `http://127.0.0.1:3425` | magpie's local gateway API. Resolved in this order: manifest `options.gateway` → `GATEWAY` → `MAGPIE_GATEWAY` → **`MAGPIE_ADDR`** (set by magpie's plugin host; a `0.0.0.0:`/`[::]:` prefix is normalised to loopback) → the `3425` default. |
| `MAGPIE_KEY` | empty | Bearer key for the gateway, when the gateway requires one. |
| `USAGE_JSONL` | `~/.config/magpie/usage.jsonl` | magpie's usage log. |
| `MAGPIE_CONFIG_DIR` | `~/.config/magpie` | Explicit override for magpie's config directory (magpie itself has no such env — this is for tests and unusual layouts). The service resolves the dir the way magpie does: the **host's cwd** when it carries magpie markers (`usage.jsonl` / `plugins.json` / `providers.json` — the plugin host starts the service with the data dir as cwd, which covers portable installs) → `XDG_CONFIG_HOME/magpie` → `~/.config/magpie`. `usage.jsonl`, `plugin-providers.json` and `providers.json` default to files inside it. |
| `MAGPIE_PROVIDERS_FILE` | `<magpie config dir>/plugin-providers.json` | Where brand logos are read from (magpie's own provider registry — see *Brand logos*). |
| `ATTRIBUTION` | `local` | Remote attribution is **opt-in**: the default `local` keeps attribution on this machine's log; `ATTRIBUTION=remote` (or manifest `options.attribution: "remote"`) makes the service query the configured remote magpie — the provider key is sent to that remote magpie. |
| `MAGPIE_PROVIDERS` | `~/.config/magpie/providers.json` | Where the remote URL and key are read from (used only with `ATTRIBUTION=remote`). |
| `REMOTE_BASE` / `REMOTE_KEY` | empty | Explicit remote override (both required) instead of `providers.json`. |
| `REMOTE_CALLERS` | empty | Caller names kept for the remote charts. **No default** — empty means no caller filtering. |
| `REMOTE_PROVIDERS` | `magpie-direct,magpie-cf,remote-magpie` | Provider aliases counted as "remote" in the 24-hour split. The default is exactly magpie's own three route names; override via manifest `options.remoteProviders`. |
## Manifest options
The magpie manifest (`magpie.options` in package.json) carries the same knobs. Options take
precedence over environment variables, and the built-in default applies when neither is set:
| Option | Default | Meaning |
|---|---|---|
| `port` | `3455` | Service port. `magpie.page.service.option: "port"` tells magpie to inject the user's chosen port into `server(input, options)`; `index.mjs` forwards it to `startServer`. |
| `attribution` | `"local"` | Keep `"local"` to hold attribution on this machine (the default — remote is never enabled implicitly). `"remote"` is the explicit opt-in that queries the configured remote magpie and sends the provider key to it. |
| `remoteCallers` | `""` | Caller filter for the remote charts; empty means no filtering. |
| `remoteProviders` | `"magpie-direct,magpie-cf,remote-magpie"` | Provider aliases counted as "remote" in the 24-hour split. |
## Languages
The interface ships in Chinese and English. `?lang=zh` or `?lang=en` forces one; otherwise
the page follows `navigator.language` automatically.
## Brand logos
The quota wall shows provider brand icons. Their only source is magpie's own
`plugin-providers.json` — the registry magpie maintains next to `usage.jsonl`
(`MAGPIE_PROVIDERS_FILE` overrides the path). At startup the service reads that file once,
keeps only `data:image/...` URIs (each capped at 2 MB, at most 4 MB injected in total) and
injects them into the served HTML. There is no plugin-directory scanning, no download, no
disk cache and no `/logos` route: `https://` icons are deliberately not fetched, so the
board never contacts a third-party CDN on your behalf — providers without a data-URI icon
fall back to a colored first-letter block.
## Data and privacy
- Reads this machine's `usage.jsonl` and magpie's local gateway API. The board itself sends
no telemetry; its Content-Security-Policy allows no third-party host at all.
- **Remote attribution is opt-in and off by default.** Only `ATTRIBUTION=remote` (or manifest
`options.attribution: "remote"`) enables it: the service then makes read-only requests to
the configured remote magpie's own `/v1/magpie/usage/requests`, using the provider key
already configured in this machine's `providers.json` — that key is sent to that remote
magpie and nowhere else. Rows are filtered by `REMOTE_CALLERS` (no default filter) and
aggregated locally; no prompts or message bodies are involved. There is no second service
and no separate page key.
- The page and its assets are served from `127.0.0.1`. The trust boundary is the local
machine: other local users can reach a loopback-bound board, and remote attribution reads
every caller's rows on the shared remote magpie (filtered for display, disclosed in the
Pages table).
- The anonymous surface is exactly two routes: `GET /api/ping` (an identity fingerprint +
build id, used to recognise a live instance of the same build) and `GET /api/health`
(liveness). Every other `/api/*` route requires the token via the `x-dash-key` header,
every route checks `Host` to block DNS rebinding, and the board page itself is never
served on a non-loopback bind or a public `Host` name.
- No prompts or message bodies are read — the service aggregates model, provider, tokens,
cost, timing and error counts.
## Develop
These commands run from a git checkout — the npm package (`npm pack`) ships the runtime,
docs and notices; `test/` stays in the checkout.
```sh
node --test # auth/host/page gate, caller filtering, package metadata
npm run build:echarts # rebuild static/echarts.min.js byte-for-byte (verify: git diff --exit-code static/echarts.min.js)
```
- `static/index.html` is the page source; at request time the service injects
`window.__DATA__`, `window.QLOGOS` (brand logos) and, on a loopback bind, `window.__KEY__`
into the served HTML.
- `npm test` / `npm pack` run the same checks; `prepack` refuses to package a stray
`remote.js` or a literal page key.
- Remote attribution defaults to off and must be opted into (see *Configuration*).
## License
MIT. `static/echarts.min.js` is a custom Apache-2.0 build of Apache ECharts, reproducible
byte-for-byte with `npm run build:echarts` (see `NOTICE`). Provider logos are collected at
runtime from magpie's `plugin-providers.json` and are the trademarks of their owners, used
only to identify providers (see `NOTICE`).
@@ -0,0 +1,24 @@
// 定制构建入口:只包含看板用到的图表与组件(见第四轮瘦身分析)。
// 重建命令:npx esbuild build/echarts-entry.mjs --bundle --minify --global-name=echarts
// --outfile=static/echarts.min.js
// 页面通过全局 echarts.init(...) 使用;新增图表类型时在此补 import 并重建。
import * as echarts from 'echarts/core';
import { BarChart, LineChart, PieChart, HeatmapChart } from 'echarts/charts';
import {
TooltipComponent, LegendComponent, GridComponent, DataZoomComponent,
DataZoomInsideComponent, DataZoomSliderComponent, VisualMapComponent,
AxisPointerComponent,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([
BarChart, LineChart, PieChart, HeatmapChart,
TooltipComponent, LegendComponent, GridComponent, DataZoomComponent,
DataZoomInsideComponent, DataZoomSliderComponent, VisualMapComponent,
AxisPointerComponent, CanvasRenderer,
]);
// 页面通过全局 echarts.init(...) 使用;--global-name 的 iife 会把 default export
// 嵌套进 .default,这里直接赋值保证 window.echarts 就是完整命名空间
if (typeof window !== 'undefined') window.echarts = echarts;
export default echarts;
@@ -0,0 +1,82 @@
# Community submission
The community publishes packages by merging a pull request into
[`magpie-community/plugins`](https://github.com/magpie-community/plugins). Submitting is just
that PR — no dashboard form, and no manual `npm publish`: merging to the registry's main
branch bumps the version and **trusted publishing puts the package on npm automatically**,
so `package.json`'s `version` must be release-ready when the PR lands. One PR adds three
things:
1. `packages/page-usage-board/` — this package (all files from `npm pack`, plus `LICENSE`,
`README.md`, `docs/` and the development files — see the layout trap below).
2. One entry in `registry.json`.
3. One row in the README's **Pages** table.
## registry.json entry
```json
{
"package": "@magpie-community/page-usage-board",
"name": "Usage Board",
"kind": "page",
"community": true,
"summary": {
"en": "A quota card wall with expiry tiers, daily/per-provider charts, 24h cache-hit and token curves, optional remote attribution and account detail. Runs its own zero-dependency local service reading this machine's Magpie usage data; optional remote attribution queries the configured remote magpie.",
"zh": "额度到期卡片墙 + 每日与 provider 用量图表 + 24 小时缓存命中与 token 曲线,可选远端归因与账号明细。自带零依赖本机服务,读本机 Magpie 用量数据;远端归因会查询所配置的远端 magpie。"
}
}
```
The `summary` above must stay **verbatim-identical** to `magpie.summary` in package.json —
copy it into the PR description together with the difference declaration (the registry
requires all three texts to match).
## README Pages row
```md
| [page-usage-board](packages/page-usage-board) | Full usage board: quota cards with expiry tiers, daily and per-provider charts, 24-hour cache-hit and token curves, optional remote attribution and account detail | none (the page reads nothing through the bridge; its local service reads your usage.jsonl, magpie's usage/quota API, and — for optional remote attribution — your magpie config's provider key to query the configured remote magpie) |
```
## The packaging layout
`npm pack` ships what the `files` field in package.json lists — the runtime (`index.mjs`,
`server.mjs`, `page/`, `static/`), the vendored echarts bundle (`build/echarts-entry.mjs` +
`static/echarts.min.js`), `docs/`, `scripts/` (`prepack.mjs`, `build-echarts.mjs`) and
`NOTICE`. The `prepack` hook asserts that the echarts entry and its build script exist and
are covered by `files`, and validates every relative link in README.md and `docs/*.md`.
Correct layout for `packages/page-usage-board/`: the `npm pack` output, plus `LICENSE`,
`.env.example` and `test/` (development files the README references — they do not need to
be in `files`).
Check before opening the PR:
- `docs/` and `.env.example` are in the staged tree.
- Every relative link in README.md and `docs/*.md` resolves inside
`packages/page-usage-board/` — click through them in the GitHub PR preview.
## Checks before opening the PR
- `npm test` passes (auth, `Host`, page gate, traversal, lead-page, package metadata).
- `npm pack --dry-run` contains no `remote.js`, no page key, and includes `LICENSE`.
- The host part guards every route with a token **and checks `Host`** (community requirement
for pages that navigate to a local service). The board page itself is served only on a
loopback bind with a loopback `Host` name — the token is injected into the served HTML
rather than typed, and a non-loopback bind or a proxied public `Host` never receives the
page. Deliberate anonymous routes, filed here for review: `GET /api/ping` (returns
`{service,ok,build,version}` — an identity fingerprint + build id, used to recognise a
live instance of the same build) and `GET /api/health` (returns `{ok,jsonl}` — liveness).
Both carry no key and no usage data; every other `/api/*` route requires the token via
the `x-dash-key` header (no `?key=` query auth, no cookie channel), and `/static/*` holds
only the chart library and page assets (no data).
- Remote attribution defaults to **off** (`magpie.options.attribution: "local"`); the user
must explicitly opt in (`ATTRIBUTION=remote` or `options.attribution: "remote"`), which
sends the configured provider key to the remote magpie and nowhere else.
- The hosted page uses `window.magpie.service` when present, so a remote `magpie web`
deployment keeps the frame under magpie's own origin and key.
- The lead page has no inline scripts (its only sources are magpie's `_magpie/bridge.js`
and the plugin's `boot.js`) and fetches nothing; the board itself only calls its own
service on `127.0.0.1`. Its Content-Security-Policy allows no third-party host, and brand
logos come from magpie's `plugin-providers.json` as data URIs — the page never contacts a
third-party CDN.
- `magpie.permissions` is `[]`: the page reads nothing through the bridge.
@@ -0,0 +1,66 @@
# Data semantics
Read this before changing the page or the aggregations. Two different totals are shown on
purpose; they answer different questions and must not be silently reconciled.
## The four exit aliases are two routes
magpie renamed its outbound providers over time:
| Route | Names in `usage.jsonl` | Remote `caller` |
|---|---|---|
| direct | `magpie-direct`, `remote-magpie` | `cloud` |
| Cloudflare | `magpie-cf`, `magpie-2` | `Magpie` |
The page keeps all four in one `REMOTE_ENTRY` set. Never hand-write a single name.
## Charts use real providers
- Local, non-exit providers are taken from the detail log as-is.
- Remote attribution adds per-provider totals under the same provider names.
- When attribution is available, the exit aliases do **not** enter the charts; their traffic
is already attributed.
- When attribution is unavailable, the four exit aliases collapse into one series labelled
"remote (unattributed)", so nothing disappears silently.
- The daily chart stacks providers; the provider pie merges aliases.
## Where the remote side comes from
The local service reads the remote magpie's own `/v1/magpie/usage/requests` (provider key
already in `providers.json`) and keeps rows whose `callerKeyName` is in `REMOTE_CALLERS`
(default `cloud`, `Magpie`). The caller breakdown still lists every caller on that instance
(e.g. `hermes`), but provider/account/day/hourly numbers are this machine's only. The 24-hour
remote curve is caller-filtered too; older builds that read the remote log without that filter
over-counted other callers.
The standalone `/usage2` service is retired: it was only a way to run that filter on the
remote log when the magpie API could not give per-caller rows.
## KPI cards use the local gateway ledger
Cost on the KPI cards is magpie's own pricing (subscription quota converted to money), not
money actually spent. It is intentionally different from the chart totals, which follow real
providers. Label both clearly; do not "fix" one to match the other.
## Quota cards deduplicate by subscription
The same subscription can be read through two routes (direct / proxy) and two instances
(local / remote). The quota wall groups by (normalized subscription + account) and shows one
card per group; the `· Magpie direct/proxy` suffix is stripped from the name. Different
accounts (different phone numbers or keys) are different quotas and stay as separate cards.
## Remote cards have three states
- No remote data source (remote attribution is opt-in and defaults to local): hide the TTFT and account cards.
- Source configured but the fetch fails (45 s client timeout, 10 s per remote page server-side): show a red error card explaining it.
- Success: show the data.
A dead source must never make the card vanish without a trace — silence looks like "zero
usage" and is the one failure mode that misleads.
## What is read
`usage.jsonl` lines are aggregated into daily × provider totals, a 7×24 heatmap, 24-hour
token/cache curves, recent requests and per-account attribution. Probe lines
(`kind: "model_list"`, `source: "probe"`) are filtered out. Prompts, messages and tool output
are never read or displayed.
+57
View File
@@ -0,0 +1,57 @@
// magpie 窗口里的「用量看板」页面。
//
// 两层结构(同 Magiczerowxy/magpie-chat、magpie-community/page-usage-tree 的做法):
// 1. 本文件作为 OpenCode v1 插件被 magpie 的 Bun 宿主加载。模块导入必须零副作用
// (社区 scripts_check.mjs 会直接 import 做静态检查,导入即监听会占端口、写配置);
// 服务只在 magpie 调用 server(input, options) 时启动,且 await 到真正监听后才返回。
// 2. page/index.html + page/boot.js 是 magpie 托管的「带路页」:优先跳
// window.magpie.service(magpie web 在自己域名下的转发路径,页面留在 magpie
// origin、由 magpie 自己的 key 保护),桌面回退 http://127.0.0.1:3455/。
// 服务端把口令注入返回的看板(window.__KEY__),只有 API 路由校验它。
//
// 服务已在本机跑着(另一个插件实例 / 手动 node)时端口占用,server.mjs 会静默复用。
import { fileURLToPath, pathToFileURL } from "node:url";
import path from "node:path";
const here = path.dirname(fileURLToPath(import.meta.url));
let starting = null;
const plugin = {
id: "magpie-usage-board",
server: async (_input, options) => {
if (!starting) {
// manifest options(page.service.option = "port" 时 options.port 由 magpie 注入)
// → startServer() 内部再回退到环境变量/默认值。port 的 0/非法值归成 undefined:
// 服务回落到默认口,页面从同一 options 读到的也走同一回落,两边永远一致。
const n = Number(options?.port);
const port = Number.isInteger(n) && n > 0 && n < 65536 ? n : undefined;
starting = import(pathToFileURL(path.join(here, "server.mjs")).href)
.then((m) => m.startServer({
port,
attribution: options?.attribution,
remoteCallers: options?.remoteCallers,
remoteProviders: options?.remoteProviders,
gateway: options?.gateway,
}))
.then((port) => ({ ok: true, port }))
.catch((err) => {
starting = null; // 允许 magpie 下次调用重试
console.error("[magpie-usage-board] server not started:", err?.message || err);
throw err;
});
}
await starting;
// 返回 { ok, port }:magpie 只要 await 成功即可,多出的字段便于测试与排障
return await starting;
},
};
export default plugin;
// 手动启动入口:node index.mjs(与 server.mjs 直跑等价,走同一生命周期契约)
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
plugin.server().catch((e) => {
console.error(`[magpie-usage-board] not started: ${e?.message || e}`);
process.exit(1);
});
}
+533
View File
@@ -0,0 +1,533 @@
{
"name": "@magpie-community/page-usage-board",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@magpie-community/page-usage-board",
"version": "0.1.0",
"license": "MIT",
"devDependencies": {
"echarts": "5.5.1",
"esbuild": "0.28.2"
},
"engines": {
"magpie": ">=0.1.1340",
"node": ">=22"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
"integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
"integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
"integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
"integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
"integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
"integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
"integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
"integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
"integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
"integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
"integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
"integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
"integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
"integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
"integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
"integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
"integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
"integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
"integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
"integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
"integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
"integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
"integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
"integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
"integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
"integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/echarts": {
"version": "5.5.1",
"resolved": "https://registry.npmjs.org/echarts/-/echarts-5.5.1.tgz",
"integrity": "sha512-Fce8upazaAXUVUVsjgV6mBnGuqgO+JNDlcgF79Dksy4+wgGpQB2lmYoO4TSweFg/mZITdpGHomw/cNBJZj1icA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"tslib": "2.3.0",
"zrender": "5.6.0"
}
},
"node_modules/esbuild": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
"integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.28.2",
"@esbuild/android-arm": "0.28.2",
"@esbuild/android-arm64": "0.28.2",
"@esbuild/android-x64": "0.28.2",
"@esbuild/darwin-arm64": "0.28.2",
"@esbuild/darwin-x64": "0.28.2",
"@esbuild/freebsd-arm64": "0.28.2",
"@esbuild/freebsd-x64": "0.28.2",
"@esbuild/linux-arm": "0.28.2",
"@esbuild/linux-arm64": "0.28.2",
"@esbuild/linux-ia32": "0.28.2",
"@esbuild/linux-loong64": "0.28.2",
"@esbuild/linux-mips64el": "0.28.2",
"@esbuild/linux-ppc64": "0.28.2",
"@esbuild/linux-riscv64": "0.28.2",
"@esbuild/linux-s390x": "0.28.2",
"@esbuild/linux-x64": "0.28.2",
"@esbuild/netbsd-arm64": "0.28.2",
"@esbuild/netbsd-x64": "0.28.2",
"@esbuild/openbsd-arm64": "0.28.2",
"@esbuild/openbsd-x64": "0.28.2",
"@esbuild/openharmony-arm64": "0.28.2",
"@esbuild/sunos-x64": "0.28.2",
"@esbuild/win32-arm64": "0.28.2",
"@esbuild/win32-ia32": "0.28.2",
"@esbuild/win32-x64": "0.28.2"
}
},
"node_modules/tslib": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz",
"integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==",
"dev": true,
"license": "0BSD"
},
"node_modules/zrender": {
"version": "5.6.0",
"resolved": "https://registry.npmjs.org/zrender/-/zrender-5.6.0.tgz",
"integrity": "sha512-uzgraf4njmmHAbEUxMJ8Oxg+P3fT04O+9p7gY+wJRVxo8Ge+KmYv0WJev945EH4wFuc4OY2NLXz46FZrWS9xJg==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"tslib": "2.3.0"
}
}
}
}
+82
View File
@@ -0,0 +1,82 @@
{
"name": "@magpie-community/page-usage-board",
"version": "0.1.0",
"description": "在 magpie 窗口里查看用量:额度到期卡片墙 + 每日/模型/provider 用量图表 + 可选远端归因,由插件自带的本机服务供数。A usage dashboard page in magpie's window: quota cards with expiry tiers, daily and per-provider charts, optional remote attribution, served by the plugin's own local service.",
"type": "module",
"main": "./index.mjs",
"files": [
"index.mjs",
"server.mjs",
"page",
"static",
"build",
"LICENSE",
"README.md",
"scripts",
"NOTICE",
"docs",
"LICENSES"
],
"scripts": {
"start": "node server.mjs",
"test": "node --test",
"build:echarts": "node scripts/build-echarts.mjs",
"prepack": "node scripts/prepack.mjs"
},
"engines": {
"node": ">=22",
"magpie": ">=0.1.1340"
},
"keywords": [
"magpie",
"magpie-page",
"magpie-plugin",
"usage",
"dashboard",
"quota",
"charts",
"token"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/magpie-community/plugins.git",
"directory": "packages/page-usage-board"
},
"homepage": "https://github.com/magpie-community/plugins/tree/main/packages/page-usage-board",
"bugs": {
"url": "https://github.com/magpie-community/plugins/issues"
},
"magpie": {
"name": "Usage Board",
"summary": {
"en": "A quota card wall with expiry tiers, daily/per-provider charts, 24h cache-hit and token curves, optional remote attribution and account detail. Runs its own zero-dependency local service reading this machine's Magpie usage data; optional remote attribution queries the configured remote magpie.",
"zh": "额度到期卡片墙 + 每日与 provider 用量图表 + 24 小时缓存命中与 token 曲线,可选远端归因与账号明细。自带零依赖本机服务,读本机 Magpie 用量数据;远端归因会查询所配置的远端 magpie。"
},
"page": {
"title": "Usage Board",
"titles": {
"en": "Usage Board",
"zh": "用量看板"
},
"file": "page/index.html",
"icon": "page/icon.svg",
"service": {
"port": 3455,
"option": "port"
}
},
"permissions": [],
"options": {
"port": 3455,
"attribution": "local",
"remoteCallers": "",
"remoteProviders": "magpie-direct,magpie-cf,remote-magpie"
},
"icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDAgMTAwIj4KICA8IS0tIFVzYWdlIGJvYXJkOiBkYXJrIHJvdW5kZWQgcGxhdGUsIGJsdWUgdXNhZ2UgbGluZSwgb25lIGFtYmVyIGJhciAtLT4KICA8cmVjdCB4PSI0IiB5PSI0IiB3aWR0aD0iOTIiIGhlaWdodD0iOTIiIHJ4PSIyMCIgZmlsbD0iIzFlMjQzMCIvPgogIDwhLS0gYW1iZXIgYmFyIChxdW90YSB0b2RheSkgLS0+CiAgPHJlY3QgeD0iMjQiIHk9IjU2IiB3aWR0aD0iMTAiIGhlaWdodD0iMjQiIHJ4PSIzIiBmaWxsPSIjZjVhNjIzIi8+CiAgPCEtLSBibHVlIHVzYWdlIGxpbmUgb3ZlciB0aGUgbGFzdCBob3VycyAtLT4KICA8cG9seWxpbmUgcG9pbnRzPSIyMiw2NiAzNiw1MiA1MCw1OCA2NCwzOCA3OCwzMCIKICAgIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzRjOWZmZSIgc3Ryb2tlLXdpZHRoPSI3IgogICAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+CiAgPCEtLSBlbmRwb2ludCBkb3QgLS0+CiAgPGNpcmNsZSBjeD0iNzgiIGN5PSIzMCIgcj0iNS41IiBmaWxsPSIjNGM5ZmZlIi8+Cjwvc3ZnPgo="
},
"devDependencies": {
"echarts": "5.5.1",
"esbuild": "0.28.2"
}
}
+114
View File
@@ -0,0 +1,114 @@
// Navigate magpie's frame to the board service.
//
// Prefer window.magpie.service: magpie web proxies the service on its own address, so the
// page stays under magpie's origin and magpie's own key/auth is the gate. A desktop window
// has no service; fall back to loopback on the port from the manifest options — the same
// value the service itself was started with, so they can never disagree.
//
// Do not probe the service: the page's CSP is connect-src 'none', so fetch/XHR is refused.
// The progress bar here is therefore driven by two real signals only — the bridge handshake
// (window.magpie.ready) and elapsed time. The meta refresh in index.html (8 s) is the last
// fallback if this script never runs.
(async () => {
const DEFAULT_PORT = 3455;
const words = {
en: {
title: "Usage Board",
bridging: "Connecting to the host bridge…",
slow: "Bridge is slow — opening the local board…",
err: (m) => `Bridge did not respond: ${m} — opening the local board…`,
nobridge: "No host bridge detected — opening the local board…",
ready: "Board located, navigating…",
readyLocal: "Ready — opening the local board…",
},
zh: {
title: "用量看板",
bridging: "正在连接宿主桥接…",
slow: "桥接响应慢,即将直接打开本机看板…",
err: (m) => `桥接未响应:${m} —— 将直接打开本机看板…`,
nobridge: "未检测到宿主桥接,直接打开本机看板…",
ready: "已定位看板服务,正在跳转…",
readyLocal: "已就绪,正在打开本机看板…",
},
};
let lang = String(navigator.language || "en").toLowerCase().startsWith("zh") ? "zh" : "en";
let port = DEFAULT_PORT;
let theme = ""; // magpie 自己的深浅色;空 = 看板回落 prefers-color-scheme
const bar = document.getElementById("bar");
const msg = document.getElementById("msg");
const say = (t, bad) => {
if (!msg) return;
msg.textContent = t;
msg.classList.toggle("bad", !!bad);
};
const setBar = (pct, bad) => {
if (!bar) return;
bar.style.width = pct + "%";
if (bar.parentElement) bar.parentElement.classList.toggle("bad", !!bad);
};
setBar(18);
// 桥接慢时进度条缓慢爬行,6 秒后预告回退(meta refresh 8 秒兜底)
const creep = setInterval(() => setBar(Math.min(38, (parseFloat(bar?.style.width) || 18) + 2.5)), 350);
let service = "";
let bridgeErr = "";
const hasBridge = !!window.magpie;
try {
const current = await window.magpie?.ready;
if (current) {
if (typeof current.lang === "string" && current.lang) {
lang = current.lang.toLowerCase().startsWith("zh") ? "zh" : "en";
}
if (typeof current.dark === "boolean") theme = current.dark ? "dark" : "light";
}
} catch (e) {
bridgeErr = (e && e.message) || "bridge handshake failed";
}
try {
const options = await window.magpie?.options?.get?.();
const n = Number(options?.port);
if (Number.isInteger(n) && n > 0 && n < 65536) port = n;
} catch {
// Use the declared default.
}
try {
const s = window.magpie?.service;
if (typeof s === "string" && /^https?:\/\//.test(s)) service = s;
} catch {
// Desktop windows navigate directly to loopback.
}
clearInterval(creep);
const w = words[lang];
document.title = w.title;
const head = document.querySelector(".box b");
if (head) head.textContent = w.title;
if (bridgeErr) {
// 桥接报错:如实展示原因,仍回退打开本机看板
setBar(30, true);
say(w.err(bridgeErr), true);
} else if (!hasBridge) {
setBar(72);
say(w.nobridge);
} else {
setBar(72);
say(service ? w.ready : w.readyLocal);
}
let target = service || `http://127.0.0.1:${port}/`;
// lang/theme 都通过 URL 带给看板(走 service 代理路径时同样要带——用 URL 拼接避免丢已有参数)
try {
const u = new URL(target, location.href);
u.searchParams.set("lang", lang);
if (theme) u.searchParams.set("theme", theme);
target = u.href;
} catch {
target += (target.includes("?") ? "&" : "?") + "lang=" + lang + (theme ? "&theme=" + theme : "");
}
const go = document.getElementById("go");
if (go) go.setAttribute("content", "0;url=" + target);
setTimeout(() => {
try {
location.replace(target);
} catch {
// The meta refresh above still navigates.
}
}, 350); // 让用户看清最终状态再跳
})();
+12
View File
@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<!-- Usage board: dark rounded plate, blue usage line, one amber bar -->
<rect x="4" y="4" width="92" height="92" rx="20" fill="#1e2430"/>
<!-- amber bar (quota today) -->
<rect x="24" y="56" width="10" height="24" rx="3" fill="#f5a623"/>
<!-- blue usage line over the last hours -->
<polyline points="22,66 36,52 50,58 64,38 78,30"
fill="none" stroke="#4c9ffe" stroke-width="7"
stroke-linecap="round" stroke-linejoin="round"/>
<!-- endpoint dot -->
<circle cx="78" cy="30" r="5.5" fill="#4c9ffe"/>
</svg>

After

Width:  |  Height:  |  Size: 593 B

+48
View File
@@ -0,0 +1,48 @@
<!doctype html>
<html lang="zh">
<head><link rel="icon" href="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDAgMTAwIj4KICA8IS0tIFVzYWdlIGJvYXJkOiBkYXJrIHJvdW5kZWQgcGxhdGUsIGJsdWUgdXNhZ2UgbGluZSwgb25lIGFtYmVyIGJhciAtLT4KICA8cmVjdCB4PSI0IiB5PSI0IiB3aWR0aD0iOTIiIGhlaWdodD0iOTIiIHJ4PSIyMCIgZmlsbD0iIzFlMjQzMCIvPgogIDwhLS0gYW1iZXIgYmFyIChxdW90YSB0b2RheSkgLS0+CiAgPHJlY3QgeD0iMjQiIHk9IjU2IiB3aWR0aD0iMTAiIGhlaWdodD0iMjQiIHJ4PSIzIiBmaWxsPSIjZjVhNjIzIi8+CiAgPCEtLSBibHVlIHVzYWdlIGxpbmUgb3ZlciB0aGUgbGFzdCBob3VycyAtLT4KICA8cG9seWxpbmUgcG9pbnRzPSIyMiw2NiAzNiw1MiA1MCw1OCA2NCwzOCA3OCwzMCIKICAgIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzRjOWZmZSIgc3Ryb2tlLXdpZHRoPSI3IgogICAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+CiAgPCEtLSBlbmRwb2ludCBkb3QgLS0+CiAgPGNpcmNsZSBjeD0iNzgiIGN5PSIzMCIgcj0iNS41IiBmaWxsPSIjNGM5ZmZlIi8+Cjwvc3ZnPgo=">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量看板</title>
<!--
带路页:把 magpie 的框架导航到看板服务。
目标优先用 window.magpie.service —— 这是 magpie web 在自己域名下替插件服务转发的
路径(package.json 的 magpie.page.service 声明了端口)。用它,页面始终留在 magpie
的 origin 里,远程打开时由 magpie 自己的 key/auth 保护;桌面窗口没有 service,
回退到本机 http://127.0.0.1:3455/。
<meta refresh> 是兜底:脚本被 CSP 拦掉、或 bridge 握手卡住时,8 秒后仍能走本机。
boot.js 只做一次跳转,不探测服务(页面 CSP 是 connect-src 'none',探测必失败)。
口令不在这里:服务端返回看板时把口令注入 window.__KEY__,只有 API 路由校验它。
仓库、URL、书签里都不出现口令。
-->
<meta id="go" http-equiv="refresh" content="8;url=http://127.0.0.1:3455/">
<style>
:root { color-scheme: light dark; }
html, body { margin: 0; height: 100%; }
body {
display: grid; place-items: center;
font: 13px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
background: Canvas; color: CanvasText;
}
.box { text-align: center; color: GrayText; }
.box b { display: block; color: CanvasText; font-size: 14px; margin-bottom: 10px; }
.bar { width: 200px; height: 3px; border-radius: 2px; background: rgba(128,128,128,.25); background: color-mix(in srgb, CanvasText 14%, transparent); overflow: hidden; margin: 0 auto 8px; }
.bar i { display: block; height: 100%; width: 12%; border-radius: 2px; background: #4da3ff; background: AccentColor; transition: width .4s ease; }
.bar.bad i { background: #f85149; }
.box span { display: block; font-size: 11.5px; min-height: 2.4em; }
.box span.bad { color: #f85149; }
</style>
</head>
<body>
<div class="box">
<b>用量看板</b>
<div class="bar"><i id="bar"></i></div>
<span id="msg">正在打开看板…</span>
</div>
<script src="_magpie/bridge.js"></script>
<script src="boot.js"></script>
</body>
</html>
@@ -0,0 +1,40 @@
// Reproducible build of the vendored ECharts bundle (custom build: bar/line/pie/heatmap only).
//
// npm run build:echarts # rebuild static/echarts.min.js from build/echarts-entry.mjs
//
// The output must stay byte-identical, so this script IS the build definition.
// Verify locally after any change:
// node scripts/build-echarts.mjs && git diff --exit-code static/echarts.min.js
// Pins: echarts@5.5.1, esbuild per devDependencies (exact) and package-lock.json.
//
// - no --global-name: the entry assigns window.echarts directly (with --global-name the
// iife gets wrapped in "var echarts=…" and the default export nests under .default);
// - the provenance banner below is prepended, so it is part of the reproducible output.
import { createHash } from 'node:crypto';
import { readFileSync, statSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { build } from 'esbuild';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const outfile = path.join(root, 'static', 'echarts.min.js');
const BANNER =
'/* Apache ECharts v5.5.1 custom build (bar/line/pie/heatmap + tooltip/legend/grid/dataZoom/visualMap/axisPointer). ' +
'Copyright 2018-2026 Apache Software Foundation, Apache-2.0. See NOTICE. */\n';
const result = await build({
entryPoints: [path.join(root, 'build', 'echarts-entry.mjs')],
bundle: true,
minify: true,
outfile,
write: false,
logLevel: 'warning',
});
const js = result.outputFiles[0].text;
writeFileSync(outfile, BANNER + js);
const sha = createHash('sha256').update(readFileSync(outfile)).digest('hex');
const kb = Math.round(statSync(outfile).size / 1024);
console.log(`static/echarts.min.js rebuilt: ${kb} KiB sha256=${sha.slice(0, 16)}…`);
@@ -0,0 +1,104 @@
// npm pack / publish 前的守卫:公开包里不能出现口令或本机部署物料。
// 这些文件不进 git(见 .gitignore);在错误的目录(如运行时副本)里执行 npm pack
// 就会把 key 带上船。同时做布局守卫(community-submission.md 的 layout trap):
// README/docs 承诺的文件(docs/、vendored echarts 构建产物)必须真实存在,
// 文档相对链接必须可达——否则合并后全 404。
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const problems = [];
const forbidden = [
'static/remote.js',
'server.log',
'usage-page-key',
];
for (const f of forbidden) {
if (existsSync(path.join(root, f))) problems.push(`${f} must not be in the package`);
}
// 口令可能是任意随机串(含 base64url),不限 32-hex:字符集放宽到 base64url 字母表
const secret = /[?&]key=[A-Za-z0-9_-]{16,}|"key"\s*:\s*"[A-Za-z0-9_-]{16,}"|PAGE_KEY\s*[:=]\s*['"]?[A-Za-z0-9_-]{16,}/i;
for (const f of ['page/index.html', 'static/index.html', 'server.mjs', 'index.mjs']) {
const full = path.join(root, f);
if (!existsSync(full)) continue;
const text = readFileSync(full, 'utf8');
if (secret.test(text)) problems.push(`${f} contains what looks like a page key`);
}
const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
for (const f of pkg.files) {
if (!existsSync(path.join(root, f))) problems.push(`files entry is missing: ${f}`);
}
if (!pkg.files.includes('LICENSE')) problems.push('files must include LICENSE');
for (const f of ['build/echarts-entry.mjs', 'scripts/build-echarts.mjs']) {
if (!existsSync(path.join(root, f))) problems.push(`${f} must exist (vendored echarts build must be reproducible)`);
const dir = f.split('/')[0];
if (!pkg.files.includes(dir)) problems.push(`files must include ${dir} (${f} must ship)`);
}
// 布局守卫:README 与 docs 承诺的文件必须随仓库走。
// 仅在 git checkout 里强制(tarball 解包环境没有这些开发文件,属正常)
const inCheckout = existsSync(path.join(root, '.git'));
if (inCheckout) {
for (const f of ['docs', '.env.example', 'README.md', 'LICENSE', 'NOTICE', 'LICENSES']) {
if (!existsSync(path.join(root, f))) problems.push(`repo tree must contain ${f} (docs/README references 404 otherwise)`);
}
for (const f of ['docs', 'scripts', 'build', 'NOTICE', 'LICENSES']) {
if (!pkg.files.includes(f)) problems.push(`files must include ${f} (docs/NOTICE references 404 on npm otherwise)`);
}
}
// README 与 docs 里的 .md 相对链接必须指向存在的文件
function walk(dir) {
let out = [];
let entries;
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return out; }
for (const e of entries) {
if (e.name.startsWith('.') || e.name === 'node_modules') continue;
const full = path.join(dir, e.name);
if (statSync(full).isDirectory()) out = out.concat(walk(full));
else out.push(full);
}
return out;
}
for (const doc of ['README.md', ...walk('docs').filter((f) => f.endsWith('.md'))]) {
const text = readFileSync(path.join(root, doc), 'utf8');
for (const m of text.matchAll(/\]\(([^)#]+?\.md)\)/g)) {
const target = path.resolve(path.dirname(path.join(root, doc)), m[1]);
if (!existsSync(target)) problems.push(`${doc} links to missing file: ${m[1]}`);
}
}
// 全量扫描 files 条目覆盖到的文本文件:口令模式不允许出现在任何被打包的位置
const pkgFiles = [];
for (const entry of pkg.files) {
const full = path.join(root, entry);
if (!existsSync(full)) continue;
if (statSync(full).isFile()) pkgFiles.push(full);
else pkgFiles.push(...walk(full));
}
for (const full of pkgFiles) {
let text;
try { text = readFileSync(full, 'utf8'); } catch { continue; }
const rel = path.relative(root, full);
if (secret.test(text)) problems.push(`${rel} contains what looks like a page key`);
// remote.js 任何形态都不允许(打包产物里按任意路径出现也算)
if (path.basename(full).toLowerCase() === 'remote.js') problems.push(`${rel} must not be in the package`);
}
// 非十六进制的长随机口令(允许 base64url 形式):PAGE_KEY=xxx 16 位以上非空白也要拦
const passphr = /PAGE_KEY\s*[:=]\s*['"]?[A-Za-z0-9_/+-]{16,}/;
for (const f of ['.env.example']) {
const full = path.join(root, f);
if (!existsSync(full)) continue;
const text = readFileSync(full, 'utf8');
const hit = [...text.matchAll(/PAGE_KEY\s*[:=]\s*['"]?([^\s'"]{16,})/g)].filter((m) => !/^\$\{/.test(m[1]) && m[1] !== 'must-be-set');
if (hit.length) problems.push(`${f} contains a literal PAGE_KEY value (${hit.length} occurrence(s))`);
if (passphr.test(text)) problems.push(`${f} contains what looks like a page passphrase`);
}
if (problems.length) {
console.error('✗ cannot pack:\n ' + problems.join('\n '));
process.exit(1);
}
console.log('✓ package is publishable');
+899
View File
@@ -0,0 +1,899 @@
#!/usr/bin/env node
// magpie 用量看板 — 零依赖,Node 22+/Bun 均可运行
// 环境变量:HOST(默认回环)、PORT(默认 3455,0=系统挑;被同构建占用则复用,异种占用则报错)、
// GATEWAY(上游网关)、MAGPIE_KEY(网关 key,本地不需要)、USAGE_JSONL、
// PAGE_KEY(脚本调 API 用的口令,不设则每次启动生成随机 token;页面 HTML 由服务端注入,
// 浏览器里永远不需要手输)、ALLOWED_HOSTS(反代域名白名单,逗号分隔)、
// ATTRIBUTION(local|remote,默认 local:远端归因会把 provider key 发给远端 magpie,必须显式开启)、
// REMOTE_CALLERS/REMOTE_PROVIDERS/MAGPIE_PROVIDERS/MAGPIE_PROVIDERS_FILE
import { createServer } from 'node:http';
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { createReadStream, existsSync, readFileSync, statSync } from 'node:fs';
import { brotliCompressSync, gzipSync } from 'node:zlib';
import path from 'node:path';
import os from 'node:os';
import { fileURLToPath } from 'node:url';
const ROOT = path.dirname(fileURLToPath(import.meta.url));
const HOST = process.env.HOST || '127.0.0.1';
// 日志里对外展示的 host:监听 0.0.0.0/:: 这类地址时展示成 127.0.0.1,IPv6 补方括号
const URL_HOST = HOST === '0.0.0.0' || HOST === '::' ? '127.0.0.1' : (HOST.includes(':') ? `[${HOST}]` : HOST);
// 回环绑定:看板页面只对回环开放(口令注入返回的 HTML,本机用户即所有者——与社区
// page-usage-tree 同一模型)。注意:'::' 与 0.0.0.0 同为通配监听(dual-stack),绝不能算回环。
const LOOPBACK_BIND = HOST === '127.0.0.1' || HOST === 'localhost' || HOST === '::1';
// magpie 的配置目录:与 usage.jsonl、plugin-providers.json、providers.json 的所在。
// 顺序照 magpie 自己的 appdir.Config():宿主数据目录(便携安装)→ XDG → ~/.config/magpie。
// 便携/宿主场景靠 cwd 探测:magpie 的插件宿主以 settings.Dir() 为 cwd 启动服务
// (internal/plugin/host.go 的 bunCommand),desktop 用户无法为宿主设环境变量,
// 所以任何 MAGPIE_CONFIG_DIR 之类的 env 都救不了便携安装——cwd 是唯一可靠信号。
// MAGPIE_CONFIG_DIR 仍保留为显式覆盖(测试/特殊布局用;magpie 本身没有这个变量)。
function magpieConfigDir() {
if (process.env.MAGPIE_CONFIG_DIR) return process.env.MAGPIE_CONFIG_DIR;
try {
const cwd = process.cwd();
if (cwd !== ROOT && (existsSync(path.join(cwd, 'usage.jsonl')) || existsSync(path.join(cwd, 'plugins.json')) || existsSync(path.join(cwd, 'providers.json')))) return cwd;
} catch {}
const xdg = process.env.XDG_CONFIG_HOME;
if (xdg && path.isAbsolute(xdg)) return path.join(xdg, 'magpie');
return path.join(os.homedir(), '.config', 'magpie');
}
const CONFIG_DIR = magpieConfigDir();
// 网关解析链(与 page-usage-tree 一致):manifest options.gateway → GATEWAY →
// MAGPIE_GATEWAY → MAGPIE_ADDR(magpie 宿主总会设置,端口可被用户改过,不能写死)→ 3425。
// MAGPIE_ADDR 是 host:port。只有**未指定地址**(0.0.0.0 / [::])才换成回环——那是
// 「绑所有网卡」的意思,等价于本机;而 [::1] 是明确的 IPv6 回环,监听在 [::1] 的网关
// 通常**没有**在 127.0.0.1 上监听,改写会把请求打到空处(与 magpie 自己的 hostAddr
// 语义一致:它也只处理 unspecified 地址)。
function gatewayCandidates(optionsGateway) {
const out = [];
const push = (v) => {
const text = String(v || '').trim().replace(/\/+$/, '');
if (text && /^https?:\/\//i.test(text) && !out.includes(text)) out.push(text);
};
push(optionsGateway);
push(process.env.GATEWAY);
push(process.env.MAGPIE_GATEWAY);
const addr = process.env.MAGPIE_ADDR;
if (addr) {
// $1=地址 $2=冒号:换掉地址、保住端口分隔
const text = String(addr).trim().replace(/^(0\.0\.0\.0|\[::\])(:|$)/, '127.0.0.1$2');
// host:port 或 [v6]:port;URL 里的 IPv6 字面量必须带方括号
if (/^(\[[0-9a-f:.]+\]|[\w.-]+):\d+$/.test(text)) push('http://' + text);
}
push('http://127.0.0.1:3425');
return out;
}
// 实际生效的网关在 main() 里定稿(listen 前);upstream() 按请求时值取用
let GATEWAY = 'http://127.0.0.1:3425';
const KEY = process.env.MAGPIE_KEY || '';
const USAGE_JSONL = process.env.USAGE_JSONL || path.join(CONFIG_DIR, 'usage.jsonl');
// 页面访问口令:未设 PAGE_KEY → 每次启动生成随机 token(页面 HTML 服务端注入,URL/日志/磁盘
// 都不落);显式设置 → 脚本调 API 用(x-dash-key 头;?key= 已废除,key 不进 URL)。
let PAGE_KEY = '';
const PORT_BASE = 3455;
// manifest options(index.mjs 传入)→ 环境变量 → 内置默认,三级回退;startServer() 时定稿
const CFG = { port: null, attribution: null, remoteCallers: null, remoteProviders: null, gateway: null };
// 远端归因(opt-in):开启后会把本机 magpie 配好的 remote provider key 发给远端 magpie
// 换逐条请求记录——必须用户显式选择,绝不默认。
let ATTRIBUTION_MODE = 'local';
// 本机直连/远端的口径:usage.jsonl 里这些 provider 线路前缀的流量记为「走远端」(其余为直连)。
// 默认只含 magpie 自己的线路名(非个人配置);个人化口径用 REMOTE_PROVIDERS 覆盖。
let REMOTE_PROVIDERS = ['magpie-direct', 'magpie-cf', 'remote-magpie'];
let REMOTE_CALLERS = [];
// Host 校验:默认只认识回环名。反代或非回环部署时用 ALLOWED_HOSTS=域名1,域名2 显式放行。
const ALLOWED_HOSTS = (process.env.ALLOWED_HOSTS || '').split(',').map((x) => x.trim().toLowerCase()).filter(Boolean);
const STATIC_DIR = path.join(ROOT, 'static');
// 品牌 logo:读 magpie 自己维护的 plugin-providers.json(插件注册 provider 时上报的 id→icon,
// data URI 为主)。零扫描、零下载、零落盘——https 图标不抓取(避免启动时向第三方 CDN 发请求),
// 页面对没有图标的品牌用首字色块兜底。
const PROVIDERS_FILE = process.env.MAGPIE_PROVIDERS_FILE || '';
const MAGPIE_PROVIDERS = process.env.MAGPIE_PROVIDERS || path.join(CONFIG_DIR, 'providers.json');
const MIME = {
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png',
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.ico': 'image/x-icon',
'.txt': 'text/plain; charset=utf-8',
};
const json = (res, code, obj) => {
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
res.end(JSON.stringify(obj));
};
async function upstream(p) {
// 瞬时网关挂起重试一次(上限 12s×2):失败已可见化(note/红条),这里只为削掉偶发抖动
let last;
for (let i = 0; i < 2; i++) {
try {
const r = await fetch(GATEWAY + p, {
headers: KEY ? { Authorization: `Bearer ${KEY}` } : {},
signal: AbortSignal.timeout(12000),
});
const body = await r.text();
try { return { code: r.status, json: JSON.parse(body) }; }
catch { return { code: r.status, json: { error: body.slice(0, 200) } }; }
} catch (e) { last = e; }
await new Promise((r2) => setTimeout(r2, 500 * (i + 1)));
}
return { code: 0, json: { error: String(last && last.message || last).slice(0, 200) } };
}
// usage.jsonl 聚合:按天×provider、7×24 热力、最近请求(60s 缓存)。
// 流式逐行读取:日志曾到 23MB,整读+全量解析把 RSS 放大 ~9 倍——现在峰值只保留聚合结果
async function* linesOf(path) {
const stream = createReadStream(path, { encoding: 'utf8' });
let buf = '';
for await (const chunk of stream) {
buf += chunk;
let i;
while ((i = buf.indexOf('\n')) >= 0) {
const line = buf.slice(0, i);
buf = buf.slice(i + 1);
if (line) yield line;
}
}
if (buf) yield buf;
}
// echarts.min.js 的预压缩缓存(按 mtime 失效):br ~172KB / gzip ~190KB,避免每次导航白拉 612KB
let echartsEnc = null;
function echartsEncoded(full) {
const mtime = statSync(full).mtimeMs;
if (!echartsEnc || echartsEnc.mtime !== mtime) {
const raw = readFileSync(full);
echartsEnc = { mtime, br: brotliCompressSync(raw), gz: gzipSync(raw, { level: 8 }) };
}
return echartsEnc;
}
let detailCache = null;
async function readDetail(days) {
const cacheKey = days + ':' + Math.floor(Date.now() / 60000);
if (detailCache && detailCache.key === cacheKey) return detailCache.data;
const since = days > 0 ? Date.now() - days * 86400e3 : 0;
const daily = new Map();
const heat = new Array(7 * 24).fill(0);
let recent = [];
try {
for await (const line of linesOf(USAGE_JSONL)) {
if (!line) continue;
let r; try { r = JSON.parse(line); } catch { continue; }
// magpie 自家探活行(kind:"model_list", source:"probe")不是真实调用,过滤(2026-11-04,实测占 9.5%)
if (r.kind === 'model_list' || r.source === 'probe') continue;
const ts = r.t ? Date.parse(r.t) : NaN;
if (!Number.isFinite(ts) || ts < since) continue;
const day = typeof r.t === 'string' ? r.t.slice(0, 10) : '';
if (!day) continue; // 脏行(t 非字符串)跳过本行,绝不静默清空整张图
const prov = r.provider || 'unknown';
let dp = daily.get(day); if (!dp) { dp = new Map(); daily.set(day, dp); }
let a = dp.get(prov);
if (!a) { a = { calls: 0, errors: 0, inp: 0, out: 0, cache: 0, reasoning: 0, ttft: 0, timed: 0 }; dp.set(prov, a); }
a.calls++; if (r.status !== 200) a.errors++;
a.inp += r.in || 0; a.out += r.out || 0; a.cache += r.cache_read || 0; a.reasoning += r.reasoning || 0;
if (r.ttft_ms > 0) { a.ttft += r.ttft_ms; a.timed++; }
if (ts >= Date.now() - 7 * 86400e3) heat[new Date(ts).getDay() * 24 + new Date(ts).getHours()]++;
if (r.status != null) {
recent.push({
t: r.t, agent: r.agent, provider: prov, model: r.served || r.model,
in: r.in || 0, out: r.out || 0, ttft: r.ttft_ms || null, ms: r.ms || null,
status: r.status, tries: r.tries || 1,
});
// recent 有界:日志按时间追加,最后 40 条即最新;超限排序截断防止长日志撑爆
if (recent.length > 80) { recent.sort((x, y) => (x.t < y.t ? 1 : -1)); recent.length = 40; }
}
}
} catch (e) {
// 读不到(ENOENT)= 全新安装的空态;其他读失败(权限/损坏)必须可见,不能伪装成零用量
if (e && e.code === 'ENOENT') return { daily: [], heat, recent: [] };
console.error('[magpie-usage] usage.jsonl read failed:', (e && e.message) || e);
return { daily: [], heat, recent: [], error: 'usage log read failed (' + ((e && e.code) || (e && e.message) || '?') + ')' };
}
recent.sort((x, y) => (x.t < y.t ? 1 : -1));
recent = recent.slice(0, 40);
const data = {
daily: [...daily.entries()].sort().map(([day, ps]) => ({
day, providers: [...ps.entries()].map(([provider, a]) => ({ provider, ...a })),
})),
heat, recent,
};
detailCache = { key: cacheKey, data };
return data;
}
// 远端归因:只有远端网关的 usage.jsonl 记着 providerAccount / callerKeyName,
// 本地那一侧一条 magpie-direct 看不出真实花在谁身上。这里按调用方把账算出来。
let attrCache = { key: '', data: null };
const pct = (arr, p) => {
if (!arr.length) return null;
const s = [...arr].sort((a, b) => a - b);
const i = Math.min(s.length - 1, Math.max(0, Math.round((p / 100) * (s.length - 1))));
return s[i];
};
// 近 24h 按小时聚合;d=直连(本机自己的 provider),r=走远端(REMOTE_PROVIDERS)
let h24Cache = { key: '', data: null };
async function readHourly24() {
const key = 'h24:' + Math.floor(Date.now() / 300000);
if (h24Cache.data && h24Cache.key === key) return h24Cache.data;
const since = Date.now() - 24 * 3600e3;
const hours = new Map();
try {
for await (const line of linesOf(USAGE_JSONL)) {
if (!line) continue;
let r; try { r = JSON.parse(line); } catch { continue; }
// magpie 自家探活行(kind:"model_list", source:"probe")不是真实调用,过滤(2026-11-04,实测占 9.5%)
if (r.kind === 'model_list' || r.source === 'probe') continue;
const ts = r.t ? Date.parse(r.t) : NaN;
if (!Number.isFinite(ts) || ts < since) continue;
const t = new Date(ts);
const hk = String(t.getMonth() + 1).padStart(2, '0') + '-' + String(t.getDate()).padStart(2, '0')
+ ' ' + String(t.getHours()).padStart(2, '0') + ':00';
let h = hours.get(hk);
if (!h) { h = { d: { calls: 0, input: 0, output: 0, cache_read: 0 }, r: { calls: 0, input: 0, output: 0, cache_read: 0 } }; hours.set(hk, h); }
const side = REMOTE_PROVIDERS.includes(r.provider || '') ? 'r' : 'd';
const b = h[side];
b.calls++; b.input += r.in || 0; b.output += r.out || 0; b.cache_read += r.cache_read || 0;
}
} catch (e) {
if (e && e.code === 'ENOENT') return { hours: [] }; // 全新安装:空态
console.error('[magpie-usage] usage.jsonl read failed (hourly):', (e && e.message) || e);
return { hours: [], error: 'usage log read failed (' + ((e && e.code) || (e && e.message) || '?') + ')' };
}
const data = { hours: [...hours.entries()].sort().map(([hour, v]) => ({ hour, ...v })) };
h24Cache = { key, data };
return data;
}
// 百分位采样:每 provider 最多 512 个样本(确定性跨步替换),长日志不会把样本数组撑爆
async function aggregateAttribution(rows, { period, days, callers, source }) {
const sampN = new Map();
const pushSample = (map, key, v, cap = 512) => {
let s = map.get(key); if (!s) { s = []; map.set(key, s); }
if (s.length < cap) { s.push(v); return; }
const c = (sampN.get(key) || 0) + 1; sampN.set(key, c);
s[c % cap] = v;
};
const since = days > 0 ? Date.now() - days * 86400e3 : 0;
const prov = new Map(), acct = new Map(), byDay = new Map(), byCaller = new Map(), hourly = new Map();
const ttftSamples = new Map(), msSamples = new Map();
const totals = { calls: 0, errors: 0, input: 0, output: 0, cache_read: 0, ttft_ms: 0, timed: 0 };
for await (const r of rows) {
if (!r) continue;
// magpie 自家探活行(kind:"model_list", source:"probe")不是真实调用,过滤
if (r.kind === 'model_list' || r.source === 'probe') continue;
// 远端 API 的 t 带 9 位小数秒,Date.parse 只认毫秒,先截断
const ts = Date.parse(String(r.t || '').replace(/(\.\d{3})\d+/, '$1'));
if (!Number.isFinite(ts) || ts < since) continue;
// 按调用方拆分:这一项不受 caller 过滤影响,前端要拿它画「本机 / remote / hermes」占比
const cn = r.callerKeyName || '(无)';
let cb = byCaller.get(cn);
if (!cb) { cb = { name: cn, calls: 0, input: 0, output: 0 }; byCaller.set(cn, cb); }
cb.calls++; cb.input += r.in || 0; cb.output += r.out || 0;
if (callers.length && !callers.includes(r.callerKeyName || '')) continue;
if (ts >= Date.now() - 24 * 3600e3) {
const t = new Date(ts);
const hk = String(t.getMonth() + 1).padStart(2, '0') + '-' + String(t.getDate()).padStart(2, '0')
+ ' ' + String(t.getHours()).padStart(2, '0') + ':00';
let hv = hourly.get(hk);
if (!hv) { hv = { calls: 0, input: 0, output: 0, cache_read: 0 }; hourly.set(hk, hv); }
hv.calls++; hv.input += r.in || 0; hv.output += r.out || 0; hv.cache_read += r.cache_read || 0;
}
const pn = r.provider || 'unknown';
const inTok = r.in || 0, outTok = r.out || 0, cache = r.cache_read || 0;
const err = r.status !== 200 ? 1 : 0;
totals.calls++; totals.errors += err;
totals.input += inTok; totals.output += outTok; totals.cache_read += cache;
if (r.ttft_ms > 0) { totals.ttft_ms += r.ttft_ms; totals.timed++; }
let a = prov.get(pn);
if (!a) { a = { provider: pn, calls: 0, errors: 0, input: 0, output: 0, cache_read: 0 }; prov.set(pn, a); }
a.calls++; a.errors += err; a.input += inTok; a.output += outTok; a.cache_read += cache;
if (r.ttft_ms > 0) pushSample(ttftSamples, pn, r.ttft_ms);
if (r.ms > 0) pushSample(msSamples, pn, r.ms);
const an = r.providerAccount || '';
if (an) {
const k = pn + '\u0000' + an;
let b = acct.get(k);
if (!b) { b = { provider: pn, account: an, calls: 0, errors: 0, input: 0, output: 0 }; acct.set(k, b); }
b.calls++; b.errors += err; b.input += inTok; b.output += outTok;
}
const day = String(r.t || '').slice(0, 10);
if (day) {
let d = byDay.get(day);
if (!d) { d = new Map(); byDay.set(day, d); }
let c = d.get(pn);
if (!c) { c = { calls: 0, input: 0, output: 0, cache_read: 0 }; d.set(pn, c); }
c.calls++; c.input += inTok; c.output += outTok; c.cache_read += cache;
}
}
const providers = [...prov.values()].sort((x, y) => y.calls - x.calls).map((p) => {
const ts = ttftSamples.get(p.provider) || [];
const ms = msSamples.get(p.provider) || [];
return {
...p,
ttft_p50: pct(ts, 50), ttft_p90: pct(ts, 90),
ttft_avg: ts.length ? ts.reduce((s, v) => s + v, 0) / ts.length : null,
ms_p50: pct(ms, 50), ms_p90: pct(ms, 90), timed: ts.length,
};
});
return {
source,
callers,
period,
since: since ? new Date(since).toISOString() : null,
totals,
providers,
accounts: [...acct.values()].sort((x, y) => y.calls - x.calls).slice(0, 30),
callerBreakdown: [...byCaller.values()].sort((x, y) => y.calls - x.calls),
days: [...byDay.entries()].sort().map(([day, m]) => ({ day, providers: Object.fromEntries(m) })),
// 远端归因的小时行按 {hour, r:{...}} 输出——页面 drawHourly 按 x.r 读取远端侧
// (扁平结构会被当成空对象,全远端出口的部署 24h 图会全 0)
hourly: [...hourly.entries()].sort().map(([hour, v]) => ({ hour, r: v })),
};
}
async function readAttribution(period, days, callers) {
// 归因数据变化很慢,5 分钟够用(看板自身也是 5 分钟自动刷新)
const bucket = Math.floor(Date.now() / (5 * 60000));
const cacheKey = 'local:' + period + ':' + callers.join(',') + ':' + bucket;
if (attrCache.data && attrCache.key === cacheKey) return attrCache.data;
async function* localRows() {
for await (const line of linesOf(USAGE_JSONL)) {
let r; try { r = JSON.parse(line); } catch { continue; }
yield r;
}
}
let data;
try { data = await aggregateAttribution(localRows(), { period, days, callers, source: 'local' }); }
catch { return null; }
attrCache = { key: cacheKey, data };
return data;
}
// 远端 magpie 的逐条请求记录:/v1/magpie/usage/requests 每行都带 callerKeyId/Name、
// provider/providerAccount、时间、TTFT。summary 端点不支持按 caller 过滤,但 rows 可以。
// 用本机 magpie 已经配好的 remote provider(providers.json)的 URL+key,不引入第二把 key。
const REMOTE_PAGE = 500, REMOTE_MAX = 40000, REMOTE_CONC = 4;
function remoteSources() {
if (ATTRIBUTION_MODE !== 'remote') return [];
const callers = REMOTE_CALLERS;
const out = [];
const push = (base, key) => {
const b = String(base || '').replace(/\/+$/, '').replace(/\/v1$/, '');
let u; try { u = new URL(b); } catch { return; }
// Bearer key 只走 https;明文 http 仅限本机回环(本地测试用)
if (u.protocol !== 'https:' && !['127.0.0.1', 'localhost', '::1'].includes(u.hostname)) return;
if (key && !out.some((x) => x.base === b && x.key === key)) out.push({ base: b, key, callers });
};
if (process.env.REMOTE_BASE && process.env.REMOTE_KEY) {
// 显式 override 独占:设置 REMOTE_BASE/KEY 时不再读 providers.json(文档承诺的语义)
push(process.env.REMOTE_BASE, process.env.REMOTE_KEY);
return out;
}
try {
const j = JSON.parse(readFileSync(MAGPIE_PROVIDERS, 'utf8'));
for (const p of j.providers || []) {
if (!p || !p.key || !/^https?:\/\//.test(String(p.chat || p.responses || ''))) continue;
if (p.preset !== 'remote-magpie' && p.id !== 'magpie-direct' && p.id !== 'magpie-cf') continue;
push(p.chat || p.responses, p.key);
}
} catch {}
return out;
}
let lastGoodRemote = null;
function orderedSources() {
const list = remoteSources();
if (lastGoodRemote) {
const i = list.findIndex((x) => x.base === lastGoodRemote.base && x.key === lastGoodRemote.key);
if (i > 0) list.unshift(list.splice(i, 1)[0]);
}
return list;
}
async function remotePage(src, period, offset) {
const u = src.base + '/v1/magpie/usage/requests?period=' + encodeURIComponent(period)
+ '&limit=' + REMOTE_PAGE + '&offset=' + offset;
let last;
for (let i = 0; i < 2; i++) {
try {
const r = await fetch(u, { headers: { Authorization: 'Bearer ' + src.key }, signal: AbortSignal.timeout(10000) });
if (r.ok) return r.json();
last = new Error('remote usage/requests ' + r.status);
if (r.status < 500) break;
} catch (e) { last = e; }
await new Promise((r) => setTimeout(r, 600 * (i + 1)));
}
throw last || new Error('remote usage/requests failed');
}
async function fetchRemoteRows(src, period, first) {
const rows = [...((first && first.rows) || [])];
const total = Number(first.total) || rows.length;
let offset = rows.length;
const t0 = Date.now();
while (offset < total && rows.length < REMOTE_MAX) {
// 远端分页总时限:provider key 是真实凭据,拉取不能无上限(前端 45s 会先行放弃)
if (Date.now() - t0 > 40000) break;
const offsets = [];
for (let i = 0; i < REMOTE_CONC; i++) {
const o = offset + i * REMOTE_PAGE;
if (o >= total || rows.length + offsets.length * REMOTE_PAGE >= REMOTE_MAX) break;
offsets.push(o);
}
if (!offsets.length) break;
const pages = await Promise.all(offsets.map((o) => remotePage(src, period, o)));
for (const page of pages) rows.push(...(page.rows || []));
offset = offsets[offsets.length - 1] + REMOTE_PAGE;
}
return rows;
}
async function readRemoteAttribution(period, days, callers, sources) {
const bucket = Math.floor(Date.now() / (5 * 60000));
const suffix = ':' + period + ':' + callers.join(',') + ':' + bucket;
if (attrCache.data && attrCache.key.startsWith('remote:') && attrCache.key.endsWith(suffix)) return attrCache.data;
// 上次成功的源优先;首次或失败时并发要首页,谁先回用谁,剩下的页只走这个源。
let picked = null;
if (lastGoodRemote && sources.some((s) => s.base === lastGoodRemote.base && s.key === lastGoodRemote.key)) {
try { picked = { src: lastGoodRemote, page: await remotePage(lastGoodRemote, period, 0) }; }
catch { lastGoodRemote = null; }
}
if (!picked) {
try {
picked = await Promise.any(sources.map(async (src) => ({ src, page: await remotePage(src, period, 0) })));
} catch (e) {
const why = (e && e.errors ? e.errors.map((x) => x && x.message).filter(Boolean).join('; ') : String(e && e.message || e));
throw new Error(why || 'all remote sources failed');
}
}
lastGoodRemote = picked.src;
const rows = await fetchRemoteRows(picked.src, period, picked.page);
const data = await aggregateAttribution(rows, { period, days, callers, source: 'remote' });
attrCache = { key: 'remote:' + picked.src.base + suffix, data };
return data;
}
function sameKey(given) {
// 先比字节长度:JS 字符串长度 ≠ 字节长(非 ASCII 自定义 key 曾让 timingSafeEqual 抛错→鉴权全 500)
if (typeof given !== 'string' || Buffer.byteLength(given) !== Buffer.byteLength(PAGE_KEY)) return false;
return timingSafeEqual(Buffer.from(given), Buffer.from(PAGE_KEY));
}
function authed(req) {
if (!PAGE_KEY) return true;
// 口令只走 x-dash-key 头:?key= 已废除(key 一旦进 URL 就会落进代理/历史记录),
// 浏览器端由服务端注入 HTML 的脚本带着头调 API,脚本调用方显式设 PAGE_KEY。
return sameKey(String(req.headers['x-dash-key'] || ''));
}
// 防 DNS rebinding:只接受本机回环名 / 本机网卡地址 / ALLOWED_HOSTS 里的名字。
// 回环名不看端口(Docker 端口映射、ssh 隧道的外部端口与监听口必然不同,而
// rebinding 的威胁在域名不在端口);非回环名的端口必须是本进程监听口,
// 除非名字进了 ALLOWED_HOSTS(反代常把 Host 写成 domain:443)。
function hostAllowed(req) {
const raw = String(req.headers.host || '').toLowerCase();
if (!raw) return false;
const m = raw.match(/^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/);
if (!m) return false;
const name = m[1];
const port = Number(m[2] || 0);
const bound = server.address()?.port || 0;
// 显式白名单优先(反代常把 Host 写成 domain:443,端口与本机监听口不同)
if (ALLOWED_HOSTS.includes(name) || ALLOWED_HOSTS.includes(raw)) return true;
if (name === '127.0.0.1' || name === 'localhost' || name === '[::1]') return true;
if (port && bound && port !== bound) return false;
if (HOST !== '127.0.0.1' && HOST !== 'localhost' && HOST !== '::1') {
if (name === HOST.toLowerCase()) return true;
for (const list of Object.values(os.networkInterfaces())) {
for (const a of list || []) if (a.address.toLowerCase() === name) return true;
}
}
return false;
}
function secHeaders(res) {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Referrer-Policy', 'no-referrer');
}
// 页面 HTML 的跨源读取:沙盒 frame 是 opaque origin(null),顶层导航没有 Origin;
// 其它网站发来的 Origin 一律拒绝,避免它们 fetch 到注入口令的页面。
// 本机 origin 只认「本进程实际监听口」——任意 localhost 端口不放行。
function originOk(req, boundPort) {
const o = req.headers.origin;
if (!o || o === 'null') return true;
return loopbackOrigin(o, boundPort);
}
function loopbackOrigin(o, boundPort) {
if (!boundPort) return false;
return o === `http://127.0.0.1:${boundPort}`
|| o === `http://localhost:${boundPort}`
|| o === `http://[::1]:${boundPort}`;
}
// 沙盒 frame(插件页面导航过来,opaque origin)跨源 fetch:允许 Origin: null,
// key 走 x-dash-key 头(opaque origin 无 cookie)。其它 origin 一律不给 ACAO——
// 页面是这份服务的唯一客户端,本机其它端口的页面也不例外。
function cors(req, res) {
const o = req.headers.origin;
const allow = (v) => {
res.setHeader('Access-Control-Allow-Origin', v);
res.setHeader('Vary', 'Origin');
return true;
};
if (o === undefined || o === 'null') return allow('null');
if (loopbackOrigin(o, server.address()?.port || 0)) return allow(o);
return false;
}
// 请求处理主体(原 handler 体):任何未捕获异常都由下方 createServer 的 .catch
// 兜底成 500,进程必须存活、继续服务下一个请求。
async function handleRequest(req, res, url) {
const p = url.pathname;
secHeaders(res);
if (!hostAllowed(req)) {
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
return res.end('invalid host');
}
console.log(`[req] ${req.method} ${p} origin=${req.headers.origin || '-'} xdk=${req.headers['x-dash-key'] ? 'yes' : 'no'}`);
if (p.startsWith('/api/')) {
// 免鉴权实例指纹:同款服务复用判定用;只报身份,不泄露网关/口令
if (p === '/api/ping') return json(res, 200, { service: 'magpie-usage-board', ok: true, build: BUILD_ID, version: VERSION });
if (req.method === 'OPTIONS') {
if (!cors(req, res)) { res.writeHead(403); return res.end(); }
res.writeHead(204, {
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'x-dash-key',
'Access-Control-Max-Age': '86400',
});
return res.end();
}
if (!cors(req, res)) { res.writeHead(403); return res.end('cross-origin reads not allowed'); }
// health 免鉴权:探活与实例识别都依赖匿名访问(响应里无口令、无用量数据)
if (p === '/api/health') return json(res, 200, { ok: true, jsonl: existsSync(USAGE_JSONL) });
if (!authed(req)) return json(res, 401, { error: 'unauthorized: send the x-dash-key header' });
try {
if (p === '/api/quotas') {
const [r, lim] = await Promise.all([
upstream('/v1/magpie/quotas'),
upstream('/v1/magpie/limit?format=json').catch(() => null),
]);
const out = { ...r.json };
// magpie 0.1.2981+ 的 /v1/magpie/limit:报告本 caller key 当前被什么 holds(limited/key)
if (lim && lim.code === 200 && lim.json && typeof lim.json === 'object') out.limit = lim.json;
// code 0 = 网关无响应(upstream 内部已重试):writeHead(0) 会 RangeError 并吞掉真实原因
const status = r.code >= 400 && r.code <= 599 ? r.code : r.code === 200 ? 200 : 502;
return json(res, status, out);
}
if (p === '/api/overview') {
const period = ['7d', '30d', 'all'].includes(url.searchParams.get('period')) ? url.searchParams.get('period') : '30d';
const days = period === '7d' ? 7 : period === '30d' ? 30 : 0;
// 网关挂起/失败不拖垮本地数据:usage/limit 失败 → null + note,本地日志聚合照常返回
const [u, lim] = await Promise.all([
upstream('/v1/magpie/usage?period=' + period).catch(() => ({ code: 0, json: null })),
upstream('/v1/magpie/limit?format=json').catch(() => null),
]);
const detail = await readDetail(days);
const notes = [u.code === 200 ? undefined : 'usage API ' + (u.code || 'no response'), detail && detail.error].filter(Boolean);
return json(res, 200, { period, usage: u.code === 200 ? u.json : null, detail,
limit: (lim && lim.code === 200 && lim.json) || undefined,
note: notes.length ? notes.join(';') : undefined });
}
// /api/icon/ 已退役(2026-11-04):前端 logo 全走 QLOGOS manifest,仅 README 提及历史
if (p === '/api/hourly') {
const data = await readHourly24();
return json(res, 200, data);
}
if (p === '/api/attribution') {
const period = ['7d', '30d', 'all'].includes(url.searchParams.get('period')) ? url.searchParams.get('period') : '30d';
const days = period === '7d' ? 7 : period === '30d' ? 30 : 0;
// 本机 magpie 配了 remote provider 时,归因直接问远端 magpie 的 usage/requests,
// 用已有的 provider key,按 caller 过滤;否则退回本机 usage.jsonl(VPS standalone)。
const sources = orderedSources();
if (sources.length) {
try {
const data = await readRemoteAttribution(period, days, sources[0].callers, sources);
return json(res, 200, data);
} catch (e) {
return json(res, 502, { error: 'remote attribution: ' + String(e && e.message || e) });
}
}
const callers = (url.searchParams.get('caller') || '').split(',').map((x) => x.trim()).filter(Boolean);
const data = await readAttribution(period, days, callers);
if (!data) return json(res, 503, { error: 'usage.jsonl not readable' });
return json(res, 200, data);
}
return json(res, 404, { error: 'not found' });
} catch (e) {
return json(res, 502, { error: String(e && e.message || e) });
}
}
let file = p === '/' ? '/index.html' : p;
if (file.startsWith('/static/')) file = file.slice('/static'.length);
// 静态资源全部来自包内 static/;品牌 logo 不再有独立路由(data URI 注入 window.QLOGOS)
const base = STATIC_DIR;
const full = path.resolve(base, '.' + file);
const rel = path.relative(base, full);
let isFile = false;
try { isFile = !rel.startsWith('..') && !path.isAbsolute(rel) && statSync(full).isFile(); } catch {}
if (!isFile) { res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }); return res.end('not found'); }
// 页面本身不要求口令(与社区 page-usage-tree 一致):回环绑定直接返回看板,
// 由服务端把口令注入 HTML;公网绑定仍要求口令,避免把数据和口令交给匿名访问者。
// 这只拦跨源 fetch(Origin 非空且不是本机),顶层导航不带 Origin,不受影响。
// 看板页面是这份服务的唯一客户端:回环绑定时一律注入口令返回(本机用户即所有者,
// 顶层/沙盒 frame 导航都不带 Origin;与社区 page-usage-tree 同一模型,桌面宿主
// 不需要任何环境变量)。非回环绑定不开放页面——?key= 已废除,远程访问者没有
// 认证通道;脚本调用走 x-dash-key 头。
if (file === '/index.html') {
if (!originOk(req, server.address()?.port || 0)) {
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
return res.end('cross-origin page read not allowed');
}
if (!LOOPBACK_BIND) {
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
return res.end('the board page is loopback-only; APIs accept the x-dash-key header');
}
// 页面还要求 Host 是回环名:反代把公共域名(ALLOWED_HOSTS 放行的 Host)转发进来时,
// 页面不随之开放——公网访问者只能拿 403;API 走 x-dash-key 头仍可用(P1 回归)。
const hostName = (String(req.headers.host || '').toLowerCase().match(/^(\[[^\]]+\]|[^:]+)/) || [])[1] || '';
if (!['127.0.0.1', 'localhost', '[::1]'].includes(hostName)) {
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
return res.end('the board page answers loopback hosts only');
}
}
// 首页:服务端把数据直接内联进 HTML(window.__DATA__),页面加载即有数据,
// 不发任何 fetch——沙盒 frame(opaque origin)里跨源 fetch 会被浏览器/
// 中间层拦成 "Failed to fetch",这是实测结论;同帧内联是唯一稳路。
if (file === '/index.html') {
let html = await readFile(full, 'utf8');
let data = null, note = '';
try {
const period = ['7d', '30d', 'all'].includes(url.searchParams.get('period')) ? url.searchParams.get('period') : '30d';
const days = period === '7d' ? 7 : period === '30d' ? 30 : 0;
const [u, detail, q] = await Promise.all([
upstream('/v1/magpie/usage?period=' + period),
readDetail(days),
upstream('/v1/magpie/quotas'),
]);
data = { period, usage: u.json, quotas: q.json?.data || [], detail };
if (u.code !== 200) note = 'usage API ' + u.code;
} catch (e) { note = String(e && e.message || e); }
const trap = '<script>window.__errs=[];window.addEventListener("error",function(e){var m=e.message||((e.target&&e.target.src||e.target&&e.target.href)?("resource: "+(e.target.src||e.target.href)):"");if(!m)return;window.__errs.push(m+" @ "+(e.filename||"")+":"+(e.lineno||0)+":"+(e.colno||0))},true);window.addEventListener("unhandledrejection",function(e){window.__errs.push("PROMISE: "+String(e.reason&&e.reason.message||e.reason))});<\/script>';
// 品牌 logo 映射 = magpie 自己的 plugin-providers.json(data URI,启动时读一次)
const inject = `<script>window.__DATA__=${JSON.stringify(data).replace(/</g, '\\u003c')};window.__NOTE__=${JSON.stringify(note)};window.QLOGOS=${JSON.stringify(providerLogos).replace(/</g, '\\u003c')};window.__BUILD__=${JSON.stringify(`${VERSION}/${BUILD_ID}`)};</script>`;
// 页面需要的口令只出现在这份 HTML 里;API 路由仍校验它,URL/书签里不出现
const keyInject = PAGE_KEY ? `<script>window.__KEY__=${JSON.stringify(PAGE_KEY).replace(/</g, '\\u003c')};</script>` : '';
html = html.replace('<head>', () => '<head>' + keyInject + trap + inject);
const boundPort = server.address()?.port || 0;
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'no-store',
// 页面脚本全是同源文件 + 少量内联(数据注入);数据获取全部同源 /api/*。
// connect-src 除 'self' 外显式列出本机回环地址——WebKit 的沙盒 frame(opaque
// origin)会把 'self' 解析成 opaque,同源 fetch 被拦,显式地址实测可行。
// frame-ancestors:看板本来就是被 magpie 的框架嵌入的(桌面/webview/web 的宿主
// origin 不固定,收不了紧)——显式写 * 表明「被宿主嵌入是设计意图」,而不是遗漏。
'Content-Security-Policy': `default-src 'self' data:; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' http://127.0.0.1:${boundPort} http://localhost:${boundPort}; object-src 'none'; base-uri 'none'; frame-ancestors *`,
});
return res.end(html);
}
const heads = { 'Content-Type': MIME[path.extname(full).toLowerCase()] || 'application/octet-stream', 'Cache-Control': 'no-store' };
// echarts.min.js:URL 带 ?v= 构建戳(内容变更即换 URL)→ 长缓存;按 Accept-Encoding 供
// 启动时预压缩的 br/gzip 版本(612KB → br ~172KB),避免每次导航白拉全量
if (file === '/echarts.min.js') {
heads['Cache-Control'] = 'public, max-age=31536000, immutable';
const enc = echartsEncoded(full);
const ae = String(req.headers['accept-encoding'] || '');
if (/\bbr\b/.test(ae)) { heads['Content-Encoding'] = 'br'; heads['Content-Length'] = String(enc.br.length); heads['Vary'] = 'Accept-Encoding'; res.writeHead(200, heads); return res.end(enc.br); }
if (/\bgzip\b/.test(ae)) { heads['Content-Encoding'] = 'gzip'; heads['Content-Length'] = String(enc.gz.length); heads['Vary'] = 'Accept-Encoding'; res.writeHead(200, heads); return res.end(enc.gz); }
}
if (file.endsWith('.svg')) heads['Content-Security-Policy'] = 'sandbox'; // SVG 可内嵌脚本:被直接打开时整页隔离
res.writeHead(200, heads);
res.end(await readFile(full));
}
const server = createServer((req, res) => {
// 畸形请求目标(如 GET // HTTP/1.1)会让 new URL 抛 Invalid URL:单独 try/catch
// 拦下直接 400,不进入 Host 校验/鉴权/任何业务逻辑(P0 修复:原实现无容错,
// 任意外部请求即可打死进程)。
let url;
try {
url = new URL(req.url, 'http://x');
} catch {
res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
return res.end('bad request');
}
handleRequest(req, res, url).catch((e) => {
// 最外层兜底:任何未捕获异常 → 500,固定文案(不带堆栈与内部错误细节),进程继续服务
console.log(`[magpie-usage] handler error: ${e && e.message || e}`);
if (!res.headersSent) {
res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('internal server error');
} else { try { res.end(); } catch {} }
});
});
// 最后防线:unhandledRejection 只记日志、不退出进程(Node/Bun 默认会终止进程),
// 兜住请求处理之外(定时器、fire-and-forget fetch 等)的意外拒绝。
process.on('unhandledRejection', (e) => {
console.log(`[magpie-usage] unhandled rejection: ${e && e.message || e}`);
});
// ---- 启动 ----
// 构建指纹:版本号 + 运行时文件哈希。端口被占时用 /api/ping 互认——只有「同一份代码」
// 的实例才允许复用(旧版本/别的构建一律报错,绝不把看板交给一个未知进程)。
const VERSION = (() => {
try { const v = JSON.parse(readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version; return typeof v === 'string' ? v : '0'; } catch { return '0'; }
})();
const BUILD_FILES = ['server.mjs', 'index.mjs', 'package.json', 'static/index.html', 'static/echarts.min.js', 'page/index.html', 'page/boot.js'];
const BUILD_ID = (() => {
try {
const h = createHash('sha256');
for (const f of BUILD_FILES) { h.update(f); h.update('\0'); h.update(readFileSync(path.join(ROOT, f))); }
return h.digest('hex').slice(0, 16);
} catch { return 'ver:' + VERSION; }
})();
// 占用端口的是不是本构建的实例:/api/ping 匿名报身份(无口令、无数据),同构建才复用。
async function probe(hp) {
try {
const j = await (await fetch(`http://${hp}/api/ping`, { signal: AbortSignal.timeout(1200) })).json();
if (j && j.service === 'magpie-usage-board') return { build: String(j.build || ''), version: String(j.version || '') };
} catch {}
return null;
}
// 品牌 logo:读 magpie 自己维护的 plugin-providers.json(插件注册 provider 时上报的
// id→icon,data URI 为主)。只取 data URI(≤2MB);https 图标一律不抓取——那会让本机
// 服务在启动时向第三方 CDN 发起用户不可见的请求。页面 brandIcon() 的别名/去后缀兜底链
// 在前端保持不变,未命中品牌走首字色块。
let providerLogos = {};
function loadProviderLogos() {
const f = PROVIDERS_FILE || path.join(CONFIG_DIR, 'plugin-providers.json');
try {
const j = JSON.parse(readFileSync(f, 'utf8'));
const out = {};
let total = 0;
for (const p of Object.values(j)) {
const id = p && typeof p.id === 'string' ? p.id.toLowerCase() : '';
const icon = p && typeof p.icon === 'string' ? p.icon : '';
if (!id || !icon.startsWith('data:image/')) continue;
const comma = icon.indexOf(',');
if (comma <= 0 || icon.length - comma > 2 * 1024 * 1024) continue; // 解码前 2MB 上限
if (out[id] === undefined) { out[id] = icon; total += icon.length; }
if (total > 4 * 1024 * 1024) break; // 注入 HTML 的总体积上限
}
providerLogos = out;
console.log(`[magpie-usage] logos: ${Object.keys(out).length} brands from ${f}`);
} catch (e) {
console.log(`[magpie-usage] logos: plugin-providers.json not readable (${(e && e.code) || (e && e.message) || e}) — badges only`);
}
}
function main(resolve, reject) {
// 口令定稿(listen 前):显式 PAGE_KEY 环境变量优先(空串=API 开放;页面门禁只看回环
// 绑定,不受它影响);未设 → 每次启动生成随机 token——页面 HTML 由服务端注入,URL、
// 日志、磁盘都不落。复用同构建实例时无需互通口令:页面由持有端口的实例自己服务。
const envKey = process.env.PAGE_KEY;
if (envKey !== undefined) PAGE_KEY = envKey;
else PAGE_KEY = randomBytes(24).toString('base64url');
// 配置定稿:manifest options(index.mjs 传入)→ 环境变量 → 内置默认
const optStr = (o, env, dft) => { const v = o === undefined || o === null || o === '' ? env : o; return v === undefined || v === null || v === '' ? dft : String(v); };
const attr = optStr(CFG.attribution, process.env.ATTRIBUTION, 'local').toLowerCase();
// 远端归因 opt-in:只有显式 remote(auto 为兼容别名)才启用——它会拿本机配好的
// remote provider key 去查远端 magpie 的请求明细。
ATTRIBUTION_MODE = attr === 'remote' || attr === 'auto' ? 'remote' : 'local';
REMOTE_CALLERS = optStr(CFG.remoteCallers, process.env.REMOTE_CALLERS, '').split(',').map((x) => x.trim()).filter(Boolean);
REMOTE_PROVIDERS = optStr(CFG.remoteProviders, process.env.REMOTE_PROVIDERS, 'magpie-direct,magpie-cf,remote-magpie').split(',').map((x) => x.trim()).filter(Boolean);
// 网关按链路解析(options → GATEWAY → MAGPIE_GATEWAY → MAGPIE_ADDR → 3425):宿主把
// MAGPIE_ADDR 指到哪,看板就问哪——端口改过/便携安装时写死 3425 会全盘落空。
GATEWAY = gatewayCandidates(CFG.gateway)[0];
loadProviderLogos();
let startPort = null;
const rawPort = CFG.port ?? process.env.PORT;
if (rawPort !== undefined && rawPort !== null && rawPort !== '') {
const n = Number(rawPort);
if (!Number.isInteger(n) || n < 0 || n > 65535) {
const err = new Error(`invalid PORT=${rawPort} — must be an integer 0-65535`);
console.error(`[magpie-usage] ${err.message}`);
reject(err);
return;
}
startPort = n;
}
// 端口语义(与社区 page-usage-tree 一致):目标口 = 显式 PORT / manifest options.port,
// 否则 PORT_BASE。空闲 → 绑定;被占 → 短重试(宿主重启时上一代濒死,通常一秒内释放);
// 仍被占 → /api/ping 指纹互认:同一份代码(BUILD_ID 一致)→ 二次确认活着后复用;
// 异构建或异种进程 → 明确报错。绝不向上扫描——带路页从 manifest options 读到的端口
// 必须与绑定口一致,扫上去页面也连不上。
const target = startPort === null ? PORT_BASE : startPort;
const deadline = Date.now() + 8000;
const attempt = async () => {
const bound = await bindOnce(target);
if (bound) return;
const st = await probe(`${URL_HOST}:${target}`);
if (st && st.build === BUILD_ID) {
// 濒死实例也能应答单次探测:1.5s 后仍活着才复用;死了就继续等端口释放
const confirm = await new Promise((r2) => setTimeout(() => probe(`${URL_HOST}:${target}`).then(r2, () => r2(null)), 1500));
if (confirm && confirm.build === BUILD_ID) {
console.log(`[magpie-usage] port ${target} in use by the same build (${BUILD_ID}) — reusing it`);
resolve(target);
return;
}
}
if (Date.now() < deadline) { setTimeout(attempt, 150); return; }
reject(new Error(st
? `port ${target} is held by another build of this board (build ${st.build || 'unknown'}) — free it or set PORT`
: `port ${target} is in use and not by this board — free it or set PORT`));
};
attempt();
function bindOnce(p) {
return new Promise((res) => {
const onListen = () => { cleanup(); finish2(server.address().port); res(true); };
const onErr = (e) => {
cleanup();
if (e.code !== 'EADDRINUSE' && e.code !== 'EACCES') {
console.log(`[magpie-usage] not started: ${e.code || e.message}`);
reject(new Error(`not started: ${e.code || e.message}`));
res(true); // 已 reject,外层不必重试
return;
}
res(false);
};
const cleanup = () => { server.off('listening', onListen); server.off('error', onErr); };
server.once('listening', onListen);
server.once('error', onErr);
server.listen(p, HOST);
});
}
// open 日志:URL 永不带口令(?key= 已废除)——回环绑定页面免口令,非回环绑定
// 页面不开放、API 用 x-dash-key 头。
function openUrl(port) {
const base = `http://${URL_HOST}:${port}/`;
if (!LOOPBACK_BIND) return `${base}(页面仅本机可开;API 请求带 x-dash-key 头)`;
return base;
}
function finish2(port) {
console.log(`[magpie-usage] listening on http://${URL_HOST}:${port}/ gateway=${GATEWAY} jsonl=${USAGE_JSONL}(${existsSync(USAGE_JSONL) ? 'ok' : 'missing'}) attribution=${ATTRIBUTION_MODE} build=${BUILD_ID}`);
console.log(`[magpie-usage] open ${openUrl(port)}`);
server.on('error', (e) => console.log(`[magpie-usage] server error: ${e.message}`)); // 绑定后的常驻兜底
resolve(port);
}
}
let bootPromise = null;
// 返回 Promise:resolve 于首次成功监听(或确认复用同构建实例),reject 于终态启动失败。
// index.mjs 的 server() 会 await 它——magpie 在 server() 返回后立刻探测服务端口,
// 「发射后不管」会让那次探测吃 connection refused(社区生命周期契约)。
function startServer(options = {}) {
if (bootPromise) return bootPromise;
// manifest options 三级回退的第一级;startServer() 已启动过则忽略(bootPromise 复用)。
// port 0 = 由系统挑随机口(测试与嵌入场景);index.mjs 会把 options.port 的 0/非法值
// 归成 undefined 落到默认口,页面从同一 options 读到的值与服务保持一致。
CFG.port = options && Number.isFinite(Number(options.port)) ? Number(options.port) : null;
CFG.attribution = options ? options.attribution : null;
CFG.remoteCallers = options ? options.remoteCallers : null;
CFG.remoteProviders = options ? options.remoteProviders : null;
CFG.gateway = options ? options.gateway : null;
bootPromise = new Promise((resolve, reject) => {
try {
main(resolve, reject);
} catch (e) { reject(e); }
});
bootPromise.catch(() => { bootPromise = null; }); // 失败不缓存:下一次 server() 调用重试
return bootPromise;
}
export { startServer, aggregateAttribution };
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
startServer().catch((e) => { console.error(`[magpie-usage] not started: ${e.message}`); process.exit(1); });
}
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,39 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { aggregateAttribution } from '../server.mjs';
const now = new Date();
const iso = (msAgo) => new Date(now.getTime() - msAgo).toISOString();
test('filters attribution by caller but keeps the caller breakdown', async () => {
const rows = [
{ t: iso(0), callerKeyName: 'cloud', provider: 'codearts', providerAccount: 'a', in: 10, out: 5, cache_read: 1, status: 200, ttft_ms: 100, ms: 200 },
{ t: iso(2 * 3600e3), callerKeyName: 'Magpie', provider: 'trae-cn', providerAccount: 'b', in: 20, out: 10, status: 500, ttft_ms: 0, ms: 0 },
{ t: iso(0), callerKeyName: 'hermes', provider: 'nvidia', providerAccount: 'c', in: 1, out: 1, status: 200, ttft_ms: 50, ms: 60 },
{ t: iso(10 * 86400e3), callerKeyName: 'cloud', provider: 'old-provider', providerAccount: 'd', in: 1, out: 1, status: 200, ttft_ms: 10, ms: 10 },
];
const d = await aggregateAttribution(rows, { period: '7d', days: 7, callers: ['cloud', 'Magpie'], source: 'remote' });
assert.equal(d.source, 'remote');
assert.deepEqual(d.callers, ['cloud', 'Magpie']);
assert.equal(d.totals.calls, 2);
assert.equal(d.totals.errors, 1);
assert.equal(d.totals.input, 30);
assert.equal(d.totals.output, 15);
assert.deepEqual(d.providers.map((p) => p.provider).sort(), ['codearts', 'trae-cn']);
assert.deepEqual(d.accounts.map((a) => a.account).sort(), ['a', 'b']);
// hermes is excluded from the device's charts but still shown in the caller breakdown
assert.deepEqual(d.callerBreakdown.map((c) => c.name).sort(), ['Magpie', 'cloud', 'hermes']);
assert.equal(d.callerBreakdown.find((c) => c.name === 'hermes').calls, 1);
// 10 days old is outside a 7-day window
assert.equal(d.providers.some((p) => p.provider === 'old-provider'), false);
// hourly is caller-filtered too (2 calls: cloud + Magpie, not hermes); rows are {hour, r:{...}}
assert.equal(d.hourly.reduce((s, h) => s + h.r.calls, 0), 2);
assert.ok(d.days.length >= 1);
});
test('local source is marked so the page can hide remote cards', async () => {
const d = await aggregateAttribution([], { period: '7d', days: 7, callers: [], source: 'local' });
assert.equal(d.source, 'local');
assert.equal(d.totals.calls, 0);
});
@@ -0,0 +1,630 @@
import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { spawn, spawnSync } from 'node:child_process';
import net from 'node:net';
import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
// 所有路径都从本测试文件定位(root bun test 从仓库根跑时 cwd 不同也能工作);
// 子进程一律 -e + 绝对 URL 导入;端口一律临时申请,不用固定口。
// spawn 目标:本测试在 bun test 下也会被跑(社区根仓库 bun test 扫全部包),
// 子进程一律 spawn process.execPath(bun test 下就是 bun——magpie 宿主也正是用 bun 跑
// server.mjs 的;node --test 下就是 node)。绝不按名字 spawn "node":根仓库 bun test
// 所有包共用一个进程,某些包的测试会清空 process.env.PATH(gcp-ai),按名字找可执行
// 文件会 "Executable not found"。内联脚本的 -e 子进程改为写临时 .mjs 文件——bun 的 -e
// 兼容性不承诺,文件形式两种运行时行为一致。
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const RUNTIME = process.execPath;
const SERVER_URL = pathToFileURL(path.join(root, 'server.mjs')).href;
const INDEX_URL = pathToFileURL(path.join(root, 'index.mjs')).href;
const TEST_KEY = 'test-page-key';
let tmp;
let child;
let port;
let publicChild;
let publicPort;
const baseEnv = (dir = os.tmpdir()) => ({
...process.env,
PAGE_KEY: TEST_KEY,
USAGE_JSONL: path.join(dir, 'usage.jsonl'),
GATEWAY: 'http://127.0.0.1:9',
ATTRIBUTION: 'local',
MAGPIE_PROVIDERS: path.join(dir, 'no-providers.json'),
MAGPIE_PROVIDERS_FILE: path.join(dir, 'no-plugin-providers.json'),
});
// 内联脚本子进程:代码写进临时 .mjs 文件再跑(跨 node/bun 一致),结束即清理。
// 返回 { code, out };killMs 到点强杀防止挂死 runner。
function spawnChild(code, env, killMs = 25000) {
return new Promise((resolve) => {
const dir = mkdtempSync(path.join(os.tmpdir(), 'usage-board-child-'));
const file = path.join(dir, 'child.mjs');
writeFileSync(file, code);
const c = spawn(RUNTIME, [file], { env, stdio: ['ignore', 'pipe', 'pipe'] });
let out = '';
c.stdout.on('data', (d) => { out += d; });
c.stderr.on('data', (d) => { out += d; });
const t = setTimeout(() => c.kill('SIGKILL'), killMs);
c.once('close', (code2) => {
clearTimeout(t);
try { rmSync(dir, { recursive: true, force: true }); } catch {}
resolve({ code: code2, out });
});
});
}
function start(extra = {}) {
const dir = mkdtempSync(path.join(os.tmpdir(), 'usage-board-'));
writeFileSync(path.join(dir, 'usage.jsonl'), '');
const c = spawn(RUNTIME, [path.join(root, 'server.mjs')], {
env: { ...baseEnv(dir), HOST: '127.0.0.1', PORT: '0', ...extra },
stdio: ['ignore', 'pipe', 'pipe'],
});
const captured = { out: '' }; // 子进程完整 stdout+stderr,供启动日志断言
const ready = new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('server did not start')), 10000);
c.stdout.on('data', (d) => {
captured.out += d.toString();
const m = captured.out.match(/listening on http:\/\/127\.0\.0\.1:(\d+)\//);
if (m) { clearTimeout(timer); resolve(Number(m[1])); }
});
c.stderr.on('data', (d) => { captured.out += d.toString(); });
c.once('exit', (code) => { clearTimeout(timer); reject(new Error(`server exited ${code}: ${captured.out}`)); });
});
return { c, dir, ready, captured };
}
function request(atPort, pathname, { headers = {}, method = 'GET' } = {}) {
return new Promise((resolve, reject) => {
const r = http.request({
host: '127.0.0.1',
port: atPort,
path: pathname,
method,
headers: { Host: `127.0.0.1:${atPort}`, ...headers },
}, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (d) => { body += d; });
res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body }));
});
r.on('error', reject);
r.end();
});
}
async function waitFor(cond, ms = 3000) {
const end = Date.now() + ms;
while (!cond()) {
if (Date.now() > end) return;
await new Promise((r) => setTimeout(r, 25));
}
}
// 申请一个当前空闲的端口:bind 0 → 记下端口 → 立刻关闭(测试进程间传递用)
function freePort() {
return new Promise((resolve, reject) => {
const s = net.createServer();
s.once('error', reject);
s.listen(0, '127.0.0.1', () => {
const p = s.address().port;
s.close(() => resolve(p));
});
});
}
let mainLog;
before(async () => {
const s = start();
child = s.c;
tmp = s.dir;
mainLog = s.captured;
port = await s.ready;
});
after(() => {
child?.kill();
publicChild?.kill();
try { rmSync(tmp, { recursive: true, force: true }); } catch {}
});
test('rejects a foreign Host header (DNS rebinding)', async () => {
const r = await request(port, '/api/ping', { headers: { Host: 'evil.example' } });
assert.equal(r.status, 403);
});
test('accepts a loopback Host with a mapped port (reverse proxy / tunnel)', async () => {
// 回环名不看端口:反代/隧道发布口与服务监听口可以不同,rebinding 威胁在域名
const r = await request(port, '/api/ping', { headers: { Host: `127.0.0.1:${port + 1}` } });
assert.equal(r.status, 200);
});
test('rejects a non-loopback Host with the wrong port', async () => {
const lan = Object.values(os.networkInterfaces()).flat()
.find((a) => a && !a.internal && a.family === 'IPv4' && a.address);
if (!lan) return; // 无局域网地址的环境(部分 CI 容器)跳过端口分支
const r = await request(port, '/api/ping', { headers: { Host: `${lan}:${port + 1}` } });
assert.equal(r.status, 403);
});
test('a malformed request target is answered 400 and the process survives', async () => {
// GET // 让 new URL 抛 Invalid URL:必须拿到 4xx,且进程不退出(P0 回归测试)
const r = await request(port, '//');
assert.equal(r.status, 400);
const h = await request(port, '/api/health');
assert.equal(h.status, 200);
});
test('startup logs never contain the page key and never offer ?key=', async () => {
// 等 finish2 的 open 行写出后再断言(listening 行先到,open 行同 tick 跟随)
await waitFor(() => mainLog.out.includes('[magpie-usage] open '));
assert.doesNotMatch(mainLog.out, /\?key=/);
assert.ok(!mainLog.out.includes(TEST_KEY), 'startup log leaked the page key');
});
test('instance fingerprint stays anonymous but carries the build id', async () => {
const r = await request(port, '/api/ping');
assert.equal(r.status, 200);
const j = JSON.parse(r.body);
assert.equal(j.service, 'magpie-usage-board');
assert.equal(j.ok, true);
assert.match(j.build, /^[0-9a-f]{16}$/);
assert.ok(j.version);
});
test('API needs the token', async () => {
const r = await request(port, '/api/overview');
assert.equal(r.status, 401);
});
test('the key never works from a URL (?key= is gone)', async () => {
// key 一旦进 URL 就会落进代理日志/浏览器历史——查询串鉴权必须彻底无效
const r = await request(port, `/api/overview?key=${TEST_KEY}`);
assert.equal(r.status, 401);
});
test('the key never works from a cookie', async () => {
const r = await request(port, '/api/overview', { headers: { Cookie: `dk=${TEST_KEY}` } });
assert.equal(r.status, 401);
});
test('API accepts the token from the x-dash-key header', async () => {
// Gateway is intentionally unreachable: passing auth yields 200 with local data + a
// visible note (the gateway failure must not take the local aggregation down with it).
const r = await request(port, '/api/overview', { headers: { 'x-dash-key': TEST_KEY } });
assert.equal(r.status, 200);
const d = JSON.parse(r.body);
assert.equal(d.usage, null);
assert.match(d.note, /usage API/);
assert.equal(d.detail.error, undefined); // ENOENT(空日志)= 空态,不是读取失败
});
test('the loopback page serves without a URL token and injects one', async () => {
const r = await request(port, '/');
assert.equal(r.status, 200);
assert.match(r.body, /window\.__KEY__=/);
assert.match(r.body, new RegExp(`window\\.__KEY__="${TEST_KEY}"`));
assert.match(r.body, /window\.__DATA__=/);
assert.equal(r.headers.location, undefined);
});
test('the page CSP lists the loopback explicitly and no third-party hosts', async () => {
const r = await request(port, '/');
assert.equal(r.status, 200);
const csp = String(r.headers['content-security-policy']);
assert.match(csp, /default-src 'self'/);
assert.match(csp, new RegExp(`connect-src 'self' http://127\\.0\\.0\\.1:${port}`));
// frame-ancestors 显式声明(* = 被宿主嵌入是设计意图;宿主 origin 桌面/web 不固定)
assert.match(csp, /frame-ancestors/);
assert.doesNotMatch(csp, /cloudflareinsights/);
assert.equal(r.headers['referrer-policy'], 'no-referrer');
});
test('a sandboxed frame (Origin: null) may fetch the page', async () => {
const r = await request(port, '/', { headers: { Origin: 'null' } });
assert.equal(r.status, 200);
});
test('a cross-origin fetch of the page is refused', async () => {
const r = await request(port, '/', { headers: { Origin: 'https://evil.example' } });
assert.equal(r.status, 403);
});
test('CORS allows only the exact bound port, not any localhost port', async () => {
const r = await request(port, '/api/attribution', { headers: { Origin: `http://127.0.0.1:${port + 1}` } });
assert.equal(r.status, 403);
const ok = await request(port, '/api/attribution', { headers: { Origin: `http://127.0.0.1:${port}` } });
assert.equal(ok.status, 401); // CORS 放行、鉴权照拦——链路各管各的
});
test('attribution stays local unless the user opts in', { timeout: 30000 }, async () => {
// 维护者复审点:护栏必须真的能拦住默认值被改坏——这里**不能**继承 baseEnv 的
// ATTRIBUTION:'local',否则有人把服务端默认改成 remote 时本测试仍绿。
// extra 里显式设 undefined → Node spawn 会把它从子进程环境里省掉,服务端走默认值;
// REMOTE_BASE/KEY 虽然没配,但默认值若是 remote,remoteSources() 就不再为空,source 会变。
const s = start({ ATTRIBUTION: undefined, REMOTE_BASE: 'https://remote.example', REMOTE_KEY: 'k' });
try {
const p = await s.ready;
const r = await request(p, '/api/attribution?period=7d', { headers: { 'x-dash-key': TEST_KEY } });
assert.equal(r.status, 200);
const j = JSON.parse(r.body);
assert.equal(j.source, 'local');
assert.equal(j.totals.calls, 0);
} finally {
s.c.kill();
try { rmSync(s.dir, { recursive: true, force: true }); } catch {}
}
});
test('the gateway follows options, env and MAGPIE_ADDR, not a hard-coded port', { timeout: 30000 }, async () => {
// 维护者实测:宿主把 MAGPIE_ADDR 指到(可能被改过端口的)真实网关——看板必须问它,
// 而不是写死的 3425。解析链:options.gateway → GATEWAY → MAGPIE_GATEWAY →
// MAGPIE_ADDR → 3425。fake 网关必须在整个测试的 finally 里关掉:断言一失败就
// close,否则它的监听 socket 会把 node --test 的进程挂死。
const fake = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ calls: 123, tokens: 456, cost: 7.89 }));
});
await new Promise((resolve) => fake.listen(0, '127.0.0.1', resolve));
const gwPort = fake.address().port;
try {
// 1) MAGPIE_ADDR 单独生效(宿主场景)
const s1 = start({
MAGPIE_ADDR: `0.0.0.0:${gwPort}`, // 宿主可能写成通配地址,服务端要归一化成回环
GATEWAY: undefined,
MAGPIE_GATEWAY: undefined,
});
try {
const p1 = await s1.ready;
assert.match(s1.captured.out, new RegExp(`gateway=http://127\\.0\\.0\\.1:${gwPort}\\b`));
const r1 = await request(p1, '/api/overview', { headers: { 'x-dash-key': TEST_KEY } });
assert.equal(r1.status, 200);
const j1 = JSON.parse(r1.body);
assert.equal(j1.usage.calls, 123); // 请求打到了 MAGPIE_ADDR 指向的网关
} finally {
s1.c.kill();
try { rmSync(s1.dir, { recursive: true, force: true }); } catch {}
}
// 2) 显式 GATEWAY 优先于 MAGPIE_ADDR
const s2 = start({ MAGPIE_ADDR: '127.0.0.1:1' });
try {
await s2.ready;
assert.match(s2.captured.out, /gateway=http:\/\/127\.0\.0\.1:9\b/); // baseEnv 的 GATEWAY 赢了
assert.doesNotMatch(s2.captured.out, /gateway=http:\/\/127\.0\.0\.1:1\b/);
} finally {
s2.c.kill();
try { rmSync(s2.dir, { recursive: true, force: true }); } catch {}
}
} finally {
fake.close(() => {});
}
});
test('[::1] in MAGPIE_ADDR stays IPv6 loopback, never 127.0.0.1', { timeout: 30000 }, async () => {
// 只有 unspecified(0.0.0.0/[::])才映射回环;[::1] 是明确的 IPv6 回环,监听在 [::1]
// 的网关通常没有监听 127.0.0.1——改写会把请求打到空处(维护者复审实测)。
let hits = 0;
const fake6 = http.createServer((req, res) => {
hits++;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ calls: 7, tokens: 8, cost: 9 }));
});
const listening = await new Promise((resolve) => {
fake6.once('error', () => resolve(false)); // 无 IPv6 的环境(部分 CI 容器)跳过
fake6.listen(0, '::1', () => resolve(true));
});
if (!listening) return;
const gwPort = fake6.address().port;
// 先探测本机的 IPv6 回环是否真的可连:某些平台(Windows 的 undici)监听 ::1 成功、
// 但 fetch http://[::1] 会超时——那种环境只验证解析结果,不做端到端请求断言。
let ipv6Reachable = true;
try {
await fetch(`http://[::1]:${gwPort}/probe`, { signal: AbortSignal.timeout(2000) });
} catch {
ipv6Reachable = false;
}
hits = 0; // 探测命中了不计入
const s = start({ MAGPIE_ADDR: `[::1]:${gwPort}`, GATEWAY: undefined, MAGPIE_GATEWAY: undefined });
try {
const p = await s.ready;
assert.match(s.captured.out, new RegExp(`gateway=http://\\[::1\\]:${gwPort}\\b`));
assert.doesNotMatch(s.captured.out, new RegExp(`gateway=http://127\\.0\\.0\\.1:${gwPort}\\b`));
if (ipv6Reachable) {
const r = await request(p, '/api/overview', { headers: { 'x-dash-key': TEST_KEY } });
assert.equal(r.status, 200);
assert.equal(JSON.parse(r.body).usage.calls, 7); // 真的打到了 ::1 上的网关
assert.ok(hits > 0, 'fake IPv6 gateway received no requests');
}
} finally {
s.c.kill();
try { rmSync(s.dir, { recursive: true, force: true }); } catch {}
fake6.close(() => {});
}
});
test('config dir: the host cwd carrying magpie markers wins (portable installs)', { timeout: 30000 }, async () => {
// magpie 宿主以数据目录为 cwd 启动服务(bunCommand(..., settings.Dir(), ...))——
// 便携安装因此不需要任何环境变量。不设 USAGE_JSONL,服务应通过 cwd 探测找到它。
// 路径比较必须用 realpathSync:macOS 的 os.tmpdir() 是 /var/folders/…,而 /var 是指向
// /private/var 的符号链接——子进程的 process.cwd() 与日志里的路径都是解析后的真实
// 路径,拿未解析的 dataDir 拼字符串比会假红(维护者复审在 macOS 实测)。
const dataDir = mkdtempSync(path.join(os.tmpdir(), 'usage-board-cwd-'));
writeFileSync(path.join(dataDir, 'usage.jsonl'), '');
const realDir = realpathSync(dataDir);
const c = spawn(RUNTIME, [path.join(root, 'server.mjs')], {
cwd: realDir,
env: {
...process.env,
PAGE_KEY: TEST_KEY,
GATEWAY: 'http://127.0.0.1:9',
ATTRIBUTION: 'local',
MAGPIE_PROVIDERS: path.join(realDir, 'no-providers.json'),
MAGPIE_PROVIDERS_FILE: path.join(realDir, 'no-plugin-providers.json'),
HOST: '127.0.0.1',
PORT: '0',
},
stdio: ['ignore', 'pipe', 'pipe'],
});
let out = '';
c.stdout.on('data', (d) => { out += d; });
c.stderr.on('data', (d) => { out += d; });
await new Promise((resolve, reject) => {
const t = setTimeout(() => reject(new Error('server did not start: ' + out)), 10000);
c.stdout.on('data', (d) => { if (/listening/.test(d.toString())) { clearTimeout(t); resolve(); } });
c.once('exit', (code) => { clearTimeout(t); reject(new Error('exited ' + code + ': ' + out)); });
});
try {
assert.ok(
out.includes('jsonl=' + path.join(realDir, 'usage.jsonl') + '(ok)'),
'usage.jsonl resolved from cwd: ' + out.slice(0, 300),
);
} finally {
c.kill();
try { rmSync(dataDir, { recursive: true, force: true }); } catch {}
}
});
test('startServer({port: 0}) binds an ephemeral port, not the default', { timeout: 30000 }, async () => {
const r = await spawnChild(`
import(${JSON.stringify(SERVER_URL)}).then(async (m) => {
try {
const bound = await m.startServer({ port: 0 });
if (bound === 3455 || bound === 0) throw new Error('expected an ephemeral port, got ' + bound);
const r = await fetch('http://127.0.0.1:' + bound + '/api/health');
if (r.status !== 200) throw new Error('health ' + r.status);
console.log('EPHEMERAL-OK');
process.exit(0);
} catch (e) { console.error('FAIL ' + (e && e.message || e)); process.exit(1); }
});
`, { ...baseEnv(), HOST: '127.0.0.1' });
assert.equal(r.code, 0, `child exit ${r.code}: ${r.out.slice(0, 300)}`);
assert.match(r.out, /EPHEMERAL-OK/);
});
test('path traversal stays inside static/', async () => {
for (const p of ['/static/../../server.mjs', '/..%2fserver.mjs', '/%2e%2e/server.mjs']) {
const r = await request(port, p);
assert.equal(r.status, 404, p);
assert.notEqual(r.body, readFileSync(path.join(root, 'server.mjs'), 'utf8'));
}
});
test('brand logos come from magpie, with zero network fetches', async () => {
// plugin-providers.json 里的 data URI 注入页面;https 图标一律不抓取(隐私红线)
const dir = mkdtempSync(path.join(os.tmpdir(), 'usage-board-logos-'));
const icon = 'data:image/svg+xml;base64,' + Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"></svg>').toString('base64');
writeFileSync(path.join(dir, 'plugin-providers.json'), JSON.stringify({
0: { id: 'TestProv', icon },
1: { id: 'remote-brand', icon: 'https://cdn.example.com/favicon.svg' },
}));
const s = start({ USAGE_JSONL: path.join(dir, 'usage.jsonl'), MAGPIE_PROVIDERS_FILE: path.join(dir, 'plugin-providers.json') });
try {
const p = await s.ready;
const page = await request(p, '/');
assert.equal(page.status, 200);
assert.ok(page.body.includes(icon), 'data-URI logo injected');
assert.doesNotMatch(page.body, /cdn\.example\.com/);
assert.match(s.captured.out, /logos: 1 brands/);
} finally {
s.c.kill();
try { rmSync(dir, { recursive: true, force: true }); } catch {}
}
});
test('a public bind never serves the board page at all', async () => {
const s = start({ HOST: '0.0.0.0', ALLOWED_HOSTS: 'dash.example' });
publicChild = s.c;
publicPort = await s.ready;
// The proxy-style Host (with :443) is allowed by the explicit allowlist for APIs...
const ping = await request(publicPort, '/api/ping', { headers: { Host: 'dash.example:443' } });
assert.equal(ping.status, 200);
// ...but the page is loopback-only: a remote visitor has no auth channel (?key= is gone).
const page = await request(publicPort, '/', { headers: { Host: 'dash.example:443' } });
assert.equal(page.status, 403);
assert.equal(String(page.body || '').includes('__KEY__'), false);
});
test('HOST=:: is a wildcard bind, never treated as loopback (P0 regression)', async () => {
// '::' listens on all interfaces (dual-stack); treating it as loopback handed the
// key-injected page to anonymous visitors. It must behave like 0.0.0.0.
const s = start({ HOST: '::', ALLOWED_HOSTS: 'dash.example' });
try {
const p = await s.ready;
const page = await request(p, '/', { headers: { Host: 'dash.example:443' } });
assert.equal(page.status, 403);
assert.equal(String(page.body || '').includes('__KEY__'), false);
} finally {
s.c.kill();
}
});
test('loopback bind with a public ALLOWED_HOSTS still gates the page (P1 regression)', async () => {
// A reverse proxy forwards the public Host name to a loopback-bound service; the
// page must answer loopback hosts only, never the proxied public name.
const s = start({ HOST: '127.0.0.1', ALLOWED_HOSTS: 'dash.example.com' });
try {
const p = await s.ready;
const viaProxyHost = await request(p, '/', { headers: { Host: 'dash.example.com' } });
assert.equal(viaProxyHost.status, 403);
assert.equal(String(viaProxyHost.body || '').includes('__KEY__'), false);
} finally {
s.c.kill();
}
});
test('waits for a dying occupier on the target port, then binds it', async () => {
// 宿主重启竞态:上一代濒死实例短暂占着口——新实例必须等它退出后自己绑定,
// 而不是复用一个马上要死的实例(复用会让页面 502)。
const p = await freePort();
const occupier = net.createServer(() => {});
await new Promise((resolve, reject) => { occupier.once('error', reject); occupier.listen(p, '127.0.0.1', resolve); });
const code = `
import(${JSON.stringify(SERVER_URL)}).then(async (m) => {
try {
const bound = await m.startServer();
const r = await fetch('http://127.0.0.1:' + bound + '/api/health');
if (r.status !== 200) throw new Error('health ' + r.status);
console.log('BOUND-AFTER-WAIT');
process.exit(0);
} catch (e) { console.error('FAIL ' + (e && e.message || e)); process.exit(1); }
});
`;
setTimeout(() => occupier.close(() => {}), 1200); // 1.2s 后释放端口(模拟濒死实例退出)
const r = await spawnChild(code, { ...baseEnv(), HOST: '127.0.0.1', PORT: String(p) }, 20000);
assert.equal(r.code, 0, `child exit ${r.code}: ${r.out.slice(0, 400)}`);
assert.match(r.out, /BOUND-AFTER-WAIT/);
});
test('reuses a live instance of the same build, never a different one', { timeout: 30000 }, async () => {
// 同构建 → 复用(resolve 端口、不重复绑定);异构建/异种 → 明确报错,绝不把看板
// 交给一个未知进程。复用判定只认 /api/ping 的 BUILD_ID。子进程必须异步 spawn:
// spawnSync 会阻塞本进程事件循环,同进程里的 fake server 就无法应答探测了。
// timeout:异构建分支要等服务端 8s deadline 才报错——超过 bun test 默认 5s(维护者复审点)。
const code = `
import(${JSON.stringify(SERVER_URL)}).then(async (m) => {
try {
const bound = await m.startServer();
console.log('RESOLVED-' + bound);
process.exit(0);
} catch (e) { console.error('FAIL ' + (e && e.message || e)); process.exit(1); }
});
`;
const p = await freePort();
const first = start({ PORT: String(p) });
try {
await first.ready;
const r = await spawnChild(code, { ...baseEnv(), HOST: '127.0.0.1', PORT: String(p) }, 20000);
assert.equal(r.code, 0, `child exit ${r.code}: ${r.out.slice(0, 400)}`);
assert.match(r.out, new RegExp(`RESOLVED-${p}`));
// 异构建:伪装成同款服务但 build 不同 → 必须拒绝启动
const p2 = await freePort();
const fake = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ service: 'magpie-usage-board', ok: true, build: 'deadbeefdeadbeef', version: '9.9.9' }));
});
await new Promise((resolve) => fake.listen(p2, '127.0.0.1', resolve));
const r2 = await spawnChild(code, { ...baseEnv(), HOST: '127.0.0.1', PORT: String(p2) }, 20000);
fake.close(() => {});
assert.notEqual(r2.code, 0, 'a foreign build must not be accepted');
assert.match(r2.out, /held by another build/);
} finally {
first.c.kill();
try { rmSync(first.dir, { recursive: true, force: true }); } catch {}
}
});
test('index.mjs: importing has no side effects, server() starts and awaits listen', { timeout: 30000 }, async () => {
// The community import-check imports this file for inspection; a module-level
// startServer would grab a port and write config during that check. The child
// picks its own free port, sets PORT, then verifies import ≠ start, server() = start.
const code = `
(async () => {
const net = await import('node:net');
const free = await new Promise((res) => {
const s = new net.Server();
s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => res(p)); });
});
process.env.PORT = String(free);
const m = await import(${JSON.stringify(INDEX_URL)});
await new Promise((r) => setTimeout(r, 800));
try { await fetch('http://127.0.0.1:' + free + '/api/health'); console.error('FAIL: import started the service'); process.exit(1); } catch {}
const r0 = await m.default.server();
if (!r0 || r0.port !== free) { console.error('FAIL: server() did not report the bound port: ' + JSON.stringify(r0)); process.exit(1); }
const r = await fetch('http://127.0.0.1:' + free + '/api/health');
if (r.status !== 200) { console.error('FAIL: server() did not start the service'); process.exit(1); }
console.log('LIFECYCLE-OK');
process.exit(0);
})();
`;
const r = await spawnChild(code, baseEnv(), 20000);
assert.equal(r.code, 0, `child exit ${r.code}: ${r.out.slice(0, 400)}`);
assert.match(r.out, /LIFECYCLE-OK/);
});
test('the dashboard asks the local service for attribution', () => {
const html = readFileSync(path.join(root, 'static', 'index.html'), 'utf8');
assert.match(html, /api\/attribution\?period=/);
assert.doesNotMatch(html, /remote\.js/);
assert.doesNotMatch(html, /cloudflareinsights/);
});
test('registry draft summary matches package.json verbatim (three-text rule)', () => {
const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
const doc = readFileSync(path.join(root, 'docs', 'community-submission.md'), 'utf8');
// \r?\n:Windows 检出(core.autocrlf)下这份文件是 CRLF,写死 \n 会假红
const block = doc.match(/```json\r?\n([\s\S]*?)```/);
assert.ok(block, 'registry json block present in community-submission.md');
const reg = JSON.parse(block[1]);
assert.equal(reg.package, pkg.name);
assert.equal(reg.name, 'Usage Board');
assert.equal(reg.summary.en, pkg.magpie.summary.en);
assert.equal(reg.summary.zh, pkg.magpie.summary.zh);
});
test('the lead page has no inline scripts and no key', () => {
const html = readFileSync(path.join(root, 'page', 'index.html'), 'utf8')
.replace(/<!--[\s\S]*?-->/g, '');
for (const tag of html.match(/<script[^>]*>/gi) || []) {
assert.match(tag, /src=/i);
}
assert.doesNotMatch(html, /[?&]key=/i);
assert.doesNotMatch(html, /fetch\(/i); // the sandboxed lead page fetches nothing
assert.match(html, /_magpie\/bridge\.js/);
assert.match(html, /boot\.js/);
});
test('boot prefers magpie.service, reads the port and theme from the bridge', () => {
const js = readFileSync(path.join(root, 'page', 'boot.js'), 'utf8');
assert.match(js, /magpie\?\.service/);
assert.match(js, /options\?\.get\?\.\(\)/);
assert.match(js, /current\.dark/); // magpie 自己的深浅色 → ?theme= 传给看板
assert.match(js, /theme/);
assert.match(js, /3455/); // manifest 声明的默认口(fallback,不再有写死的第二个来源)
});
test('the board page ships both languages', () => {
const html = readFileSync(path.join(root, 'static', 'index.html'), 'utf8');
assert.match(html, /navigator\.language/);
assert.match(html, /\?lang=/);
assert.match(html, /T\s*=\s*\{\s*zh:/);
assert.match(html, /en:/);
});
test('package metadata matches the community page spec', () => {
const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
assert.equal(pkg.name, '@magpie-community/page-usage-board');
assert.equal(pkg.license, 'MIT');
assert.ok(pkg.files.includes('LICENSE'));
assert.ok(pkg.scripts.test);
assert.deepEqual(pkg.magpie.permissions, []);
assert.equal(pkg.magpie.page.file, 'page/index.html');
assert.equal(pkg.magpie.page.service.port, 3455);
assert.equal(pkg.magpie.page.service.option, 'port');
assert.equal(pkg.magpie.options.attribution, 'local'); // 远端归因必须 opt-in
assert.ok(pkg.magpie.summary.en && pkg.magpie.summary.zh);
assert.ok(pkg.magpie.page.titles.en && pkg.magpie.page.titles.zh);
});
+3 -1
View File
@@ -273,6 +273,8 @@
{ "package": "opencode-teleagent-auth", "name": "TeleAgent 模型", "icon": "https://raw.githubusercontent.com/anbulang/opencode-teleagent-auth/main/assets/icon.svg", "providers": ["teleagent"],
"summary": { "en": "Unofficial TeleAgent (天翼 AI 星辰超级智能体) desktop app models in magpie: the app's own sign-in, no API key, macOS and Windows, with points balance and daily check-in.", "zh": "非官方接入 TeleAgent(天翼 AI 星辰超级智能体)桌面端:复用桌面端登录态,不需要 API Key,支持 macOS 和 Windows,带积分余额与每日签到。" } },
{ "package": "opencode-xfyun-maas-auth", "name": "讯飞星辰 MaaS", "icon": "https://raw.githubusercontent.com/linjicong/opencode-xfyun-maas-auth/main/icon.svg", "providers": ["xfyun-maas", "xfyun-coding", "xfyun-token"],
"summary": { "en": "iFlytek Xfyun MaaS: Spark, GLM, DeepSeek, Kimi, Qwen and more — pay-as-you-go, Coding Plan and Token Plan.", "zh": "讯飞星辰 MaaS:星火、GLM、DeepSeek、Kimi、Qwen 等模型,按量付费与 Coding/Token 套餐。" } }
"summary": { "en": "iFlytek Xfyun MaaS: Spark, GLM, DeepSeek, Kimi, Qwen and more — pay-as-you-go, Coding Plan and Token Plan.", "zh": "讯飞星辰 MaaS:星火、GLM、DeepSeek、Kimi、Qwen 等模型,按量付费与 Coding/Token 套餐。" } },
{ "package": "@magpie-community/page-usage-board", "name": "Usage Board", "kind": "page", "community": true,
"summary": { "en": "A quota card wall with expiry tiers, daily/per-provider charts, 24h cache-hit and token curves, optional remote attribution and account detail. Runs its own zero-dependency local service reading this machine's Magpie usage data; optional remote attribution queries the configured remote magpie.", "zh": "额度到期卡片墙 + 每日与 provider 用量图表 + 24 小时缓存命中与 token 曲线,可选远端归因与账号明细。自带零依赖本机服务,读本机 Magpie 用量数据;远端归因会查询所配置的远端 magpie。" } }
]
}