core: publish self-hosted weekly dashboard and Proxmox deployment #20
@@ -0,0 +1,13 @@
|
||||
# Architecture
|
||||
|
||||
- [2026-11-14] D14's Fleet library reuses Core Pace/LimitAnalysis/ApiPrices; the web host and outbound worker add no second forecast implementation. Working-time schedules remain outside D7.
|
||||
- [2026-11-14] Quota is one newest observation per account/window, not a sum. Source ids dedupe consumption across machines; local/session figures include shared copies and cannot be summed as machine-exclusive use.
|
||||
- [2026-11-15] Legacy hourly history needs one account-attributed source and UTC-hour cutoff; provider and DataEmail checks match raw usage even after rebinding. Reconcile Codex increases before clipping; without a pre-cutoff baseline, omit the first cumulative total and warn rather than counting imported use twice.
|
||||
- [2026-11-14] LoginCoordinator is memory-only and binds browser session/machine/profile/worker boot/deadline. CLI identity verification is separate from process success; never serialize login URLs, codes or authorization responses into fleet state.
|
||||
- [2026-11-14] Persist worker export metadata before cursor advancement. Server merges acknowledged source records so an empty restart heartbeat cannot erase history. Current login health and historical data attribution are separate fields.
|
||||
|
||||
- [2026-11-15] Proxmox setup creates an unprivileged Debian 13 CT and builds NativeAOT inside it as a separate user. `proxmox-update.sh CTID` fast-forwards a clean tracking clone and enters the fetched installer; the local-source entry point stays offline. Updates preserve role/config/keys/profiles/history with binary-health rollback; no automatic CT or old-release deletion.
|
||||
|
||||
- [2026-11-15] Public source uses MIT; notices travel with ZIP/plugin and Proxmox outputs. `tools/source_policy.py` excludes recognized live config/keys/runtime data from both publication checks and source archives. Audit disk and index separately; inspect all historical trees, not just one filename hint per blob. Visibility/history changes need explicit authorization.
|
||||
|
||||
## Archive
|
||||
@@ -5,4 +5,15 @@
|
||||
- [2026-10-18] Avalonia 12 `CustomPopupPlacementCallback` gets the target's bounds in window coordinates, and a flip mirrors anchor and gravity but not the offset. Put a gap into the anchor rectangle (see `DataTooltip.BesidePointer`).
|
||||
- [2026-10-18] Fluent caps `ToolTip` `MaxWidth` at 320 px, and a tooltip that covers the pointer takes pointer-over from its control, which raises `PointerExited`. `Ui.Theme` raises the cap; tall tips open beside the pointer.
|
||||
|
||||
- [2026-11-14] Official Claude manual-code login must be relayed to the original process, not a browser's remote localhost. Redirected-stdin support needs live verification; Codex uses device auth. Worker D3 print-mode quota probing is opt-in because current docs do not promise it as a non-interactive quota API.
|
||||
|
||||
- [2026-11-14] Proxmox `pct exec` environment defaults differ by version. Installer calls explicitly use `--keep-env 0`; build/CLI installation also uses a clean environment under the intended non-root user.
|
||||
|
||||
- [2026-11-15] Documentation checks must skip `artifacts/` as well as `.artifacts/`: ignored build/audit downloads can contain third-party Markdown and are not project documentation.
|
||||
|
||||
- [2026-11-15] Plain `git pull` can silently overwrite ignored files newly tracked upstream. The Proxmox updater fetches then merges with `--ff-only --no-overwrite-ignore`; a real-Git regression covers ignored operator-state collisions.
|
||||
|
||||
- [2026-11-15] npm's local `--prefix` install writes `node_modules/.bin`; the Linux worker's `.local/bin/codex` requires a user-owned global prefix. The regression installs an offline synthetic package with real npm.
|
||||
- [2026-11-15] Compare copied/archived license bytes with source bytes. `read_text()` normalizes Windows CRLF while ZIP reads retain it; explicit LF/CRLF fixtures cover both checkouts.
|
||||
|
||||
## Archive
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
> Always-loaded. Everything else is on-demand. Update TOC when files change.
|
||||
|
||||
## Current Focus
|
||||
- [2026-10-18] Reset history (D12), API value (D13) and panel fixes on issue #14, PR #16.
|
||||
- [2026-11-15] Validate live Linux/LXC/TLS and official provider login. D14 dashboard/workers and Proxmox delivery are implemented in 1.2.0.
|
||||
|
||||
## Invariants
|
||||
- No credential is ever read, stored or sent; providers are reached only through their CLIs (D2).
|
||||
- Provider access/refresh tokens, API keys and cookies stay with the CLIs; only a pending login's authorization response may be relayed transiently (D2, D14).
|
||||
- Everything shipped stays NativeAOT-safe on win-x64 and linux-x64 (D1).
|
||||
- A response counts once, across restarts, rescans and resumed sessions (D3, D4, D5).
|
||||
- `snapshot.json` is the only interface between the app and other processes (D9).
|
||||
- Desktop/Stream Deck retain `snapshot.json` (D9); the optional authenticated server/worker transport is separate (D14).
|
||||
|
||||
## Table of Contents
|
||||
- `gotchas.md` — 4 entries — CLI probing pitfalls on this machine; Avalonia tooltip placement.
|
||||
- `gotchas.md` — 10 entries — CLI login, Proxmox/npm/update safety, publication checks and Avalonia tooltips.
|
||||
- `architecture.md` — 7 entries — Fleet analysis, attribution, migration, authentication, durability, Proxmox and publication.
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
tools/proxmox*.sh text eol=lf
|
||||
tools/proxmox/*.py text eol=lf
|
||||
+47
@@ -6,3 +6,50 @@ artifacts/
|
||||
*.user
|
||||
*.suo
|
||||
TestResults/
|
||||
|
||||
# Local deployment configuration and transport keys. Commit examples, never live values.
|
||||
**/server.json
|
||||
**/worker.json
|
||||
**/server.env
|
||||
**/worker.env
|
||||
*.env
|
||||
**/transport-keys.json
|
||||
**/dashboard-key
|
||||
**/worker-key
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
*.key
|
||||
*.pem
|
||||
*.pfx
|
||||
*.p12
|
||||
**/.ssh/
|
||||
**/.aws/
|
||||
**/.azure/
|
||||
id_rsa
|
||||
id_ecdsa
|
||||
id_ed25519
|
||||
|
||||
# Provider profiles and FinalToken usage/history are local runtime data.
|
||||
**/.claude/
|
||||
**/.codex/
|
||||
**/auth.json
|
||||
**/.credentials.json
|
||||
**/snapshot.json
|
||||
**/fleet.json
|
||||
**/history.json
|
||||
**/history.state.json
|
||||
**/history.journal.jsonl
|
||||
**/usage.json
|
||||
**/profile.json
|
||||
**/settings.json
|
||||
/history/
|
||||
/data/
|
||||
/state/
|
||||
/runs/
|
||||
/logs/
|
||||
*.log
|
||||
|
||||
# Python tooling outputs.
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# FinalToken
|
||||
|
||||
A small tray app that tracks Claude Code and Codex usage and limits on Windows 11 and CachyOS. It
|
||||
never signs in to a provider and never handles a token: all data comes from the installed CLIs
|
||||
and the files they write. A stats panel shows history, small popups warn when usage runs ahead
|
||||
keeps provider credentials owned by the installed CLIs. The optional web dashboard coordinates
|
||||
official CLI login with transient authorization-code relay (D14). A stats panel shows history, small popups warn when usage runs ahead
|
||||
of or behind a limit's pace, and a Stream Deck plugin puts stats on keys. Developer:
|
||||
schmidt.florian (Gitea user name).
|
||||
|
||||
@@ -30,6 +30,9 @@ the decision, why and gives-up format, and carries the `type/decision` label.
|
||||
| `src/FinalToken.App` | Avalonia desktop app (D8): stats panel, tray, settings, popups |
|
||||
| `src/FinalToken.Cli` | `finaltoken-cli` console: runs a refresh and prints the snapshot, for scripts and checks |
|
||||
| `src/FinalToken.StreamDeck` | Stream Deck plugin executable and its `.sdPlugin` assets (D10) |
|
||||
| `src/FinalToken.Fleet` | Account/machine metadata, shared analysis and pending official CLI logins (D14) |
|
||||
| `src/FinalToken.Web` | Authenticated self-hosted dashboard and outbound-worker API (D14) |
|
||||
| `src/FinalToken.Worker` | Per-OS-user collector and official CLI login process host (D14) |
|
||||
| `tests/*` | One test project per tested project, named `<Project>.Tests` |
|
||||
| `tools/` | Repository tools, listed under [Tools](#tools) |
|
||||
|
||||
@@ -41,8 +44,10 @@ the decision, why and gives-up format, and carries the `type/decision` label.
|
||||
no reflection-driven serialization, binding or loading, no `dynamic`, no runtime code
|
||||
generation. Trim and AOT analyzer warnings are errors; never suppress one without a one-line
|
||||
reason at that spot.
|
||||
- Never touch credentials (D2): do not open credential files, environment secrets or keychains,
|
||||
never log message text, and never call a provider's HTTP API.
|
||||
- Never touch provider credentials (D2): do not open credential files, provider environment secrets or keychains,
|
||||
never log message text, and never call a provider's HTTP API. D14 permits authenticated,
|
||||
transient authorization-response relay to the pending official CLI login. Dashboard/worker
|
||||
access keys authenticate FinalToken transport; they are not provider credentials.
|
||||
- Child processes (`claude`, `codex`) run without a shell, with arguments as a list, a timeout and
|
||||
cancellation, and are killed with their process tree when they overrun (D6).
|
||||
- Every file the app writes for itself is written atomically (D5).
|
||||
@@ -130,6 +135,14 @@ a screenshot of each changed view: compiling is not working.
|
||||
- `tools/publish.py`: publishes the app, `finaltoken-cli` and Stream Deck plugin with NativeAOT
|
||||
into an empty output directory and creates a ZIP beside it. Run on the target OS. It stamps
|
||||
the plugin manifest's `Version` from `<Version>`; its test is `python -B tools/test_publish.py`.
|
||||
- `tools/test_web_dashboard.py`: provider-free HTTP/worker/process integration; build Release first.
|
||||
`--serve-fixture` runs a temporary synthetic dashboard for screenshots. See `docs/web-dashboard.md`.
|
||||
- `tools/proxmox.sh`: creates/updates a managed Debian 13 LXC from the Proxmox host. Its Python
|
||||
helpers live in `tools/proxmox/`; test with `python -B tools/proxmox/test_installer.py`. See `docs/proxmox.md`.
|
||||
- `tools/proxmox-update.sh CTID`: fast-forwards a clean tracking checkout, then runs the fetched
|
||||
installer against a managed CT; test with `python -B tools/proxmox/test_update.py`.
|
||||
- `tools/check_public.py --history`: read-only publication pattern check. It reports paths/pattern
|
||||
names, never matching values; tests are `python -B tools/test_check_public.py`. See `docs/publication.md`.
|
||||
|
||||
## Writing
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# Contributing
|
||||
|
||||
FinalToken is licensed under [MIT](LICENSE). Contributions should preserve its main question:
|
||||
will the user's measured provider allowance last until the actual reset?
|
||||
|
||||
Read [AGENTS.md](AGENTS.md), [requirements](docs/requirements.md) and the relevant
|
||||
[recorded decisions](docs/decisions.md) before changing behavior. Core owns forecasting and
|
||||
history calculations; reuse them in each host. New behavior needs deterministic tests. Use
|
||||
small synthetic fixtures, never real transcripts, rollout files, credential files or customer data.
|
||||
|
||||
## Get the source
|
||||
|
||||
When anonymous repository access is enabled, these HTTPS commands need no account/token:
|
||||
|
||||
```bash
|
||||
git clone https://git.finalfactory.de/FinalFactory/FinalToken.git
|
||||
cd FinalToken
|
||||
```
|
||||
|
||||
Update a clean checkout with:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
```
|
||||
|
||||
A public repository does not grant push permission. Authenticated Gitea maintenance commands
|
||||
are separate from read-only clone/pull. Do not embed passwords, tokens or an email/password in
|
||||
the remote URL. If anonymous access is still disabled, the host must first make it public.
|
||||
|
||||
## Build and check
|
||||
|
||||
Use the .NET SDK selected by `global.json` and run commands from the repository root:
|
||||
|
||||
```text
|
||||
dotnet build FinalToken.slnx -c Release
|
||||
dotnet test --solution FinalToken.slnx -c Release
|
||||
python -B tools/docs/check_docs.py
|
||||
python -B tools/check_public.py --history
|
||||
```
|
||||
|
||||
For Proxmox tooling, also run `python -B tools/proxmox/test_installer.py`,
|
||||
`python -B tools/proxmox/test_update.py`, `bash -n tools/proxmox.sh` and
|
||||
`bash -n tools/proxmox-update.sh`. [Web setup](docs/web-dashboard.md) and [Proxmox setup](docs/proxmox.md)
|
||||
describe additional integration checks. State exactly what was exercised; mocked provider/Proxmox
|
||||
tests do not establish that live login, native publishing or CT creation worked.
|
||||
|
||||
Use the Gitea issue/branch/review workflow in [AGENTS.md](AGENTS.md#workflow). Keep changes focused
|
||||
and preserve unrelated work. Contributions do not require granting an agent permission to push
|
||||
or publish; those actions still need explicit authorization.
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Version>1.1.0</Version>
|
||||
<Version>1.2.0</Version>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>14</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
@@ -3,9 +3,14 @@
|
||||
<Project Path="src/FinalToken.Core/FinalToken.Core.csproj" />
|
||||
<Project Path="src/FinalToken.Cli/FinalToken.Cli.csproj" />
|
||||
<Project Path="src/FinalToken.App/FinalToken.App.csproj" />
|
||||
<Project Path="src/FinalToken.Fleet/FinalToken.Fleet.csproj" />
|
||||
<Project Path="src/FinalToken.StreamDeck/FinalToken.StreamDeck.csproj" />
|
||||
<Project Path="src/FinalToken.Web/FinalToken.Web.csproj" />
|
||||
<Project Path="src/FinalToken.Worker/FinalToken.Worker.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/tests/">
|
||||
<Project Path="tests/FinalToken.FakeCli/FinalToken.FakeCli.csproj" />
|
||||
<Project Path="tests/FinalToken.Fleet.Tests/FinalToken.Fleet.Tests.csproj" />
|
||||
<Project Path="tests/FinalToken.ProcessHost/FinalToken.ProcessHost.csproj" />
|
||||
<Project Path="tests/FinalToken.Core.Tests/FinalToken.Core.Tests.csproj" />
|
||||
<Project Path="tests/FinalToken.Cli.Tests/FinalToken.Cli.Tests.csproj" />
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 FinalFactory 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.
|
||||
@@ -1,18 +1,26 @@
|
||||
# FinalToken
|
||||
|
||||
FinalToken is a tray app for Claude Code and Codex usage. It shows token history, provider limits,
|
||||
and pace, warns when usage runs ahead of or behind a limit, and puts selected stats on Stream Deck
|
||||
keys. Starting the app opens the stats panel; closing it keeps the tray app running by default.
|
||||
FinalToken answers: **at my current usage, will my allowance last until the weekly reset?**
|
||||
It tracks Claude Code and Codex limits, average/recent forecasts, daily budgets and reset history.
|
||||
Use the desktop tray app, the optional self-hosted web dashboard, or Stream Deck keys.
|
||||
Starting the desktop app opens its stats panel; closing it keeps the tray app running by default.
|
||||
|
||||
FinalToken does not sign in to a provider, handle API keys or OAuth tokens, or read credential
|
||||
files. It reads the installed CLIs' usage files and runs their local commands. It never calls a
|
||||
provider's HTTP API itself. Missing or logged-out CLIs show as unavailable.
|
||||
FinalToken reads the installed CLIs' usage files and runs their commands. Provider credentials
|
||||
stay owned by those CLIs; FinalToken never reads credential files or calls a provider's HTTP API.
|
||||
The optional [self-hosted dashboard and worker](docs/web-dashboard.md) combine multiple machines
|
||||
and coordinate official CLI login with transient authorization-code relay. Weekly forecasts,
|
||||
daily budgets and reset history reuse the desktop app's analysis. Missing or logged-out CLIs
|
||||
show their observed health; stale allowances have no current forecast.
|
||||
|
||||
For automatic container creation from a Proxmox host, use the [LXC install/update script](docs/proxmox.md).
|
||||
It supports a server-only LXC and a single-command update that refreshes the deployment checkout.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Claude Code and/or Codex CLI installed and logged in through the CLI. Their paths can be
|
||||
overridden in Settings.
|
||||
- Windows 11, or Linux with X11 or XWayland. CachyOS with KDE Plasma uses XWayland.
|
||||
- Desktop: Windows 11, or Linux with X11 or XWayland. CachyOS with KDE Plasma uses XWayland.
|
||||
- Web server/client: .NET 10 source build or a target-OS NativeAOT build; no desktop required.
|
||||
- For keys: Stream Deck 7 on Windows, or OpenDeck on Linux. These are optional.
|
||||
|
||||
## Install and use
|
||||
@@ -55,3 +63,13 @@ python -B tools/publish.py win-x64 --out artifacts/package-win-x64
|
||||
The publish directory must be empty. The tool bundles all three executables and plugin assets,
|
||||
then creates a ZIP beside the directory. Publish `win-x64` on Windows and `linux-x64` on Linux.
|
||||
|
||||
## Public source and contributing
|
||||
|
||||
Once the repository is publicly readable, cloning/fetching/pulling over HTTPS needs no Git login.
|
||||
Push access, dashboard access and official provider logins remain separate authenticated operations.
|
||||
See [contributing](CONTRIBUTING.md) and [publication checks](docs/publication.md).
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE). Third-party dependencies retain their own licenses.
|
||||
|
||||
|
||||
+54
-4
@@ -7,7 +7,7 @@ the IDs instead of restating the text. The requirements (R1 to R7) are in
|
||||
|
||||
## D1 — .NET 10, C# 14 and NativeAOT for win-x64 and linux-x64
|
||||
|
||||
**Decision.** Every shipped executable (the app, the CLI and the Stream Deck plugin) targets
|
||||
**Decision.** Every shipped executable (the app, the CLI, Stream Deck plugin and optional web/worker hosts) targets
|
||||
`net10.0` with C# 14 and publishes NativeAOT for `win-x64` and `linux-x64`. `global.json` asks
|
||||
for SDK 10.0.100 or newer within 10.0 (`rollForward: latestFeature`), so the SDK from CachyOS's
|
||||
package manager works too. Builds treat warnings as errors and run the trim and AOT analyzers.
|
||||
@@ -20,8 +20,10 @@ serialization, binding or loading, or runtime code generation.
|
||||
|
||||
## D2 — The CLIs are the only interface to a provider
|
||||
|
||||
**Decision.** FinalToken never reads, stores, logs or sends a credential (OAuth token, API key,
|
||||
cookie). It never opens a provider login and never calls a provider's HTTP API itself. It reads
|
||||
**Decision.** FinalToken never reads, stores, logs or sends a provider access/refresh token,
|
||||
API key or cookie. It can invoke an official CLI login and transiently relay the browser's
|
||||
authorization response to that exact pending process ([D14](#d14--self-hosted-dashboard-and-workers)).
|
||||
It never calls a provider's HTTP API itself. It reads
|
||||
the files the CLIs write and runs the installed `claude` and `codex` executables as child
|
||||
processes, which use their own login. It never opens credential files such as
|
||||
`~/.claude/.credentials.json` or `~/.codex/auth.json`, or the OS keychain. Only counts, model
|
||||
@@ -32,6 +34,7 @@ working.
|
||||
**Why.** R2, R3.
|
||||
|
||||
**Gives up.** Whatever the CLIs do not expose, and limit data while a CLI is not installed.
|
||||
Login coordination needs the installed CLI's supported flow; no central credential pool is possible.
|
||||
|
||||
## D3 — Claude data sources
|
||||
|
||||
@@ -299,7 +302,8 @@ week's start and the id of the limit window it follows (`weekStart`, `weekWindow
|
||||
the current instance of the provider's weekly limit: its longest window over a day whose label
|
||||
names no model family. Without one, it is the local calendar week from Monday, and `weekWindow`
|
||||
is absent. The DTOs and their source-generated JSON context live in `FinalToken.Core`, shared by
|
||||
the app, the CLI and the Stream Deck plugin. Nothing listens on a socket or runs an HTTP server. A reader treats a
|
||||
the app, the CLI and the Stream Deck plugin. The optional separate dashboard/worker hosts use
|
||||
[D14](#d14--self-hosted-dashboard-and-workers); the desktop app itself has no server. A reader treats a
|
||||
snapshot older than three refresh intervals as stale. The app gives the engine its own path; a
|
||||
CLI refresh keeps the path already in the snapshot, and a snapshot without one has none, so a
|
||||
reader never mistakes its own path for the app's.
|
||||
@@ -310,6 +314,52 @@ calendar week (developer feedback, 2026-10-18).
|
||||
|
||||
**Gives up.** Updates faster than the reader's poll interval.
|
||||
|
||||
## D14 — Self-hosted dashboard and workers
|
||||
|
||||
**Decision.** Add a separate ASP.NET Core slim/NativeAOT-compatible server and an outbound .NET
|
||||
worker per OS user, following the developer's direction in
|
||||
[#19](https://git.finalfactory.de/FinalFactory/FinalToken/issues/19).
|
||||
|
||||
- Account ids, expected emails and machine/profile bindings are configured by the operator.
|
||||
The server has a dashboard access key and distinct per-machine keys. Browser sessions are
|
||||
HttpOnly, SameSite cookies with CSRF checks; remote access uses HTTPS. A worker cannot select
|
||||
another machine's identity or execute arbitrary remote commands.
|
||||
- The dashboard calls Core's D7, D12 and D13 APIs. No second forecasting implementation is added.
|
||||
Local settings remain local; the newest quota observation's profile supplies the pace threshold,
|
||||
hidden windows and freshness interval. Account timezone controls calendar days. No working-hour
|
||||
forecast is added. Old/expired limits are displayed but have no current forecast.
|
||||
- Quota is the newest observed account/window value, never the sum across machines. Consumption
|
||||
uses Claude response ids and ordered Codex session cumulative counts across machine copies.
|
||||
Conflicting event metadata is excluded with a warning. Raw metadata history and observations
|
||||
survive offline clients and restarts; messages and project paths are not exported.
|
||||
- Old hourly history cannot be deduplicated after aggregation. An optional designated source and
|
||||
fixed UTC-hour cutoff import it once; identified source events own the interval after the cutoff.
|
||||
Historical profile/account attribution is an operator assertion; identity probes cannot prove
|
||||
which account produced older transcripts. Use a separate profile/data directory per account.
|
||||
- A login is bound to browser session, machine, OS user, config profile, worker boot and a
|
||||
15-minute maximum attempt deadline. That deadline is not a provider credential expiry.
|
||||
Claude uses `auth login --claudeai` and manual code relay through stdin; Codex uses
|
||||
`login --device-auth`. The CLI exchanges and stores its own credentials. A status probe verifies
|
||||
the resulting email. Unknown identity or account mismatch cannot be reported as success.
|
||||
Responses, URLs and device codes live only in pending-session memory and are not logged.
|
||||
- Cancellation, timeout, worker restart and concurrent attempts have explicit outcomes.
|
||||
No remote localhost callback forwarding or private provider endpoint is implemented.
|
||||
CLI output/flow changes fail visibly and may require terminal login on that machine.
|
||||
- The worker reuses the local store and scanner. Claude's legacy D3 print-mode quota probe is
|
||||
opt-in: current official documentation does not promise that slash commands in print mode are
|
||||
a supported quota API. Without it, existing observations remain available and age to stale.
|
||||
Codex uses D4's CLI app-server and rollout fallback. No provider HTTP API is added.
|
||||
|
||||
**Why.** R8, and the developer's clarification that the browser authorization response must
|
||||
travel through FinalToken to the CLI, without being stored. D7's analysis answers whether the
|
||||
remaining allowance will last through the actual reset; token prices alone cannot answer it.
|
||||
|
||||
**Gives up.** Automatic remote callbacks, provider-token sharing, automatic account switching,
|
||||
unverified identities, universal login lifetimes, and exact cross-machine attribution of old
|
||||
hourly buckets. The metadata inventory currently has a 100,000-record per-profile export bound;
|
||||
the collector retains prior data and reports failure when full. This version uses atomic JSON
|
||||
inventories, not an unbounded fleet database. See [operation and limits](web-dashboard.md).
|
||||
|
||||
## D10 — Stream Deck plugin
|
||||
|
||||
**Decision.** The plugin's UUID is `de.finalfactory.finaltoken`, its folder
|
||||
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
# Proxmox LXC install and update
|
||||
|
||||
Run [tools/proxmox.sh](../tools/proxmox.sh) **as root on the Proxmox host**, from a trusted local
|
||||
copy of this checkout. It creates the container itself; do not run it inside an existing LXC.
|
||||
The default is a dashboard plus a collector/client in one new, unprivileged Debian 13 amd64 CT.
|
||||
This follows [D14](decisions.md#d14--self-hosted-dashboard-and-workers).
|
||||
|
||||
Use a checkout containing the web/worker and installer source. A public repository can be
|
||||
[cloned and updated over HTTPS without a Git login](publication.md#anonymous-git-reads).
|
||||
Alternatively copy the source to the host, including `tools/proxmox/`, `tools/proxmox.sh`, `tools/source_policy.py`,
|
||||
`LICENSE`, root build files and the four Core/Fleet/Web/Worker source directories. Git metadata
|
||||
and build artifacts are not needed. The installer snapshots the selected local source, including
|
||||
uncommitted files; this local-source installer never pulls, commits or pushes Git changes.
|
||||
The separate [one-command updater](../tools/proxmox-update.sh) refreshes a clean Git checkout
|
||||
before invoking the installer.
|
||||
The snapshot excludes recognized local configuration, key and runtime-data paths independently
|
||||
of Git ignore rules; those files are not read or transferred with the source.
|
||||
|
||||
## Install dashboard and client
|
||||
|
||||
From the copied repository root on the Proxmox host:
|
||||
|
||||
```bash
|
||||
bash tools/proxmox.sh install --ctid 201 --storage local-lvm \
|
||||
--domain usage.example.com --email [email protected] --timezone Europe/Berlin
|
||||
```
|
||||
|
||||
Replace the storage, CT id, domain and email. Omit `--ctid` to ask Proxmox for the next free id.
|
||||
`--storage` is deliberately required: the installer does not choose where to allocate your disk.
|
||||
Add `--dry-run` to print the validated plan without calling Proxmox or changing files.
|
||||
|
||||
The installer:
|
||||
|
||||
1. Downloads the latest available Debian 13 standard amd64 template to `local`, or uses the
|
||||
filename selected with `--template`. `--template-storage` selects another template storage.
|
||||
2. Creates an unprivileged CT, with on-boot startup, 2 cores, 4096 MiB RAM, 2048 MiB swap,
|
||||
a 20 GiB root disk and DHCP on `vmbr0`. It does not enable nesting or privileged mode.
|
||||
3. Uploads an allowlisted source archive and builds `linux-x64` NativeAOT **inside the CT**, as
|
||||
the separate `finaltoken-build` OS user. Windows-built executables are never deployed to Linux.
|
||||
4. Installs the .NET 10 SDK/native compiler prerequisites in the CT, Caddy for HTTPS, and the
|
||||
official Claude native stable installer and Codex npm package as the `finaltoken` user.
|
||||
Official CLI downloads run under that user, not root. No provider login is attempted.
|
||||
5. Generates service keys, account/profile bindings, systemd services and a loopback web backend.
|
||||
Caddy exposes `https://<domain>`. The new client is automatically registered with this server.
|
||||
6. Checks local services and the dashboard HTTP response. Keys are not printed by the script.
|
||||
|
||||
The host needs Proxmox's `pct`, `pvesh`, `pveam`, `pvesm` and Python 3. Its package repositories
|
||||
are not changed. The CT needs working DNS and outbound package/download access. Native builds
|
||||
need time and memory; increase `--memory`, `--cores` or `--disk` for a slower/smaller host.
|
||||
The first build restores .NET packages. Later updates also run package installation in the CT;
|
||||
this is not a fully offline or byte-for-byte reproducible supply-chain build.
|
||||
|
||||
For static networking:
|
||||
|
||||
```bash
|
||||
bash tools/proxmox.sh install --ctid 201 --storage local-lvm \
|
||||
--bridge vmbr0 --ip 192.0.2.20/24 --gateway 192.0.2.1 --vlan 10 \
|
||||
--domain usage.example.com --email [email protected]
|
||||
```
|
||||
|
||||
`--vlan` is optional. Set DNS to point the chosen domain to the CT. Allow incoming TCP 80/443
|
||||
through your Proxmox/network firewall and, for public ACME certificates, forward the required
|
||||
ports. The script sets the CT interface's firewall flag; it does not modify cluster/host firewall
|
||||
rules, DNS, NAT or routing. The public certificate/network path is not proven by the local
|
||||
health check. Caddy's default ACME certificate issuance needs the domain to be reachable.
|
||||
|
||||
For a private LAN hostname, add `--tls internal`. Caddy then uses a private CA; explicitly trust
|
||||
its root certificate on browsers and remote clients. Do not disable TLS verification.
|
||||
The root certificate is inside the CT at:
|
||||
|
||||
```text
|
||||
/var/lib/finaltoken-proxy/caddy/pki/authorities/local/root.crt
|
||||
```
|
||||
|
||||
Read the dashboard access key from the Proxmox root console when you need to sign in:
|
||||
|
||||
```bash
|
||||
pct exec 201 -- cat /etc/finaltoken/dashboard-key
|
||||
```
|
||||
|
||||
Open the dashboard and use **Log in / renew** for each provider profile. This is the actual
|
||||
official CLI login, bound to that CT's `finaltoken` user. The CLI still requires your browser
|
||||
authorization. The client only observes coding activity in this CT's profiles; it cannot see
|
||||
coding sessions on a desktop or a different CT unless a client is installed there too.
|
||||
Claude quota probing remains subject to the [web integration limitations](web-dashboard.md#provider-usage-limitations).
|
||||
|
||||
## Client-only or server-only
|
||||
|
||||
For a **server-only** container, run this as root on the Proxmox host after these changes are
|
||||
published to `master` and anonymous HTTPS reads are enabled. The host needs Git in addition to
|
||||
the Proxmox commands and Python 3. Use a new checkout path and a free CT id; replace the storage,
|
||||
domain and timezone for your setup:
|
||||
|
||||
```bash
|
||||
git clone --branch master --single-branch https://git.finalfactory.de/FinalFactory/FinalToken.git /opt/finaltoken-src && \
|
||||
bash /opt/finaltoken-src/tools/proxmox.sh install --role server --ctid 201 \
|
||||
--storage local-lvm --domain usage.example.com --timezone Europe/Berlin
|
||||
```
|
||||
|
||||
This installs only the dashboard and HTTPS proxy. No provider login or provider email is required
|
||||
on the server. Optional `--email` seeds the provider accounts; accounts and remote machine
|
||||
bindings can also be configured afterwards. Set the domain's DNS and TCP 80/443 access as
|
||||
described above. Private-LAN deployments can add `--tls internal` and trust the private CA.
|
||||
|
||||
Read the dashboard key with `pct exec 201 -- cat /etc/finaltoken/dashboard-key`.
|
||||
Keep `/opt/finaltoken-src` as a dedicated deployment checkout for the update command below.
|
||||
|
||||
For a separate collector LXC, first configure an account/machine binding on the existing server
|
||||
as described in [the dashboard setup](web-dashboard.md#run-locally). The machine's `osUser` must
|
||||
be `finaltoken`, with the selected provider ids as its profile ids. Put that machine's matching
|
||||
transport key in a root-readable host file (mode 0600); it is a FinalToken key, not a provider token.
|
||||
|
||||
```bash
|
||||
bash tools/proxmox.sh install --ctid 202 --storage local-lvm --role worker \
|
||||
--server-url https://usage.example.com --machine-id lxc_202 \
|
||||
--worker-key-file /root/lxc_202.key --email [email protected]
|
||||
```
|
||||
|
||||
The script creates the client CT, installs its CLIs, configures profiles and starts its service.
|
||||
The existing server must already authorize that machine id/key; this mode does not edit another
|
||||
server's configuration. If the existing server uses a private CA, install that CA in the new CT's
|
||||
system trust store with `update-ca-certificates` before expecting the worker to connect.
|
||||
|
||||
`--role server` omits the local client/CLIs and starts with no machine bindings. You can supply
|
||||
`--email` to seed provider accounts, then configure remote machines in `/etc/finaltoken/server.json`
|
||||
and add their distinct `FINALTOKEN_MACHINE_<id>` keys in `/etc/finaltoken/server.env`.
|
||||
Restart the server after editing its configuration. The operator guide documents this static
|
||||
configuration contract; there is no automatic remote enrollment HTTP API.
|
||||
|
||||
Use `--providers codex` or `--providers claude` to install only one provider.
|
||||
`--claude-email` and `--codex-email` override `--email` independently. Machine ids must begin with
|
||||
a letter and use letters/digits/underscores, because they also name systemd environment variables.
|
||||
|
||||
## Update or resume a partial installation
|
||||
|
||||
For a clean clone at `/opt/finaltoken-src`, run this **single command as root on the host**
|
||||
from any working directory. Change `201` to the installed CT id:
|
||||
|
||||
```bash
|
||||
bash /opt/finaltoken-src/tools/proxmox-update.sh 201
|
||||
```
|
||||
|
||||
It fetches the checkout's tracking branch with fast-forward-only/no-autostash rules, verifies that
|
||||
HEAD matches that upstream, then enters the **newly fetched** installer. Re-running the command
|
||||
with no new commit still retries deployment, which is useful after a package/build interruption.
|
||||
The existing managed CT marker preserves the installed role, including server-only installations.
|
||||
It refuses a detached branch, missing upstream, local-only commits and tracked/staged/untracked
|
||||
changes; it never resets, stashes, commits or pushes local work. Upstream paths that would overwrite
|
||||
ignored local files also stop the update. Ignored runtime state is retained
|
||||
and filtered from source archives. Update failures return a nonzero exit status. Git failures
|
||||
stop before deployment and do not echo remote URLs that might contain operator credentials.
|
||||
The updater locks its checkout with `flock` (util-linux); the installer also holds its existing
|
||||
host-wide deployment lock. Do not edit the dedicated clone during an update.
|
||||
|
||||
To validate the current source and deployment arguments without fetching or changing the CT:
|
||||
|
||||
```bash
|
||||
bash /opt/finaltoken-src/tools/proxmox-update.sh 201 --dry-run
|
||||
```
|
||||
|
||||
For a manually copied checkout or a deliberately selected local source snapshot, copy the
|
||||
desired new source into place and use the original offline-source entry point:
|
||||
|
||||
```bash
|
||||
bash tools/proxmox.sh update --ctid 201
|
||||
```
|
||||
|
||||
Use `--source /absolute/path/to/another/checkout` to select a different local source snapshot.
|
||||
Update requires a running CT with this installer's marker and matching CT id. It refuses foreign
|
||||
or stopped containers. It does not overwrite identity settings; install-only identity flags are
|
||||
rejected on update. Service keys, configuration, CLI profiles and usage history are preserved.
|
||||
Updates do not reinstall/upgrade the official CLIs; they keep their normal CLI-owned lifecycle.
|
||||
|
||||
A new binary release is built before the `current` symlink changes. Only services that were
|
||||
running are restarted; intentionally stopped services remain stopped. A local health failure
|
||||
restores the previous binary release and attempts to restart the previously running services.
|
||||
That is binary rollback, not a history/configuration/OS-package rollback. Old releases are kept;
|
||||
no automatic pruning or container deletion takes place. A future incompatible data schema needs
|
||||
an explicit migration/backup plan before deploying it.
|
||||
|
||||
Restarting a server/client interrupts pending login attempts; finish or cancel them first.
|
||||
An interrupted package download or build leaves the CT for inspection. Once the guest marker
|
||||
exists, the same `update` command resumes an incomplete initial installation without rotating
|
||||
its enrollment key. If creation failed before the marker was written, inspect the CT and its
|
||||
network rather than trying to overwrite it with another `install`.
|
||||
|
||||
## Files and service ownership
|
||||
|
||||
| Location | Purpose |
|
||||
|---|---|
|
||||
| `/etc/finaltoken/install.json` | Managed CT id, role, source checksum and last successful release |
|
||||
| `/etc/finaltoken/server.json`, `worker.json` | Operator-editable account/profile configuration |
|
||||
| `/etc/finaltoken/server.env`, `worker.env` | Root-only FinalToken service keys/environment |
|
||||
| `/etc/finaltoken/transport-keys.json` | Root-only initial transport-key backup; not provider credentials |
|
||||
| `/opt/finaltoken/releases/`, `/opt/finaltoken/current` | Root-owned staged/active native binaries |
|
||||
| `/var/lib/finaltoken-server/` | Server data; owned by `finaltoken-server` |
|
||||
| `/var/lib/finaltoken-worker/` | CLI profiles, per-provider history and collector state; owned by `finaltoken` |
|
||||
| `/var/lib/finaltoken-proxy/` | Caddy state/certificates; owned by `finaltoken-proxy` |
|
||||
| `/var/cache/finaltoken-build/` | Separate build user home/cache; per-build source directories are removed |
|
||||
|
||||
Generated units use separate non-root users, restrictive file permissions, no-new-privileges and
|
||||
process-group shutdown. They avoid mount-namespace sandbox settings that require extra LXC
|
||||
features. Unit files are created once and preserved on update; put site overrides in systemd
|
||||
drop-ins. Default package `caddy.service` is disabled in favor of `finaltoken-proxy.service`.
|
||||
|
||||
```bash
|
||||
pct exec 201 -- systemctl status finaltoken-server finaltoken-worker finaltoken-proxy
|
||||
pct exec 201 -- journalctl -u finaltoken-worker -u finaltoken-server --since today
|
||||
```
|
||||
|
||||
Application stdout/stderr are discarded by these units to prevent CLI/login material entering
|
||||
the journal. The journal still shows service exit/restart metadata. Inspect configuration and
|
||||
CLI installation under the intended user when diagnosing a failed service. Do not dump provider
|
||||
credential files into logs or support reports. For coding inside the worker CT, use
|
||||
`pct enter 201`, then `su - finaltoken`; its official CLIs are in `~/.local/bin`.
|
||||
|
||||
## Verification and limits
|
||||
|
||||
Run from the repository root:
|
||||
|
||||
```text
|
||||
python -B tools/proxmox/test_installer.py
|
||||
python -B tools/proxmox/test_update.py
|
||||
bash -n tools/proxmox.sh
|
||||
bash -n tools/proxmox-update.sh
|
||||
python -B tools/docs/check_docs.py
|
||||
```
|
||||
|
||||
Installer tests mock Proxmox, package installation, native publishing and systemd. They cover
|
||||
argument validation, CT refusal, command order, environment isolation, archive safety, preservation
|
||||
of configuration/keys, partial setup, stopped services and activation rollback. They do not prove
|
||||
a real Proxmox create/update, Linux build, certificate issuance or provider login. No Proxmox
|
||||
host/container was changed while developing this script.
|
||||
|
||||
One installer regression uses real Node.js/npm with an offline synthetic package to check the
|
||||
configured Codex launcher and repeat installation. It skips explicitly when Node.js/npm are
|
||||
unavailable. On Windows its fixture adapts npm's global-prefix layout to the guest's Linux `bin`
|
||||
path; that checks npm install mode and actual files without claiming Linux execution.
|
||||
|
||||
Updater tests use real local Git repositories and Bash with a synthetic installer. They verify
|
||||
two-version fast-forward deployment, no-change retry, dirty/diverged/ahead/detached refusal,
|
||||
fetch failure, dry-run, exit status, ignored-state retention and ignored-file collisions. Advisory lock command results
|
||||
are substituted so the checks also run on Windows; real Linux locking is not exercised here.
|
||||
|
||||
References: [Proxmox CLI source](https://github.com/proxmox/pve-container/blob/master/src/PVE/CLI/pct.pm),
|
||||
[.NET on Debian](https://learn.microsoft.com/en-us/dotnet/core/install/linux-debian),
|
||||
[NativeAOT prerequisites](https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/),
|
||||
[Caddy TLS](https://caddyserver.com/docs/caddyfile/directives/tls),
|
||||
[Claude installation](https://code.claude.com/docs/en/setup),
|
||||
[Codex installation](https://github.com/openai/codex/blob/main/README.md).
|
||||
Source refresh uses [Git fetch](https://git-scm.com/docs/git-fetch),
|
||||
[fast-forward merge](https://git-scm.com/docs/git-merge) and
|
||||
[flock](https://man7.org/linux/man-pages/man1/flock.1.html).
|
||||
@@ -0,0 +1,72 @@
|
||||
# Preparing a public repository
|
||||
|
||||
The repository uses the [MIT license](../LICENSE). Build/runtime dependencies keep their own
|
||||
licenses. MIT licensing does not change authentication to providers or the running dashboard.
|
||||
|
||||
## Anonymous Git reads
|
||||
|
||||
After the repository host enables anonymous read access, HTTPS clone/fetch/pull need no login,
|
||||
email, password or Git token. Use the public URL in [contributing](../CONTRIBUTING.md#get-the-source).
|
||||
Pushes and maintainer API operations still require their own authorization.
|
||||
|
||||
For the Proxmox workflow, clone the published source on the host, then run its installer:
|
||||
|
||||
```bash
|
||||
git clone https://git.finalfactory.de/FinalFactory/FinalToken.git
|
||||
cd FinalToken
|
||||
bash tools/proxmox.sh install --ctid 201 --storage local-lvm \
|
||||
--domain usage.example.com --email [email protected]
|
||||
```
|
||||
|
||||
For a later update, refresh and deploy the clean checkout with one command:
|
||||
|
||||
```bash
|
||||
bash tools/proxmox-update.sh 201
|
||||
```
|
||||
|
||||
Here `--email` is the intended **provider account identity**, not a Git login. The installer
|
||||
reads the local checkout; the separate updater fetches its tracking branch first. The branch being cloned must contain the
|
||||
web/worker/installer changes. A public visibility setting alone does not publish uncommitted work.
|
||||
|
||||
## Files to keep local
|
||||
|
||||
The ignore rules exclude live deployment configuration, service keys, provider profiles, usage
|
||||
history, build outputs and screenshots/logs. Keep real configuration outside the checkout when
|
||||
possible. Example files must use reserved example domains and explicit placeholders.
|
||||
Ignoring a file does not remove a copy that was already committed.
|
||||
|
||||
The dashboard and client still authenticate their transport. Provider authorization goes through
|
||||
the official CLI on its machine; making source public does not make your running instance or
|
||||
CLI credentials public. Do not remove dashboard/client authentication to simplify Git downloads.
|
||||
|
||||
## Read-only audit
|
||||
|
||||
From the repository root:
|
||||
|
||||
```text
|
||||
python -B tools/check_public.py --history
|
||||
```
|
||||
|
||||
This checks Git-listed source files (including non-ignored untracked files), the actual staged
|
||||
index blobs and reachable local history (source, commit and tag text) for sensitive runtime filenames and recognizable
|
||||
private-key/provider-token patterns.
|
||||
It reports paths, line numbers and pattern names, never matching values. Credential/config files
|
||||
are reported by filename without opening them. Binary/oversized objects are reported as skipped.
|
||||
The check is a targeted pattern check, not proof that arbitrary secrets are absent.
|
||||
Index blobs are checked even when the working copy is clean or different. Historical trees are
|
||||
checked for private filenames even when the same blob also appeared under a harmless name.
|
||||
The shared path policy in `tools/source_policy.py` also keeps recognized runtime files out of
|
||||
Proxmox source archives; `.gitignore` alone does not filter a custom deployment archive.
|
||||
|
||||
For an independent secret-detector check, use a verified [Gitleaks release](https://github.com/gitleaks/gitleaks).
|
||||
Scan the candidate source snapshot, staged index and reachable Git history with full redaction.
|
||||
Keep reports outside the published source, review every finding, and never paste secret values
|
||||
into issues. A clean detector report is limited to its rules and scanned inputs.
|
||||
|
||||
Git author/committer identities and old source remain in history. Review whether those identities
|
||||
are suitable for publication. Do not silently rewrite attribution/history or delete branches to
|
||||
hide findings. Any real credential exposure needs revocation and a separately authorized history
|
||||
cleanup. Re-run the audit after that work and on the actual refs intended for publication.
|
||||
|
||||
Publication is a separate action: review the local changes, commit/push with authorization, and
|
||||
enable anonymous access on the intended host. This cleanup does not change repository visibility.
|
||||
@@ -4,11 +4,15 @@ Set by schmidt.florian on 2026-10-14 ([#1](https://git.finalfactory.de/FinalFact
|
||||
Each requirement has a stable ID. [Decisions](decisions.md) say how FinalToken meets them.
|
||||
|
||||
- **R1** NativeAOT on the newest .NET. Cross-platform: at least Windows 11 and CachyOS.
|
||||
- **R2** No sign-in to an AI provider inside the app and no API key or OAuth token. Data comes
|
||||
through the providers' command-line tools.
|
||||
- **R2** Provider credentials stay owned by the installed command-line tools. FinalToken can
|
||||
coordinate their official login and transiently relay an authorization response to the exact
|
||||
pending CLI process. It never stores or distributes provider access/refresh tokens or API keys.
|
||||
- **R3** Supported providers: at least Codex and Claude.
|
||||
- **R4** Opening the app shows a comprehensive stats panel, history included.
|
||||
- **R5** Small, non-intrusive popups remind the user when usage runs ahead of or behind the pace
|
||||
of a limit.
|
||||
- **R6** A Stream Deck plugin shows selected stats on its buttons.
|
||||
- **R7** The app installs or updates the Stream Deck plugin automatically, as the user chooses.
|
||||
- **R8** An authenticated self-hosted dashboard combines the user's Windows/Linux machines,
|
||||
keeping weekly sustainability central, account quota separate from deduplicated consumption,
|
||||
and measured, estimated, unknown and stale values distinct. See [D14](decisions.md#d14--self-hosted-dashboard-and-workers).
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
# Self-hosted dashboard and workers
|
||||
|
||||
The web dashboard leads with “will my allowance last until reset?” It uses Core's existing
|
||||
[D7 analysis](decisions.md#d7--pace), daily budgets, measured/estimated burn-up, recent-rate forecast,
|
||||
[reset history](decisions.md#d12--reset-history) and dated API list-price estimates.
|
||||
There is no inference gateway. Coding traffic continues through the user's own coding CLIs.
|
||||
|
||||
## Run locally
|
||||
|
||||
For automatic CT creation from a Proxmox host, use the [Proxmox install/update script](proxmox.md).
|
||||
|
||||
Build from the repository root:
|
||||
|
||||
```text
|
||||
dotnet build FinalToken.slnx -c Release
|
||||
```
|
||||
|
||||
Create an operator-owned `server.json` outside the source tree. Account ids represent one actual
|
||||
provider subscription/account. Bind every profile using the same account to the same id.
|
||||
Do not merge separate provider organizations/workspaces simply because their email is the same:
|
||||
this version verifies email, not organization entitlement. Use distinct account ids/profiles.
|
||||
|
||||
```json
|
||||
{
|
||||
"accounts": [
|
||||
{ "id": "personal-claude", "provider": "Claude", "label": "Personal Claude", "expectedEmail": "[email protected]", "timeZone": "Europe/Berlin" },
|
||||
{ "id": "personal-codex", "provider": "Codex", "label": "Personal Codex", "expectedEmail": "[email protected]", "timeZone": "Europe/Berlin" }
|
||||
],
|
||||
"machines": [
|
||||
{ "id": "desktop", "label": "Desktop", "osUser": "your-os-user", "profiles": [
|
||||
{ "id": "claude", "accountId": "personal-claude" },
|
||||
{ "id": "codex", "accountId": "personal-codex" }
|
||||
] }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Set `FINALTOKEN_SERVER_CONFIG` to that file, `FINALTOKEN_SERVER_DATA` to a writable data directory,
|
||||
`FINALTOKEN_DASHBOARD_KEY` to a random key of at least 32 characters and
|
||||
`FINALTOKEN_MACHINE_desktop` to a different random key of at least 32 characters.
|
||||
For example generate keys with your password manager or `openssl rand -hex 32`.
|
||||
Do not put keys in source control, command arguments, URLs or screenshots.
|
||||
|
||||
Start the server from the repository root:
|
||||
|
||||
```text
|
||||
dotnet run --project src/FinalToken.Web -c Release --no-build
|
||||
```
|
||||
|
||||
By default it listens on `http://127.0.0.1:5187`. Open exactly that URL and enter the dashboard key.
|
||||
For a remote deployment, set `FINALTOKEN_PUBLIC_ORIGIN` to the public HTTPS origin and run a TLS
|
||||
reverse proxy that preserves its Host header, or configure HTTPS directly in Kestrel.
|
||||
`ASPNETCORE_URLS` changes the listening address. Do not expose a plain HTTP listener to a remote
|
||||
network. No forwarded-header trust is enabled automatically. Restrict direct backend access;
|
||||
the reverse proxy must not log request bodies or authorization headers. Login URLs/codes are
|
||||
deliberately absent from server logs and disk state. TLS termination sees the transient code.
|
||||
Keys authorize all profiles on their configured machine; use service-account file/environment
|
||||
permissions and a private network/firewall. Rotate a machine key on both ends to revoke it.
|
||||
|
||||
## Configure each worker
|
||||
|
||||
Run one worker under the OS user that owns the official CLIs. It cannot switch OS users remotely.
|
||||
Use absolute paths in `worker.json`; a profile's `configDirectory` is the existing `.claude` or
|
||||
`.codex` directory (or the relevant environment override), and `dataDirectory` is its existing
|
||||
FinalToken history/settings directory. Use a separate data/config/state directory per account.
|
||||
|
||||
```json
|
||||
{
|
||||
"machineId": "desktop",
|
||||
"serverUrl": "http://127.0.0.1:5187",
|
||||
"stateDirectory": "<absolute worker metadata directory>",
|
||||
"profiles": [
|
||||
{ "id": "claude", "provider": "Claude", "expectedEmail": "[email protected]", "configDirectory": "<absolute Claude config directory>", "dataDirectory": "<absolute existing FinalToken data directory>" },
|
||||
{ "id": "codex", "provider": "Codex", "expectedEmail": "[email protected]", "configDirectory": "<absolute Codex config directory>", "dataDirectory": "<absolute separate FinalToken data directory>" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
JSON backslashes must be escaped on Windows, or use forward slashes. `cliPath` is an optional
|
||||
local executable override; ordinary native/npm CLI discovery reuses the desktop code.
|
||||
Set `FINALTOKEN_WORKER_KEY` to the server's key for this machine. Start from the repository root:
|
||||
|
||||
```text
|
||||
dotnet run --project src/FinalToken.Worker -c Release --no-build -- <absolute worker.json path>
|
||||
```
|
||||
|
||||
Remote worker URLs require HTTPS. Workers only make outbound connections; no worker port is open.
|
||||
Use the OS service manager/Task Scheduler for unattended startup, under the intended user with
|
||||
the CLI on PATH. A Linux/LXC worker needs .NET 10 (or a future locally built NativeAOT binary),
|
||||
installed official CLIs, writable profile directories, outbound HTTPS and any CLI keychain
|
||||
requirements. It needs no desktop/X11. Actual Linux/LXC operation has not been exercised here.
|
||||
The existing release ZIP tool does not package the new hosts yet; source builds and the
|
||||
[Proxmox installer](proxmox.md) are the supported setup paths.
|
||||
|
||||
## History, account identity and settings
|
||||
|
||||
The worker acquires the normal store lock before refreshing the existing store. When the desktop
|
||||
app owns it, the worker reads existing observations and independently scans metadata using its
|
||||
own cursors. It does not replace the user's existing settings. Both provider settings may remain
|
||||
in an older desktop store; for two worker profiles, point one at that existing store and give
|
||||
the other a new directory. Shared-provider historical import can use a read-only copy made while
|
||||
the desktop is stopped. Never run two writers against a copied active journal.
|
||||
|
||||
Source metadata is durably saved before export cursor advancement. The server persists received
|
||||
metadata and last-seen state atomically; offline data remains visible. Claude response ids dedupe
|
||||
across transcripts, resumed copies and machines. Codex session ids/timestamps are merged before
|
||||
calculating cumulative increases. Conflicting response/counter metadata is excluded with a
|
||||
warning. A source copied under a different session id cannot be recognized as the same session.
|
||||
Per-machine attribution of a shared session is inherently ambiguous; the dashboard shows configured
|
||||
profiles/health, while consumption charts show the deduplicated account total.
|
||||
|
||||
Existing hourly history has no response identities. To import older history without overlapping
|
||||
identified records, add these account fields to `server.json`:
|
||||
|
||||
```json
|
||||
{ "legacyMachine": "desktop", "legacyProfile": "claude", "historyBefore": "2026-11-01T00:00:00Z" }
|
||||
```
|
||||
|
||||
This is a fragment to merge into one account entry. Choose one source and a fixed whole UTC hour
|
||||
within the still-available source logs. Before it, use that source's hourly buckets once; after
|
||||
it, use identified events only. Missing source logs after the cutoff produce incomplete history,
|
||||
not reconstructed guesses. Account assignment of older logs is an operator assertion. Never
|
||||
reuse a profile directory for another account; configure a new profile instead.
|
||||
For Codex sessions without a cumulative sample before the cutoff, the first available total
|
||||
has an unknown migration baseline and is omitted with a warning. Later increases still count.
|
||||
This can omit a new session's first use too; supplying complete pre-cutoff session history or
|
||||
avoiding legacy import is preferable to counting potentially imported usage twice.
|
||||
|
||||
The newest account/window observation wins; quotas are never added. Its profile's existing
|
||||
threshold, hidden-window settings and probe interval control that window. A sample older than
|
||||
three probe intervals, an expired reset, offline source or unhealthy login withholds forecasts.
|
||||
The account timezone controls days/DST. There is no working-hour schedule in existing D7.
|
||||
API list-price values are labelled estimates; unknown models stay unpriced, and prices never
|
||||
imply guaranteed subscription capacity.
|
||||
|
||||
## Official login coordination
|
||||
|
||||
Select a machine/profile under **Machines & official CLI logins**, then **Log in / renew**.
|
||||
Verify its OS user and expected email before opening the official authorization page.
|
||||
|
||||
- Claude: the worker invokes `claude auth login --claudeai --email <expected email>` with the
|
||||
selected `CLAUDE_CONFIG_DIR`. When the CLI prints its manual-code prompt, paste the browser's
|
||||
authorization code into the dashboard. It travels transiently to that exact process's stdin.
|
||||
There is no automatic forwarding of a desktop browser's localhost callback to a worker.
|
||||
- Codex: the worker invokes `codex login --device-auth` with the selected `CODEX_HOME`, displays
|
||||
the CLI's official URL/device code and lets the CLI poll/exchange/store locally. Device auth
|
||||
must be enabled for that account/workspace. No remote localhost callback is needed.
|
||||
- FinalToken verifies the resulting email with `claude auth status --json` or Codex app-server
|
||||
`account/read`. A CLI exit code alone is not success. A mismatch may already have replaced that
|
||||
profile's CLI login; FinalToken flags it and excludes new collection. Log in again with the
|
||||
correct account. It does not copy, revert or auto-switch credentials.
|
||||
|
||||
Only the initiating browser session can inspect/respond/cancel its pending login. One attempt
|
||||
per machine/profile is allowed. Cancellation and the 15-minute deadline kill the process tree;
|
||||
worker restart invalidates pending routing. A server restart loses memory-only attempts; the
|
||||
worker's local deadline still cancels its CLI. Closing the dialog does not cancel a login:
|
||||
press **Cancel login** first if that is intended. Access/refresh tokens, API keys, cookies and
|
||||
credential files are never sent through FinalToken. The authorization code necessarily passes
|
||||
through browser/server/worker memory; it is never deliberately persisted or logged.
|
||||
|
||||
Provider login health is observed, not a fabricated 30-day expiry. The official CLI owns refresh.
|
||||
The real manual Claude stdin handoff and real provider authorization still need an interactive
|
||||
test with the installed CLI version. If redirected stdin is unsupported, cancel and run the login
|
||||
in the selected machine's terminal. Synthetic CLI integration tests exercise the implementation,
|
||||
not a provider's live service or changing terminal behavior.
|
||||
|
||||
## Provider usage limitations
|
||||
|
||||
Codex quota comes through its CLI app-server/rollout integration (D4). Claude's existing D3
|
||||
`-p /usage` probe is a legacy integration; current official docs do not establish it as a
|
||||
supported non-interactive quota API. Worker profiles default `enableLegacyClaudeProbe` to false.
|
||||
Existing Claude observations can be read but become stale; current subscription allowance may
|
||||
remain unknown. Enable the legacy probe only after verifying that your installed CLI resolves
|
||||
it locally without a model request. No private OAuth usage endpoint was added. Tokens are still
|
||||
collected locally from supported log parsers after identity verification.
|
||||
|
||||
The metadata inventory currently exports at most 100,000 source records, 30,000 quota samples
|
||||
and 100,000 legacy hourly/model points per profile. Requests are capped at 32 MiB. Full inventory
|
||||
exchange favors small personal fleets; it is not a streaming fleet database. When bounds or
|
||||
collection fail, previous metadata is retained and collection failure is shown. Server history
|
||||
has no automatic retention/deletion UI. Back up its metadata directory and the worker state.
|
||||
|
||||
Official references checked 2026-11-14:
|
||||
|
||||
- [Claude authentication and manual code handoff](https://code.claude.com/docs/en/authentication)
|
||||
- [Claude CLI auth commands](https://code.claude.com/docs/en/cli-reference)
|
||||
- [Codex authentication](https://learn.chatgpt.com/docs/auth?surface=cli)
|
||||
- [Codex CLI flags](https://learn.chatgpt.com/docs/cli/reference)
|
||||
- [Official Codex device-code implementation](https://github.com/openai/codex/blob/main/codex-rs/login/src/device_code_auth.rs)
|
||||
- [Official Codex app-server account identity](https://github.com/openai/codex/blob/main/codex-rs/app-server/README.md)
|
||||
|
||||
## Verification
|
||||
|
||||
Run from the repository root:
|
||||
|
||||
```text
|
||||
dotnet build FinalToken.slnx -c Release
|
||||
dotnet test --solution FinalToken.slnx -c Release
|
||||
python -B tools/test_web_dashboard.py
|
||||
python -B tools/docs/check_docs.py
|
||||
node --check src/FinalToken.Web/wwwroot/app.js
|
||||
```
|
||||
|
||||
The Python check launches the real web/worker executables with a synthetic C# CLI and temporary
|
||||
profiles. It tests HTTP authentication/CSRF/session isolation, Claude code relay, Codex device
|
||||
flow, cancellation, account mismatch, deduplicated history and absence of login payloads in
|
||||
server state. `--serve-fixture` starts the same provider-free setup for local visual inspection.
|
||||
It never invokes the installed Claude or Codex CLIs. NativeAOT publishing and live provider
|
||||
authorization require separate verification; analyzers/build success alone do not prove them.
|
||||
@@ -68,7 +68,7 @@ public static class ActivationFile
|
||||
}
|
||||
}
|
||||
|
||||
internal static class SharedFile
|
||||
public static class SharedFile
|
||||
{
|
||||
public static FileStream OpenRead(string path) => new(path, FileMode.Open, FileAccess.Read,
|
||||
FileShare.ReadWrite | FileShare.Delete, 65536, FileOptions.SequentialScan);
|
||||
|
||||
@@ -9,7 +9,7 @@ public sealed record ScanResult(int AddedEvents, IReadOnlyList<LimitWindow> Code
|
||||
/// <summary>Only opens transcript/rollout jsonl paths. Offsets advance through complete lines only.
|
||||
/// Prefix and consumed-tail fingerprints detect replacements without rereading whole files.</summary>
|
||||
public sealed class IncrementalScanner(HistoryStore history, DiagnosticLog diagnostics,
|
||||
string claudeDirectory, string codexDirectory)
|
||||
string claudeDirectory, string codexDirectory, Action<UsageEvent, string?>? observe = null)
|
||||
{
|
||||
private static readonly UTF8Encoding StrictUtf8 = new(false, true);
|
||||
public async Task<ScanResult> ScanAsync(CancellationToken cancellationToken = default,
|
||||
@@ -93,12 +93,20 @@ public sealed class IncrementalScanner(HistoryStore history, DiagnosticLog diagn
|
||||
var text = StrictUtf8.GetString(line.GetBuffer(), 0, (int)line.Length).TrimEnd('\r');
|
||||
if (text.Length > 0 && provider == Provider.Claude)
|
||||
{
|
||||
if (TranscriptParser.Parse(text, diagnostics) is { } usage && history.Add(usage)) added++;
|
||||
if (TranscriptParser.Parse(text, diagnostics) is { } usage)
|
||||
{
|
||||
observe?.Invoke(usage, cursor.SessionId);
|
||||
if (history.Add(usage)) added++;
|
||||
}
|
||||
}
|
||||
else if (text.Length > 0)
|
||||
{
|
||||
var entry = RolloutParser.Parse(text, cursor, DateTimeOffset.UtcNow, diagnostics);
|
||||
if (entry.CumulativeUsage is { } usage && history.AddCodex(cursor.SessionId!, usage)) added++;
|
||||
if (entry.CumulativeUsage is { } usage)
|
||||
{
|
||||
observe?.Invoke(usage, cursor.SessionId);
|
||||
if (history.AddCodex(cursor.SessionId!, usage)) added++;
|
||||
}
|
||||
if (entry.Limits.Count > 0)
|
||||
{
|
||||
latestLimits.Clear(); latestLimits.AddRange(entry.Limits);
|
||||
|
||||
@@ -5,7 +5,8 @@ using System.Text.Json;
|
||||
namespace FinalToken.Core.Processes;
|
||||
|
||||
public sealed record ProcessRequest(CliCommand Command, IReadOnlyList<string> Arguments, string WorkingDirectory,
|
||||
TimeSpan Timeout, bool CodexRpc = false, int OutputLimit = 1024 * 1024);
|
||||
TimeSpan Timeout, bool CodexRpc = false, int OutputLimit = 1024 * 1024,
|
||||
IReadOnlyDictionary<string, string>? EnvironmentOverrides = null, string RpcMethod = "account/rateLimits/read");
|
||||
public sealed record ProcessResult(int ExitCode, string Output, bool TimedOut = false, bool OutputTruncated = false);
|
||||
public interface IProcessRunner
|
||||
{
|
||||
@@ -31,6 +32,8 @@ public sealed class ProcessRunner(TimeProvider? timeProvider = null) : IProcessR
|
||||
StandardInputEncoding = new UTF8Encoding(false)
|
||||
} };
|
||||
foreach (var argument in request.Command.PrefixArguments.Concat(request.Arguments)) process.StartInfo.ArgumentList.Add(argument);
|
||||
if (request.EnvironmentOverrides is not null)
|
||||
foreach (var (key, value) in request.EnvironmentOverrides) process.StartInfo.Environment[key] = value;
|
||||
process.Start();
|
||||
// D6: a WinExe host can have no standard input handle. Give every child a valid
|
||||
// pipe; non-interactive probes get EOF, while app-server keeps its RPC input open.
|
||||
@@ -44,7 +47,9 @@ public sealed class ProcessRunner(TimeProvider? timeProvider = null) : IProcessR
|
||||
await process.StandardInput.WriteLineAsync("{\"id\":1,\"method\":\"initialize\",\"params\":{\"clientInfo\":{\"name\":\"finaltoken\",\"version\":\"1.0.0\"},\"capabilities\":{\"experimentalApi\":false,\"explicitGatewayOauth\":true}}}".AsMemory(), token);
|
||||
await ReadResponseAsync(process.StandardOutput, 1, request.OutputLimit, token);
|
||||
await process.StandardInput.WriteLineAsync("{\"method\":\"initialized\"}".AsMemory(), token);
|
||||
await process.StandardInput.WriteLineAsync("{\"id\":2,\"method\":\"account/rateLimits/read\",\"params\":null}".AsMemory(), token);
|
||||
if (request.RpcMethod is not ("account/rateLimits/read" or "account/read"))
|
||||
throw new ArgumentException("Unsupported metadata RPC.");
|
||||
await process.StandardInput.WriteLineAsync(($"{{\"id\":2,\"method\":\"{request.RpcMethod}\",\"params\":null}}").AsMemory(), token);
|
||||
var output = await ReadResponseAsync(process.StandardOutput, 2, request.OutputLimit, token);
|
||||
Kill(process);
|
||||
await process.WaitForExitAsync(CancellationToken.None);
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# Fleet
|
||||
Shared metadata transport, account aggregation and official CLI login coordination. Reuse Core D7/D12/D13 analysis. No provider credentials or raw process output in persisted state. Authorization responses and login URLs exist only in live session memory (D14). Run Fleet tests from the root.
|
||||
@@ -0,0 +1,236 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using FinalToken.Core;
|
||||
using FinalToken.Core.Processes;
|
||||
|
||||
namespace FinalToken.Fleet;
|
||||
|
||||
public static class CliAuthentication
|
||||
{
|
||||
public static IReadOnlyDictionary<string, string> EnvironmentFor(WorkerProfile profile) =>
|
||||
new Dictionary<string, string> { [profile.Provider == Provider.Claude ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME"] = Path.GetFullPath(profile.ConfigDirectory) };
|
||||
public static async Task<AuthHealth> ReadAsync(WorkerProfile profile, IProcessRunner? runner = null, CancellationToken token = default)
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var command = CliDiscovery.Find(profile.Provider, profile.CliPath).Command;
|
||||
if (command is null) return new("Unavailable", null, now, "Configured CLI not found.");
|
||||
try
|
||||
{
|
||||
var result = await (runner ?? new ProcessRunner()).RunAsync(new(command,
|
||||
profile.Provider == Provider.Claude ? ["auth", "status", "--json"] : ["app-server"],
|
||||
profile.DataDirectory, TimeSpan.FromSeconds(30), CodexRpc: profile.Provider == Provider.Codex,
|
||||
EnvironmentOverrides: EnvironmentFor(profile), RpcMethod: "account/read"), token);
|
||||
return Parse(profile, result, now);
|
||||
}
|
||||
catch (Exception) when (!token.IsCancellationRequested) { return new("Unknown", null, now, "CLI identity probe failed; no expiry inferred."); }
|
||||
}
|
||||
public static AuthHealth Parse(WorkerProfile profile, ProcessResult result, DateTimeOffset now)
|
||||
{
|
||||
if (result.ExitCode != 0 || result.TimedOut || result.OutputTruncated) return new("Unavailable", null, now, "CLI status failed; login may require renewal.");
|
||||
try
|
||||
{
|
||||
using var json = JsonDocument.Parse(result.Output);
|
||||
var root = json.RootElement;
|
||||
if (profile.Provider == Provider.Claude)
|
||||
{
|
||||
if (!root.TryGetProperty("loggedIn", out var logged) || logged.ValueKind is not (JsonValueKind.True or JsonValueKind.False))
|
||||
return new("Unknown", null, now, "CLI did not expose login status.");
|
||||
if (logged.ValueKind != JsonValueKind.True)
|
||||
return new("Unavailable", null, now, "CLI reports signed out.");
|
||||
if (root.TryGetProperty("configDirectory", out var directory) && directory.ValueKind == JsonValueKind.String &&
|
||||
!Path.GetFullPath(directory.GetString()!).Equals(Path.GetFullPath(profile.ConfigDirectory), OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
|
||||
return new("ProfileMismatch", null, now, "CLI reports a different config directory.");
|
||||
}
|
||||
else
|
||||
{
|
||||
root = root.GetProperty("result").GetProperty("account");
|
||||
if (root.ValueKind != JsonValueKind.Object) return new("Unavailable", null, now, "CLI reports no account.");
|
||||
}
|
||||
var email = root.TryGetProperty("email", out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
|
||||
if (email is not { Length: > 0 and <= 320 }) return new("Unknown", null, now, "CLI did not expose account identity; no expiry inferred.");
|
||||
return new(string.Equals(email, profile.ExpectedEmail, StringComparison.OrdinalIgnoreCase) ? "Healthy" : "AccountMismatch",
|
||||
email, now, "CLI-reported account identity; refresh/expiry remains owned by the CLI.");
|
||||
}
|
||||
catch (Exception e) when (e is JsonException or InvalidOperationException or KeyNotFoundException or ArgumentException)
|
||||
{ return new("Unknown", null, now, "Unrecognized CLI identity response; no expiry inferred."); }
|
||||
}
|
||||
}
|
||||
|
||||
public static partial class LoginOutput
|
||||
{
|
||||
[GeneratedRegex(@"\x1B\[[0-?]*[ -/]*[@-~]", RegexOptions.None, 100)]
|
||||
private static partial Regex Ansi();
|
||||
[GeneratedRegex(@"https://[^\s\x1b<>""']+", RegexOptions.None, 100)]
|
||||
private static partial Regex Url();
|
||||
[GeneratedRegex(@"\b[A-Z0-9]{4}-[A-Z0-9]{4,5}\b", RegexOptions.None, 100)]
|
||||
private static partial Regex DeviceCode();
|
||||
public static bool OfficialUrl(Provider provider, string url) => Uri.TryCreate(url, UriKind.Absolute, out var u) &&
|
||||
u.Scheme == "https" && u.IsDefaultPort && u.UserInfo.Length == 0 && (provider == Provider.Claude
|
||||
? (u.Host is "claude.ai" or "platform.claude.com" or "console.anthropic.com") && u.AbsolutePath.StartsWith("/oauth/", StringComparison.Ordinal)
|
||||
: u.Host == "auth.openai.com" && u.AbsolutePath == "/codex/device");
|
||||
public static LoginUpdate Parse(string id, WorkerProfile profile, string output, bool accepted)
|
||||
{
|
||||
var text = Ansi().Replace(output, "");
|
||||
var url = Url().Matches(text).Select(m => m.Value.TrimEnd(')', '.', ',')).LastOrDefault(u => OfficialUrl(profile.Provider, u));
|
||||
var code = profile.Provider == Provider.Codex ? DeviceCode().Match(text).Value : null;
|
||||
var state = accepted ? "Verifying" : profile.Provider == Provider.Claude && url is not null &&
|
||||
(text.Contains("Paste code", StringComparison.OrdinalIgnoreCase) || text.Contains("Enter code", StringComparison.OrdinalIgnoreCase))
|
||||
? "WaitingForCode" : url is not null ? "WaitingForBrowser" : "Starting";
|
||||
return new(id, profile.Id, state, url, string.IsNullOrEmpty(code) ? null : code, InputAccepted: accepted);
|
||||
}
|
||||
}
|
||||
|
||||
public interface ILoginProcess : IAsyncDisposable
|
||||
{
|
||||
LoginUpdate Current { get; }
|
||||
Task SubmitAsync(string response, CancellationToken token);
|
||||
void Cancel();
|
||||
}
|
||||
|
||||
/// <summary>Real installed CLI; bounded output stays only in memory and is reduced to allowlisted login fields.</summary>
|
||||
public sealed class CliLoginProcess : ILoginProcess
|
||||
{
|
||||
private readonly WorkerProfile profile;
|
||||
private readonly string id;
|
||||
private readonly CancellationTokenSource stop;
|
||||
private readonly Process process;
|
||||
private readonly Task run;
|
||||
private readonly Lock gate = new();
|
||||
private readonly SemaphoreSlim inputGate = new(1, 1);
|
||||
private string output = "";
|
||||
private bool accepted, cancelled, outputFailed;
|
||||
private LoginUpdate current;
|
||||
public LoginUpdate Current { get { lock (gate) return current; } }
|
||||
public CliLoginProcess(LoginCommand command, WorkerProfile profile)
|
||||
{
|
||||
this.profile = profile; id = command.Id;
|
||||
current = new(id, profile.Id, "Starting");
|
||||
var remaining = command.ExpiresAt - DateTimeOffset.UtcNow;
|
||||
if (remaining <= TimeSpan.Zero || remaining > TimeSpan.FromMinutes(16)) throw new InvalidDataException("Invalid login deadline.");
|
||||
stop = new(remaining);
|
||||
var cli = CliDiscovery.Find(profile.Provider, profile.CliPath).Command ?? throw new InvalidDataException("CLI not found.");
|
||||
process = new() { StartInfo = new()
|
||||
{
|
||||
FileName = cli.FileName, WorkingDirectory = profile.DataDirectory, UseShellExecute = false, CreateNoWindow = true,
|
||||
RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true,
|
||||
StandardInputEncoding = new UTF8Encoding(false), StandardOutputEncoding = new UTF8Encoding(false), StandardErrorEncoding = new UTF8Encoding(false)
|
||||
} };
|
||||
foreach (var arg in cli.PrefixArguments.Concat(profile.Provider == Provider.Claude ? new[] { "auth", "login", "--claudeai", "--email", profile.ExpectedEmail } : ["login", "--device-auth"]))
|
||||
process.StartInfo.ArgumentList.Add(arg);
|
||||
foreach (var (key, value) in CliAuthentication.EnvironmentFor(profile)) process.StartInfo.Environment[key] = value;
|
||||
process.Start(); run = RunAsync();
|
||||
}
|
||||
public async Task SubmitAsync(string response, CancellationToken token)
|
||||
{
|
||||
await inputGate.WaitAsync(token);
|
||||
try
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
if (accepted) return; // retransmitted transport command is idempotent
|
||||
if (current.State != "WaitingForCode" || stop.IsCancellationRequested) throw new InvalidDataException("CLI is not waiting for a code.");
|
||||
accepted = true; current = current with { State = "Verifying", InputAccepted = true };
|
||||
}
|
||||
await process.StandardInput.WriteLineAsync(response.AsMemory(), token);
|
||||
await process.StandardInput.FlushAsync(token);
|
||||
}
|
||||
finally { inputGate.Release(); }
|
||||
}
|
||||
public void Cancel() { cancelled = true; stop.Cancel(); }
|
||||
private async Task PumpAsync(StreamReader reader)
|
||||
{
|
||||
try
|
||||
{
|
||||
var buffer = new char[1024]; int count;
|
||||
while ((count = await reader.ReadAsync(buffer, stop.Token)) > 0)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
if (output.Length + count > 64 * 1024) throw new InvalidDataException("Login output exceeded bound.");
|
||||
output += new string(buffer, 0, count);
|
||||
current = LoginOutput.Parse(id, profile, output, accepted);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception) when (!stop.IsCancellationRequested)
|
||||
{
|
||||
// Task.WhenAll alone waits for the other pipe: cancel immediately so a CLI
|
||||
// waiting for stdin cannot keep the failed pump/process alive until timeout.
|
||||
lock (gate) outputFailed = true;
|
||||
stop.Cancel(); throw;
|
||||
}
|
||||
}
|
||||
private async Task RunAsync()
|
||||
{
|
||||
var stdout = PumpAsync(process.StandardOutput); var stderr = PumpAsync(process.StandardError);
|
||||
try
|
||||
{
|
||||
// A failed output pump must stop the process promptly, even when it is waiting for stdin.
|
||||
var pumps = Task.WhenAll(stdout, stderr);
|
||||
var exited = process.WaitForExitAsync(stop.Token);
|
||||
if (await Task.WhenAny(pumps, exited) == pumps) await pumps;
|
||||
await exited; await pumps;
|
||||
if (process.ExitCode != 0) { Set("Failed"); return; }
|
||||
Set("Verifying");
|
||||
var health = await CliAuthentication.ReadAsync(profile, token: stop.Token);
|
||||
Set(health.State == "Healthy" ? "Succeeded" : health.State == "AccountMismatch" ? "AccountMismatch" : "IdentityUnknown", health.Email);
|
||||
}
|
||||
catch (OperationCanceledException) { Set(outputFailed ? "Failed" : cancelled ? "Cancelled" : "TimedOut"); }
|
||||
catch (Exception) { Set("Failed"); }
|
||||
finally
|
||||
{
|
||||
try { if (!process.HasExited) process.Kill(true); } catch (InvalidOperationException) { }
|
||||
await process.WaitForExitAsync(CancellationToken.None);
|
||||
stop.Cancel();
|
||||
try { await Task.WhenAll(stdout, stderr); } catch (Exception) { }
|
||||
lock (gate) output = "";
|
||||
}
|
||||
}
|
||||
private void Set(string state, string? email = null)
|
||||
{ lock (gate) current = new(id, profile.Id, state, Email: email, InputAccepted: accepted); }
|
||||
public async ValueTask DisposeAsync() { stop.Cancel(); await run; process.Dispose(); stop.Dispose(); inputGate.Dispose(); }
|
||||
}
|
||||
|
||||
public sealed class WorkerLogins(IReadOnlyList<WorkerProfile> profiles, Func<LoginCommand, WorkerProfile, ILoginProcess>? factory = null) : IAsyncDisposable
|
||||
{
|
||||
private readonly Dictionary<string, ILoginProcess> processes = [];
|
||||
private readonly Dictionary<string, LoginUpdate> failures = [];
|
||||
private readonly HashSet<string> identityChanges = [];
|
||||
public IReadOnlyList<LoginUpdate> Updates => processes.Values.Select(p => p.Current).Concat(failures.Values).ToArray();
|
||||
public bool TakeIdentityChanges()
|
||||
{
|
||||
var changed = false;
|
||||
foreach (var update in Updates.Where(u => u.State is "Succeeded" or "AccountMismatch" or "IdentityUnknown"))
|
||||
changed |= identityChanges.Add(update.Id);
|
||||
return changed;
|
||||
}
|
||||
public async Task ApplyAsync(WorkerReply reply, CancellationToken token)
|
||||
{
|
||||
foreach (var command in reply.Commands)
|
||||
{
|
||||
if (processes.TryGetValue(command.Id, out var process))
|
||||
{
|
||||
if (process.Current.ProfileId != command.ProfileId) continue;
|
||||
if (command.Cancel) process.Cancel();
|
||||
else if (command.Response is { } response) await process.SubmitAsync(response, token);
|
||||
continue;
|
||||
}
|
||||
if (command.Cancel) { failures[command.Id] = new(command.Id, command.ProfileId, "Cancelled"); continue; }
|
||||
if (failures.ContainsKey(command.Id)) continue;
|
||||
var profile = profiles.SingleOrDefault(p => p.Id == command.ProfileId);
|
||||
if (profile is null || processes.Values.Any(p => p.Current.ProfileId == command.ProfileId &&
|
||||
p.Current.State is "Starting" or "WaitingForCode" or "WaitingForBrowser" or "Verifying"))
|
||||
{ failures[command.Id] = new(command.Id, command.ProfileId, "Failed"); continue; }
|
||||
try { processes.Add(command.Id, (factory ?? ((c, p) => new CliLoginProcess(c, p)))(command, profile)); }
|
||||
catch (Exception) { failures[command.Id] = new(command.Id, command.ProfileId, "Failed"); }
|
||||
}
|
||||
// Only the server's current commands are live. Keep recent outcomes for acknowledgement, bound memory.
|
||||
if (processes.Count > 80)
|
||||
foreach (var key in processes.Where(p => !reply.Commands.Any(c => c.Id == p.Key)).Select(p => p.Key).Take(40).ToArray())
|
||||
{ await processes[key].DisposeAsync(); processes.Remove(key); identityChanges.Remove(key); }
|
||||
if (failures.Count > 80) failures.Clear();
|
||||
}
|
||||
public async ValueTask DisposeAsync() { foreach (var p in processes.Values) await p.DisposeAsync(); }
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using FinalToken.Core;
|
||||
|
||||
namespace FinalToken.Fleet;
|
||||
|
||||
public sealed record AccountConfig(string Id, Provider Provider, string Label, string ExpectedEmail,
|
||||
string TimeZone = "UTC", string? LegacyMachine = null, string? LegacyProfile = null, DateTimeOffset? HistoryBefore = null);
|
||||
public sealed record ProfileBinding(string Id, string AccountId);
|
||||
public sealed record MachineConfig(string Id, string Label, string OsUser, IReadOnlyList<ProfileBinding> Profiles);
|
||||
public sealed record ServerConfig(IReadOnlyList<AccountConfig> Accounts, IReadOnlyList<MachineConfig> Machines);
|
||||
public sealed record WorkerProfile(string Id, Provider Provider, string ExpectedEmail, string ConfigDirectory,
|
||||
string DataDirectory, string? CliPath = null, bool EnableLegacyClaudeProbe = false);
|
||||
public sealed record WorkerConfig(string MachineId, string ServerUrl, string StateDirectory, IReadOnlyList<WorkerProfile> Profiles);
|
||||
public sealed record AuthHealth(string State, string? Email, DateTimeOffset CheckedAt, string Reason);
|
||||
// Claude: absolute response counts; Codex: cumulative session counts. Never send transcript content/project paths.
|
||||
public sealed record SourceUsage(string Key, string? Session, DateTimeOffset Time, string? Model, TokenCounts Counts);
|
||||
public sealed record ProfileReport(string Id, Provider Provider, AuthHealth Auth, Settings Settings,
|
||||
IReadOnlyList<SourceUsage> Usage, IReadOnlyList<LimitWindow> Samples, IReadOnlyList<ModelTokenPoint> LegacyTokens,
|
||||
string? CollectionError = null, string? DataEmail = null, string? CollectionNote = null);
|
||||
public sealed record WorkerReport(string MachineId, string OsUser, string BootId, DateTimeOffset CollectedAt,
|
||||
IReadOnlyList<ProfileReport> Profiles, IReadOnlyList<LoginUpdate> Logins);
|
||||
public sealed record MachineState(string MachineId, DateTimeOffset SeenAt, WorkerReport Report);
|
||||
public sealed record FleetState(IReadOnlyList<MachineState> Machines);
|
||||
public sealed record LoginUpdate(string Id, string ProfileId, string State, string? Url = null,
|
||||
string? DeviceCode = null, string? Email = null, bool InputAccepted = false);
|
||||
public sealed record LoginCommand(string Id, string ProfileId, DateTimeOffset ExpiresAt, bool Cancel = false, string? Response = null);
|
||||
public sealed record WorkerReply(IReadOnlyList<LoginCommand> Commands);
|
||||
public sealed record LoginView(string Id, string MachineId, string ProfileId, string State, DateTimeOffset ExpiresAt,
|
||||
string? Url, string? DeviceCode, string? Email);
|
||||
public sealed record StartLogin(string MachineId, string ProfileId);
|
||||
public sealed record LoginResponse(string Response);
|
||||
public sealed record SignIn(string Key);
|
||||
public sealed record BrowserSession(string Csrf);
|
||||
public sealed record WindowView(LimitWindow Window, bool Stale, PaceResult Pace, double? UseAtReset,
|
||||
double? RemainingAtReset, RateForecast? Recent, LimitEstimate? Analysis, ResetHistory? Resets);
|
||||
public sealed record AccountView(AccountConfig Account, IReadOnlyList<WindowView> Windows,
|
||||
IReadOnlyList<ModelTokenPoint> Tokens, TokenCounts Total, decimal? ApiValue, long UnpricedTokens,
|
||||
IReadOnlyList<string> Warnings, DateOnly PricesCheckedOn, IReadOnlyList<SessionConsumption> Sessions, bool HasConsumptionData);
|
||||
public sealed record SessionConsumption(string Id, TokenCounts Tokens);
|
||||
public sealed record ProfileConsumption(string ProfileId, TokenCounts? Tokens, int Sessions);
|
||||
public sealed record MachineView(string Id, string Label, string OsUser, bool Online, DateTimeOffset? SeenAt,
|
||||
IReadOnlyList<ProfileReport> Profiles, IReadOnlyList<ProfileBinding> Bindings, IReadOnlyList<ProfileConsumption> Consumption);
|
||||
public sealed record DashboardView(DateTimeOffset Now, IReadOnlyList<AccountView> Accounts, IReadOnlyList<MachineView> Machines);
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true)]
|
||||
[JsonSerializable(typeof(ServerConfig))]
|
||||
[JsonSerializable(typeof(WorkerConfig))]
|
||||
[JsonSerializable(typeof(WorkerReport))]
|
||||
[JsonSerializable(typeof(FleetState))]
|
||||
[JsonSerializable(typeof(WorkerReply))]
|
||||
[JsonSerializable(typeof(DashboardView))]
|
||||
[JsonSerializable(typeof(LoginView))]
|
||||
[JsonSerializable(typeof(StartLogin))]
|
||||
[JsonSerializable(typeof(LoginResponse))]
|
||||
[JsonSerializable(typeof(SignIn))]
|
||||
[JsonSerializable(typeof(BrowserSession))]
|
||||
[JsonSerializable(typeof(List<SourceUsage>))]
|
||||
public partial class FleetJsonContext : JsonSerializerContext;
|
||||
|
||||
public static class FleetValidation
|
||||
{
|
||||
public static bool Identifier(string? value) => value is { Length: > 0 and <= 64 } &&
|
||||
value.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_');
|
||||
public static void Config(ServerConfig config)
|
||||
{
|
||||
if (config.Accounts is null || config.Machines is null ||
|
||||
config.Accounts.Select(a => a.Id).Distinct().Count() != config.Accounts.Count ||
|
||||
config.Machines.Select(m => m.Id).Distinct().Count() != config.Machines.Count)
|
||||
throw new InvalidDataException("Duplicate or missing configuration.");
|
||||
foreach (var account in config.Accounts)
|
||||
{
|
||||
if (!Identifier(account.Id) || !Enum.IsDefined(account.Provider) || string.IsNullOrWhiteSpace(account.ExpectedEmail))
|
||||
throw new InvalidDataException("Invalid account configuration.");
|
||||
_ = TimeZoneInfo.FindSystemTimeZoneById(account.TimeZone);
|
||||
if (account.HistoryBefore is { } cutoff && (cutoff.UtcTicks % TimeSpan.TicksPerHour != 0 ||
|
||||
!config.Machines.Any(m => m.Id == account.LegacyMachine && m.Profiles.Any(p => p.Id == account.LegacyProfile && p.AccountId == account.Id))))
|
||||
throw new InvalidDataException("Legacy history requires one bound source and an exact UTC hour cutoff.");
|
||||
}
|
||||
foreach (var machine in config.Machines)
|
||||
if (!Identifier(machine.Id) || string.IsNullOrWhiteSpace(machine.OsUser) || machine.Profiles is null ||
|
||||
machine.Profiles.Select(p => p.Id).Distinct().Count() != machine.Profiles.Count ||
|
||||
machine.Profiles.Any(p => !Identifier(p.Id) || !config.Accounts.Any(a => a.Id == p.AccountId)))
|
||||
throw new InvalidDataException("Invalid machine/profile configuration.");
|
||||
}
|
||||
public static bool Counts(TokenCounts c) => c.Input is >= 0 and <= 1_000_000_000_000 && c.Output is >= 0 and <= 1_000_000_000_000 &&
|
||||
c.CacheRead is >= 0 and <= 1_000_000_000_000 && c.CacheWrite is >= 0 and <= 1_000_000_000_000 &&
|
||||
c.ReasoningOutput is >= 0 and <= 1_000_000_000_000 && c.Total is >= 0 and <= 4_000_000_000_000;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,125 @@
|
||||
using FinalToken.Core;
|
||||
|
||||
namespace FinalToken.Fleet;
|
||||
|
||||
public static class FleetAnalysis
|
||||
{
|
||||
public static DashboardView Build(ServerConfig config, FleetState state, DateTimeOffset now)
|
||||
{
|
||||
var machines = config.Machines.Select(m =>
|
||||
{
|
||||
var saved = state.Machines.SingleOrDefault(s => s.MachineId == m.Id);
|
||||
return new MachineView(m.Id, m.Label, m.OsUser, saved is not null && now - saved.SeenAt <= TimeSpan.FromSeconds(90),
|
||||
saved?.SeenAt, saved?.Report.Profiles.Where(p => m.Profiles.Any(b => b.Id == p.Id)).Select(p => p with { Usage = [], Samples = [], LegacyTokens = [] }).ToArray() ?? [], m.Profiles,
|
||||
saved?.Report.Profiles.Where(p => m.Profiles.Any(b => b.Id == p.Id)).Select(p =>
|
||||
{
|
||||
var account = config.Accounts.Single(a => a.Id == m.Profiles.Single(b => b.Id == p.Id).AccountId);
|
||||
var usage = Reconcile(p.Usage, p.Provider, []);
|
||||
return new ProfileConsumption(p.Id, string.Equals(p.DataEmail, account.ExpectedEmail, StringComparison.OrdinalIgnoreCase) ? Sum(usage) : null,
|
||||
usage.Where(u => u.Session is not null).Select(u => u.Session).Distinct().Count());
|
||||
}).ToArray() ?? []);
|
||||
}).ToArray();
|
||||
var accounts = config.Accounts.Select(account => Account(account, config, state, now)).ToArray();
|
||||
return new(now, accounts.OrderByDescending(a => a.Windows.Any(w => !w.Stale)).ToArray(), machines);
|
||||
}
|
||||
private static AccountView Account(AccountConfig account, ServerConfig config, FleetState state, DateTimeOffset now)
|
||||
{
|
||||
List<string> warnings = [];
|
||||
var profiles = (from machine in config.Machines
|
||||
from binding in machine.Profiles where binding.AccountId == account.Id
|
||||
let saved = state.Machines.SingleOrDefault(s => s.MachineId == machine.Id)
|
||||
let profile = saved?.Report.Profiles.SingleOrDefault(p => p.Id == binding.Id)
|
||||
where profile is not null
|
||||
select (Machine: machine.Id, Profile: profile, Saved: saved!)).ToArray();
|
||||
var verified = profiles.Where(p => p.Profile.Provider == account.Provider &&
|
||||
string.Equals(p.Profile.DataEmail, account.ExpectedEmail, StringComparison.OrdinalIgnoreCase)).ToArray();
|
||||
if (verified.Length != profiles.Length) warnings.Add("Unverified or mismatched profiles excluded from this account's analysis.");
|
||||
if (profiles.Any(p => p.Profile.Auth.State != "Healthy")) warnings.Add("One or more CLI logins need attention; previously attributed history is retained.");
|
||||
if (profiles.Length == 0) warnings.Add("No machine has reported this account yet.");
|
||||
if (verified.Any(p => p.Profile.CollectionError is not null)) warnings.Add("A collector failed; retained metadata may be incomplete or stale.");
|
||||
warnings.AddRange(verified.Select(p => p.Profile.CollectionNote).OfType<string>());
|
||||
if (verified.Select(p => (p.Profile.Settings.PaceThreshold,p.Profile.Settings.ProbeInterval)).Distinct().Count() > 1)
|
||||
warnings.Add("Profile analysis settings differ; each window uses the newest observation's source settings.");
|
||||
var records = verified.SelectMany(p => p.Profile.Usage).ToArray();
|
||||
// D4/D14: compute cumulative increases before clipping, or the first post-cutoff
|
||||
// event would charge the already-imported pre-cutoff session total a second time.
|
||||
var allUsage = Reconcile(records, account.Provider, warnings);
|
||||
if (account.Provider == Provider.Codex && account.HistoryBefore is { } cutoff)
|
||||
{
|
||||
var uncertain = allUsage.GroupBy(u => u.Session).Where(g => g.Min(u => u.Time) >= cutoff)
|
||||
.Select(g => g.OrderBy(u => u.Time).First()).ToHashSet();
|
||||
if (uncertain.Count > 0)
|
||||
warnings.Add("Migration baseline unknown for some Codex sessions: their first cumulative totals are omitted; consumption history is incomplete.");
|
||||
allUsage = allUsage.Where(u => !uncertain.Contains(u)).ToArray();
|
||||
}
|
||||
var reconciled = allUsage.Where(u => account.HistoryBefore is null || u.Time >= account.HistoryBefore).ToArray();
|
||||
List<ModelTokenPoint> tokens = reconciled.Select(u => new ModelTokenPoint(Hour(u.Time), u.Model, u.Counts)).ToList();
|
||||
if (account.HistoryBefore is { } before)
|
||||
{
|
||||
var legacy = verified.SingleOrDefault(p => p.Machine == account.LegacyMachine && p.Profile.Id == account.LegacyProfile).Profile;
|
||||
if (legacy is null) warnings.Add("Designated legacy history source is unavailable or unverified.");
|
||||
else tokens.AddRange(legacy.LegacyTokens.Where(t => t.Time < before));
|
||||
warnings.Add("Before the migration cutoff, history uses one designated machine; cross-machine attribution is unavailable.");
|
||||
}
|
||||
tokens = tokens.GroupBy(t => (t.Time, t.Model)).Select(g => new ModelTokenPoint(g.Key.Time, g.Key.Model,
|
||||
g.Aggregate(new TokenCounts(), (sum, t) => sum + t.Counts))).OrderBy(t => t.Time).ToList();
|
||||
var observations = verified.SelectMany(p => p.Profile.Samples).Distinct().ToArray();
|
||||
List<WindowView> windows = [];
|
||||
foreach (var series in observations.GroupBy(WindowSeries.For))
|
||||
{
|
||||
var window = series.OrderBy(w => w.SampleTime).ThenBy(w => w.Id, StringComparer.Ordinal).Last();
|
||||
var owner = verified.Where(p => p.Profile.Samples.Contains(window)).OrderByDescending(p => p.Saved.SeenAt).First();
|
||||
var stale = now - window.SampleTime > owner.Profile.Settings.ProbeInterval * 3 || owner.Profile.Auth.State != "Healthy" ||
|
||||
!owner.Profile.Settings.For(account.Provider).Enabled ||
|
||||
now - owner.Saved.SeenAt > TimeSpan.FromSeconds(90) || window.ResetsAt <= now;
|
||||
var settings = owner.Profile.Settings;
|
||||
if (settings.For(account.Provider).IsHidden(window)) continue;
|
||||
var pace = stale ? new PaceResult(PaceState.Unknown) : Pace.Calculate(window, now, settings.PaceThreshold);
|
||||
var forecast = stale ? null : LimitAnalysis.AverageUseAtReset(window, now, pace);
|
||||
var zone = TimeZoneInfo.FindSystemTimeZoneById(account.TimeZone);
|
||||
windows.Add(new(window, stale, pace, forecast, forecast is null ? null : 100 - forecast,
|
||||
stale ? null : LimitAnalysis.Recent(window, series, now, pace),
|
||||
stale ? null : LimitAnalysis.Analyze(window, series, tokens, now, zone),
|
||||
window.Length > TimeSpan.FromDays(1) ? LimitAnalysis.Resets(window, series, tokens, now.AddDays(-90), now, zone) : null));
|
||||
}
|
||||
if (windows.Count == 0) warnings.Add("Provider allowance unknown. Token costs cannot establish subscription capacity.");
|
||||
if (windows.Any(w => w.Stale)) warnings.Add("Stale or expired allowance: forecasts withheld until a fresh CLI observation.");
|
||||
var costs = tokens.Select(t => (Point: t, Value: ApiPrices.Value(account.Provider, t.Model, t.Counts))).ToArray();
|
||||
var priced = costs.Where(c => c.Value is not null).ToArray();
|
||||
return new(account, windows.OrderByDescending(w => w.Window.Length).ToArray(), tokens,
|
||||
tokens.Aggregate(new TokenCounts(), (sum, t) => sum + t.Counts), priced.Length == 0 ? null : priced.Sum(c => c.Value!.Value),
|
||||
costs.Where(c => c.Value is null).Sum(c => c.Point.Counts.Total), warnings.Distinct().ToArray(), ApiPrices.CheckedOn,
|
||||
reconciled.Where(u => u.Session is not null).GroupBy(u => u.Session!).Select(g => new SessionConsumption(g.Key, Sum(g)))
|
||||
.OrderByDescending(s => s.Tokens.Total).ToArray(), verified.Length > 0);
|
||||
}
|
||||
private static TokenCounts Sum(IEnumerable<SourceUsage> events) => events.Aggregate(new TokenCounts(), (sum,u) => sum + u.Counts);
|
||||
private static IReadOnlyList<SourceUsage> Reconcile(IEnumerable<SourceUsage> records, Provider provider, List<string> warnings)
|
||||
{
|
||||
List<SourceUsage> result = [];
|
||||
if (provider == Provider.Claude)
|
||||
{
|
||||
foreach (var group in records.GroupBy(u => u.Key))
|
||||
{
|
||||
if (group.Select(u => (u.Time,u.Model,u.Counts)).Distinct().Count() != 1)
|
||||
{ warnings.Add("Conflicting response metadata excluded; consumption is incomplete."); continue; }
|
||||
if (group.Select(u => u.Session).Distinct().Count() > 1)
|
||||
warnings.Add("Shared/resumed responses are assigned once to a stable session id; session attribution is approximate.");
|
||||
result.Add(group.OrderBy(u => u.Session, StringComparer.Ordinal).First());
|
||||
}
|
||||
}
|
||||
else
|
||||
foreach (var session in records.GroupBy(u => u.Session))
|
||||
{
|
||||
var previous = new TokenCounts();
|
||||
foreach (var group in session.GroupBy(u => u.Time).OrderBy(g => g.Key))
|
||||
{
|
||||
if (group.Select(u => (u.Model,u.Counts)).Distinct().Count() != 1)
|
||||
{ warnings.Add("Conflicting session metadata excluded; consumption is incomplete."); continue; }
|
||||
var value = group.First();
|
||||
result.Add(value with { Counts = value.Counts.IncreaseFrom(previous) }); previous = value.Counts;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
private static DateTimeOffset Hour(DateTimeOffset t) => new(t.UtcTicks - t.UtcTicks % TimeSpan.TicksPerHour, TimeSpan.Zero);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using System.Text.Json;
|
||||
using FinalToken.Core;
|
||||
|
||||
namespace FinalToken.Fleet;
|
||||
|
||||
/// <summary>D14: only durable metadata. LoginCoordinator has a separate, memory-only lifetime.</summary>
|
||||
public sealed class FleetStore
|
||||
{
|
||||
private readonly SemaphoreSlim gate = new(1, 1);
|
||||
private readonly string path;
|
||||
private FleetState state;
|
||||
public ServerConfig Config { get; }
|
||||
public FleetStore(string directory, ServerConfig config)
|
||||
{
|
||||
FleetValidation.Config(config);
|
||||
Config = config;
|
||||
path = Path.Combine(directory, "fleet.json");
|
||||
state = File.Exists(path) ? JsonSerializer.Deserialize(SharedFile.ReadAllText(path), FleetJsonContext.Default.FleetState)
|
||||
?? throw new InvalidDataException("Invalid fleet state; refusing overwrite.") : new([]);
|
||||
}
|
||||
public FleetState Current => Volatile.Read(ref state);
|
||||
public void Validate(WorkerReport report, string authenticatedMachine, DateTimeOffset now)
|
||||
{
|
||||
var machine = Config.Machines.Single(m => m.Id == authenticatedMachine);
|
||||
if (report.MachineId != machine.Id || report.OsUser != machine.OsUser ||
|
||||
string.IsNullOrWhiteSpace(report.BootId) || report.BootId.Length > 64 ||
|
||||
report.CollectedAt > now.AddMinutes(2) || report.Profiles is null || report.Logins is null ||
|
||||
report.Logins.Count > 200 || report.Profiles.Count != machine.Profiles.Count ||
|
||||
report.Logins.Any(u => u is null || !FleetValidation.Identifier(u.Id) || !FleetValidation.Identifier(u.ProfileId) ||
|
||||
u.State is not { Length: > 0 and <= 40 } || u.Url?.Length > 16384 || u.DeviceCode?.Length > 24 || u.Email?.Length > 320) ||
|
||||
report.Profiles.Any(p => p is null) ||
|
||||
report.Profiles.Select(p => p.Id).Distinct().Count() != report.Profiles.Count)
|
||||
throw new InvalidDataException("Machine/user/profile mismatch or invalid report.");
|
||||
foreach (var profile in report.Profiles)
|
||||
{
|
||||
var binding = machine.Profiles.SingleOrDefault(p => p.Id == profile.Id) ?? throw new InvalidDataException("Unknown profile.");
|
||||
var account = Config.Accounts.Single(a => a.Id == binding.AccountId);
|
||||
if (profile.Provider != account.Provider || profile.Auth is null || profile.Settings is not { IsValid: true } ||
|
||||
profile.Usage is null || profile.Samples is null || profile.LegacyTokens is null ||
|
||||
profile.Usage.Count > 100_000 || profile.Samples.Count > 30_000 || profile.LegacyTokens.Count > 100_000 ||
|
||||
profile.Auth.Email?.Length > 320 || profile.DataEmail?.Length > 320 || profile.CollectionNote?.Length > 300 ||
|
||||
profile.Auth.Reason is not { Length: <= 300 } || profile.Auth.State is not { Length: > 0 and <= 40 } || profile.CollectionError?.Length > 300 ||
|
||||
profile.Auth.CheckedAt > now.AddMinutes(2) ||
|
||||
profile.Usage.Any(u => u is null || u.Key is not { Length: > 0 and <= 512 } || u.Session?.Length > 256 || u.Model?.Length > 160 ||
|
||||
u.Time > now.AddMinutes(2) || !FleetValidation.Counts(u.Counts) || (profile.Provider == Provider.Codex && string.IsNullOrWhiteSpace(u.Session))) ||
|
||||
profile.Samples.Any(w => w is null || w.Provider != profile.Provider || w.Id is not { Length: > 0 and <= 160 } || w.Label is not { Length: <= 160 } || w.Source is not { Length: <= 80 } ||
|
||||
!double.IsFinite(w.UsedPercent) || w.UsedPercent is < 0 or > 100 || w.Length is { Ticks: <= 0 } ||
|
||||
w.Length > TimeSpan.FromDays(366) || w.SampleTime > now.AddMinutes(2)) ||
|
||||
profile.LegacyTokens.Any(p => p is null || p.Model?.Length > 160 || !FleetValidation.Counts(p.Counts) || p.Time > now.AddMinutes(2)))
|
||||
throw new InvalidDataException("Invalid or oversized profile metadata.");
|
||||
}
|
||||
}
|
||||
public async Task AcceptAsync(WorkerReport report, string authenticatedMachine, DateTimeOffset now, CancellationToken token = default)
|
||||
{
|
||||
Validate(report, authenticatedMachine, now);
|
||||
await gate.WaitAsync(token);
|
||||
try
|
||||
{
|
||||
var old = state.Machines.SingleOrDefault(m => m.MachineId == report.MachineId);
|
||||
if (old is not null && report.CollectedAt < old.Report.CollectedAt) throw new InvalidDataException("Out-of-order report.");
|
||||
// D14: a starting/reinstalled worker cannot erase acknowledged historical metadata.
|
||||
// Values are source identities/absolute hourly values, never additive report counters.
|
||||
var merged = report.Profiles.Select(profile =>
|
||||
{
|
||||
var prior = old?.Report.Profiles.SingleOrDefault(p => p.Id == profile.Id);
|
||||
if (prior is null) return profile;
|
||||
if (profile.DataEmail is not null && prior.DataEmail is not null &&
|
||||
!string.Equals(profile.DataEmail, prior.DataEmail, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidDataException("Profile attribution changed; configure a separate profile.");
|
||||
return profile with
|
||||
{
|
||||
DataEmail = profile.DataEmail ?? prior.DataEmail,
|
||||
Usage = prior.Usage.Union(profile.Usage).ToArray(),
|
||||
Samples = prior.Samples.Union(profile.Samples).ToArray(),
|
||||
LegacyTokens = prior.LegacyTokens.Concat(profile.LegacyTokens).GroupBy(p => (p.Time,p.Model)).Select(g => g.Last()).ToArray()
|
||||
};
|
||||
}).ToArray();
|
||||
var next = new FleetState(state.Machines.Where(m => m.MachineId != report.MachineId)
|
||||
.Append(new(report.MachineId, now, report with { Profiles = merged, Logins = [] })).ToArray());
|
||||
await AtomicFile.WriteAsync(path, JsonSerializer.Serialize(next, FleetJsonContext.Default.FleetState), token);
|
||||
Volatile.Write(ref state, next);
|
||||
}
|
||||
finally { gate.Release(); }
|
||||
}
|
||||
public DashboardView Dashboard(DateTimeOffset now) => FleetAnalysis.Build(Config, Current, now);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
namespace FinalToken.Fleet;
|
||||
|
||||
/// <summary>D14: short-lived routing state only. Never serialized or logged.</summary>
|
||||
public sealed class LoginCoordinator(ServerConfig config)
|
||||
{
|
||||
private sealed class Pending(string id, string owner, string machine, string profile, string boot, DateTimeOffset expires)
|
||||
{
|
||||
public readonly string Id = id, Owner = owner, Machine = machine, Profile = profile, Boot = boot;
|
||||
public readonly DateTimeOffset Expires = expires;
|
||||
public string State = "Queued";
|
||||
public string? Url, DeviceCode, Email, Response;
|
||||
public bool InputAccepted;
|
||||
public LoginView View => new(Id, Machine, Profile, State, Expires, Url, DeviceCode, Email);
|
||||
}
|
||||
private readonly Lock gate = new();
|
||||
private readonly Dictionary<string, Pending> pending = [];
|
||||
private static bool Terminal(string state) => state is "Succeeded" or "Failed" or "Cancelled" or "TimedOut" or "AccountMismatch" or "IdentityUnknown" or "WorkerRestarted";
|
||||
public LoginView Start(string owner, string machine, string profile, FleetState fleet, DateTimeOffset now)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
Expire(now);
|
||||
var definition = config.Machines.SingleOrDefault(m => m.Id == machine);
|
||||
if (definition is null || !definition.Profiles.Any(p => p.Id == profile)) throw new InvalidDataException("Unknown machine/profile.");
|
||||
var saved = fleet.Machines.SingleOrDefault(m => m.MachineId == machine);
|
||||
if (saved is null || now - saved.SeenAt > TimeSpan.FromSeconds(90)) throw new InvalidDataException("Machine is offline.");
|
||||
if (pending.Values.Any(p => p.Machine == machine && p.Profile == profile && !Terminal(p.State)))
|
||||
throw new InvalidDataException("A login is already pending for this profile.");
|
||||
if (pending.Count >= 100) throw new InvalidDataException("Too many login attempts; wait for expiry.");
|
||||
var id = Guid.NewGuid().ToString("N");
|
||||
var entry = new Pending(id, owner, machine, profile, saved.Report.BootId, now.AddMinutes(15));
|
||||
pending.Add(id, entry); return entry.View;
|
||||
}
|
||||
}
|
||||
public LoginView Get(string id, string owner, DateTimeOffset now)
|
||||
{
|
||||
lock (gate) { Expire(now); return Owned(id, owner).View; }
|
||||
}
|
||||
public void Respond(string id, string owner, string response, DateTimeOffset now)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
Expire(now); var entry = Owned(id, owner);
|
||||
var binding = config.Machines.Single(m => m.Id == entry.Machine).Profiles.Single(p => p.Id == entry.Profile);
|
||||
if (config.Accounts.Single(a => a.Id == binding.AccountId).Provider != Core.Provider.Claude ||
|
||||
entry.State != "WaitingForCode" || entry.InputAccepted || entry.Response is not null)
|
||||
throw new InvalidDataException("This login is not waiting for an authorization response.");
|
||||
if (string.IsNullOrWhiteSpace(response) || response.Length > 2048 || response.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not ('_' or '-' or '.' or '#')))
|
||||
throw new InvalidDataException("Paste only the official authorization code, not a URL or credential file.");
|
||||
entry.Response = response;
|
||||
}
|
||||
}
|
||||
public void Cancel(string id, string owner, DateTimeOffset now)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
Expire(now); var p = Owned(id, owner);
|
||||
if (!Terminal(p.State)) { p.State = "Cancelling"; Clear(p); }
|
||||
}
|
||||
}
|
||||
public WorkerReply Exchange(string machine, string boot, IReadOnlyList<LoginUpdate> updates, DateTimeOffset now)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
Expire(now);
|
||||
foreach (var p in pending.Values.Where(p => p.Machine == machine && !Terminal(p.State)))
|
||||
if (p.Boot != boot) { p.State = "WorkerRestarted"; Clear(p); }
|
||||
foreach (var update in updates)
|
||||
{
|
||||
if (!pending.TryGetValue(update.Id, out var p) || p.Machine != machine || p.Boot != boot ||
|
||||
p.Profile != update.ProfileId || Terminal(p.State)) continue;
|
||||
if (update.State is not ("Starting" or "WaitingForBrowser" or "WaitingForCode" or "Verifying" or "Succeeded" or "Failed" or "Cancelled" or "TimedOut" or "AccountMismatch" or "IdentityUnknown")) continue;
|
||||
if (p.State == "Cancelling" && !Terminal(update.State)) continue;
|
||||
var binding = config.Machines.Single(m => m.Id == machine).Profiles.Single(b => b.Id == p.Profile);
|
||||
var account = config.Accounts.Single(a => a.Id == binding.AccountId);
|
||||
if (update.Url is not null && !LoginOutput.OfficialUrl(account.Provider, update.Url)) continue;
|
||||
p.State = update.State;
|
||||
p.Url = update.Url;
|
||||
p.DeviceCode = update.DeviceCode is { Length: <= 24 } code && code.All(c => char.IsAsciiLetterOrDigit(c) || c == '-') ? code : null;
|
||||
p.Email = update.Email is { Length: <= 320 } ? update.Email : null;
|
||||
p.InputAccepted |= update.InputAccepted;
|
||||
if (p.State == "Succeeded" && !string.Equals(account.ExpectedEmail, p.Email, StringComparison.OrdinalIgnoreCase)) p.State = "AccountMismatch";
|
||||
if (p.InputAccepted) p.Response = null;
|
||||
if (Terminal(p.State)) Clear(p);
|
||||
}
|
||||
return new(pending.Values.Where(p => p.Machine == machine && p.Boot == boot &&
|
||||
(!Terminal(p.State) || p.State is "Cancelled" or "TimedOut"))
|
||||
.Select(p => new LoginCommand(p.Id, p.Profile, p.Expires, Terminal(p.State) || p.State == "Cancelling", p.Response)).ToArray());
|
||||
}
|
||||
}
|
||||
private Pending Owned(string id, string owner) => pending.TryGetValue(id, out var p) && p.Owner == owner
|
||||
? p : throw new KeyNotFoundException("Login not found in this browser session.");
|
||||
private void Expire(DateTimeOffset now)
|
||||
{
|
||||
foreach (var p in pending.Values)
|
||||
if (p.Expires <= now && !Terminal(p.State)) { p.State = "TimedOut"; Clear(p); }
|
||||
foreach (var p in pending.Values.Where(p => p.Expires.AddMinutes(15) < now).ToArray()) pending.Remove(p.Id);
|
||||
}
|
||||
private static void Clear(Pending p) { p.Url = null; p.DeviceCode = null; p.Response = null; }
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using System.Text.Json;
|
||||
using FinalToken.Core;
|
||||
using FinalToken.Core.Collectors;
|
||||
using FinalToken.Core.Processes;
|
||||
|
||||
namespace FinalToken.Fleet;
|
||||
|
||||
/// <summary>Independent metadata export cursors preserve response/session identities across rescans and offline restarts.</summary>
|
||||
public sealed class ProfileCollector
|
||||
{
|
||||
private readonly WorkerProfile profile;
|
||||
private readonly string directory;
|
||||
private readonly Dictionary<string, SourceUsage> records;
|
||||
private readonly HistoryStore cursors;
|
||||
private readonly IncrementalScanner scanner;
|
||||
private ProfileReport? previous;
|
||||
private DateTimeOffset lastProbe = DateTimeOffset.MinValue;
|
||||
private readonly DiagnosticLog diagnostics = new();
|
||||
public ProfileCollector(WorkerProfile profile, string stateDirectory)
|
||||
{
|
||||
this.profile = profile;
|
||||
directory = Path.Combine(stateDirectory, profile.Id);
|
||||
Directory.CreateDirectory(directory); Directory.CreateDirectory(profile.DataDirectory);
|
||||
var ledger = Path.Combine(directory, "usage.json");
|
||||
var loaded = File.Exists(ledger) ? JsonSerializer.Deserialize(SharedFile.ReadAllText(ledger), FleetJsonContext.Default.ListSourceUsage)
|
||||
?? throw new InvalidDataException("Invalid usage export; refusing overwrite.") : [];
|
||||
records = loaded.ToDictionary(Key, StringComparer.Ordinal);
|
||||
var saved = Path.Combine(directory, "profile.json");
|
||||
if (File.Exists(saved))
|
||||
{
|
||||
var report = JsonSerializer.Deserialize(SharedFile.ReadAllText(saved), FleetJsonContext.Default.WorkerReport);
|
||||
previous = report?.Profiles.SingleOrDefault();
|
||||
}
|
||||
cursors = new(Path.Combine(directory, "scan"), diagnostics);
|
||||
scanner = new(cursors, diagnostics,
|
||||
profile.Provider == Provider.Claude ? profile.ConfigDirectory : Path.Combine(directory, "no-claude"),
|
||||
profile.Provider == Provider.Codex ? profile.ConfigDirectory : Path.Combine(directory, "no-codex"), Observe);
|
||||
}
|
||||
private string Key(SourceUsage u) => profile.Provider == Provider.Claude ? u.Key : $"{u.Session!.Length}:{u.Session}:{u.Time:O}";
|
||||
private void Observe(UsageEvent usage, string? session)
|
||||
{
|
||||
// Original source ids survive cross-machine copies. Never transmit project paths or message text.
|
||||
var value = new SourceUsage(usage.DedupeKey, session, usage.Time, usage.Model, usage.Counts);
|
||||
var key = Key(value);
|
||||
if (!records.ContainsKey(key) && records.Count >= 100_000) throw new InvalidDataException("Metadata export is full; increase capacity with an explicit retention design.");
|
||||
records[key] = value;
|
||||
}
|
||||
public async Task<ProfileReport> CollectAsync(CancellationToken token)
|
||||
{
|
||||
var auth = await CliAuthentication.ReadAsync(profile, token: token);
|
||||
var settings = SettingsFile.Load(profile.DataDirectory, diagnostics);
|
||||
if (!settings.For(profile.Provider).Enabled)
|
||||
return (previous ?? new(profile.Id, profile.Provider, auth, settings, [], [], [])) with
|
||||
{ Auth = auth, Settings = settings, CollectionNote = "Collection is disabled in this profile's existing settings." };
|
||||
if (auth.State != "Healthy") return (previous ?? new(profile.Id, profile.Provider, auth, settings, [], [], [])) with { Auth = auth };
|
||||
if (previous?.DataEmail is { } old && !string.Equals(old, auth.Email, StringComparison.OrdinalIgnoreCase))
|
||||
return previous with { Auth = auth with { State = "AccountMismatch", Reason = "Profile account changed; use a separate worker profile/state directory." } };
|
||||
try
|
||||
{
|
||||
var scan = await scanner.ScanAsync(token, profile.Provider == Provider.Claude, profile.Provider == Provider.Codex);
|
||||
// Persist records BEFORE cursor progress: a crash can replay metadata, but cannot lose an event.
|
||||
await AtomicFile.WriteAsync(Path.Combine(directory, "usage.json"),
|
||||
JsonSerializer.Serialize(records.Values.ToList(), FleetJsonContext.Default.ListSourceUsage), token);
|
||||
await cursors.SaveAsync(token);
|
||||
// The existing store remains the authoritative local history/settings. A desktop host may own it.
|
||||
using (var storeLock = StoreLock.TryAcquire(profile.DataDirectory))
|
||||
{
|
||||
if (storeLock is not null)
|
||||
{
|
||||
await using var engine = new RefreshEngine(profile.DataDirectory, processRunner: new ProfileRunner(profile),
|
||||
claudeDirectory: profile.Provider == Provider.Claude ? profile.ConfigDirectory : Path.Combine(directory, "no-claude"),
|
||||
codexDirectory: profile.Provider == Provider.Codex ? profile.ConfigDirectory : Path.Combine(directory, "no-codex"),
|
||||
cliDiscovery: (provider, path) => provider == profile.Provider && (provider != Provider.Claude || profile.EnableLegacyClaudeProbe)
|
||||
? CliDiscovery.Find(provider, profile.CliPath ?? path) : new(null, "Provider probe disabled for this worker profile."));
|
||||
var since = DateTimeOffset.UtcNow - lastProbe;
|
||||
var probeDue = since >= TimeSpan.FromMinutes(1) && (since >= settings.ProbeInterval || scan.AddedEvents > 0);
|
||||
if (probeDue) lastProbe = DateTimeOffset.UtcNow;
|
||||
await engine.RefreshNowAsync(noProbe: !probeDue, cancellationToken: token);
|
||||
}
|
||||
}
|
||||
var history = new HistoryStore(profile.DataDirectory, diagnostics);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var samples = history.LimitSamples(profile.Provider, DateTimeOffset.MinValue, now.AddMinutes(1))
|
||||
.Concat(history.LatestLimits(profile.Provider)).Concat(scan.CodexFallback).Distinct().ToArray();
|
||||
var legacy = history.TokenSeriesByModel(profile.Provider, DateTimeOffset.MinValue, now.AddHours(1), SeriesInterval.Hour);
|
||||
previous = new(profile.Id, profile.Provider, auth, settings, records.Values.ToArray(), samples, legacy,
|
||||
DataEmail: auth.Email, CollectionNote: profile.Provider == Provider.Claude && !profile.EnableLegacyClaudeProbe
|
||||
? "Claude quota probe is disabled; only existing observed quota history is available." : null);
|
||||
await AtomicFile.WriteAsync(Path.Combine(directory, "profile.json"), JsonSerializer.Serialize(
|
||||
new WorkerReport("local", Environment.UserName, "persisted", now, [previous], []), FleetJsonContext.Default.WorkerReport), token);
|
||||
return previous;
|
||||
}
|
||||
catch (Exception) when (!token.IsCancellationRequested)
|
||||
{
|
||||
return (previous ?? new(profile.Id, profile.Provider, auth, settings, [], [], [])) with
|
||||
{ Auth = auth, CollectionError = "Metadata collection failed; previous data retained." };
|
||||
}
|
||||
}
|
||||
private sealed class ProfileRunner(WorkerProfile profile) : IProcessRunner
|
||||
{
|
||||
public Task<ProcessResult> RunAsync(ProcessRequest request, CancellationToken token) => new ProcessRunner().RunAsync(
|
||||
request with { EnvironmentOverrides = CliAuthentication.EnvironmentFor(profile) }, token);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# Web
|
||||
Authenticated private dashboard. All JSON uses FleetJsonContext. No request-body logging. Login responses stay in memory, session-bound and profile-bound; never serialize LoginCoordinator into durable state. Browser code uses textContent for external metadata. See D14.
|
||||
@@ -0,0 +1,39 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace FinalToken.Web;
|
||||
|
||||
public sealed class BrowserSessions
|
||||
{
|
||||
private sealed record Session(string Csrf, DateTimeOffset Expires);
|
||||
private readonly Lock gate = new();
|
||||
private readonly Dictionary<string, Session> sessions = [];
|
||||
private readonly Dictionary<string, (DateTimeOffset Since, int Count)> attempts = [];
|
||||
public static bool Matches(string? supplied, string expected) => supplied is not null &&
|
||||
CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(supplied)), SHA256.HashData(Encoding.UTF8.GetBytes(expected)));
|
||||
public bool AllowAttempt(string address, DateTimeOffset now)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
foreach (var key in attempts.Where(p => now - p.Value.Since >= TimeSpan.FromMinutes(1)).Select(p => p.Key).ToArray()) attempts.Remove(key);
|
||||
if (!attempts.TryGetValue(address, out var value))
|
||||
{ if (attempts.Count >= 1000) return false; value = (now, 0); }
|
||||
attempts[address] = (value.Since, value.Count + 1);
|
||||
return value.Count < 10;
|
||||
}
|
||||
}
|
||||
public (string Id, string Csrf) Create(DateTimeOffset now)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
foreach (var expired in sessions.Where(s => s.Value.Expires <= now).Select(s => s.Key).ToArray()) sessions.Remove(expired);
|
||||
if (sessions.Count >= 100) throw new InvalidDataException("Too many dashboard sessions.");
|
||||
var id = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
|
||||
var csrf = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
|
||||
sessions.Add(id, new(csrf, now.AddHours(8))); return (id, csrf);
|
||||
}
|
||||
}
|
||||
public string? Csrf(string? id, DateTimeOffset now)
|
||||
{ lock (gate) return id is not null && sessions.TryGetValue(id, out var s) && s.Expires > now ? s.Csrf : null; }
|
||||
public void Remove(string? id) { lock (gate) if (id is not null) sessions.Remove(id); }
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup><PublishAot>true</PublishAot><EnableRequestDelegateGenerator>true</EnableRequestDelegateGenerator></PropertyGroup>
|
||||
<ItemGroup><ProjectReference Include="../FinalToken.Fleet/FinalToken.Fleet.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,107 @@
|
||||
using System.Text.Json;
|
||||
using FinalToken.Core;
|
||||
using FinalToken.Fleet;
|
||||
using FinalToken.Web;
|
||||
|
||||
var configPath = Environment.GetEnvironmentVariable("FINALTOKEN_SERVER_CONFIG") ?? "server.json";
|
||||
var directory = Environment.GetEnvironmentVariable("FINALTOKEN_SERVER_DATA") ?? Path.Combine(DataPaths.DataDirectory, "server");
|
||||
var config = JsonSerializer.Deserialize(File.ReadAllText(configPath), FleetJsonContext.Default.ServerConfig)
|
||||
?? throw new InvalidDataException("Invalid server configuration.");
|
||||
var dashboardKey = Environment.GetEnvironmentVariable("FINALTOKEN_DASHBOARD_KEY");
|
||||
if (dashboardKey is not { Length: >= 32 }) throw new InvalidDataException("Set FINALTOKEN_DASHBOARD_KEY to a random key of at least 32 characters.");
|
||||
var machineKeys = config.Machines.ToDictionary(m => m.Id, m => Environment.GetEnvironmentVariable("FINALTOKEN_MACHINE_" + m.Id));
|
||||
if (machineKeys.Values.Any(k => k is not { Length: >= 32 }) || machineKeys.Values.Append(dashboardKey).Distinct().Count() != machineKeys.Count + 1)
|
||||
throw new InvalidDataException("Set a separate random FINALTOKEN_MACHINE_<id> key for every machine.");
|
||||
var publicOrigin = Environment.GetEnvironmentVariable("FINALTOKEN_PUBLIC_ORIGIN") ?? "http://127.0.0.1:5187";
|
||||
if (!Uri.TryCreate(publicOrigin, UriKind.Absolute, out var origin) || origin.AbsolutePath != "/" || origin.UserInfo.Length != 0 ||
|
||||
origin.Query.Length != 0 || origin.Fragment.Length != 0 || !(origin.Scheme == "https" || origin.Scheme == "http" && origin.IsLoopback))
|
||||
throw new InvalidDataException("Public origin must be HTTPS, or loopback HTTP for local development.");
|
||||
using var serverLock = StoreLock.TryAcquire(directory) ?? throw new InvalidDataException("Server data directory is already in use.");
|
||||
var store = new FleetStore(directory, config);
|
||||
var logins = new LoginCoordinator(config);
|
||||
var sessions = new BrowserSessions();
|
||||
var builder = WebApplication.CreateSlimBuilder(args);
|
||||
builder.Logging.ClearProviders(); // Never log request bodies, authorization codes, CLI output or URL query strings.
|
||||
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_URLS"))) builder.WebHost.UseUrls("http://127.0.0.1:5187");
|
||||
builder.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = 32 * 1024 * 1024);
|
||||
builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.TypeInfoResolverChain.Insert(0, FleetJsonContext.Default));
|
||||
var app = builder.Build();
|
||||
app.Use(async (ctx, next) =>
|
||||
{
|
||||
ctx.Response.Headers.CacheControl = "no-store";
|
||||
ctx.Response.Headers["Referrer-Policy"] = "no-referrer";
|
||||
ctx.Response.Headers["X-Content-Type-Options"] = "nosniff";
|
||||
ctx.Response.Headers["Content-Security-Policy"] = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
|
||||
var worker = ctx.Request.Path == "/worker/report";
|
||||
if (worker)
|
||||
{
|
||||
var id = ctx.Request.Headers["X-FinalToken-Machine"].ToString();
|
||||
var auth = ctx.Request.Headers.Authorization.ToString();
|
||||
if (!machineKeys.TryGetValue(id, out var key) || !auth.StartsWith("Bearer ", StringComparison.Ordinal) || !BrowserSessions.Matches(auth[7..], key!))
|
||||
{ ctx.Response.StatusCode = 401; return; }
|
||||
ctx.Items["machine"] = id;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Pin Host and Origin. Reverse proxies terminate HTTPS and must preserve the public Host.
|
||||
if (!string.Equals(ctx.Request.Host.Value, origin.Authority, StringComparison.OrdinalIgnoreCase)) { ctx.Response.StatusCode = 400; return; }
|
||||
if (ctx.Request.Method != "GET" && (ctx.Request.Headers["X-FinalToken"] != "1" ||
|
||||
ctx.Request.Headers.Origin.Count > 0 && !ctx.Request.Headers.Origin.ToString().Equals(origin.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase)))
|
||||
{ ctx.Response.StatusCode = 403; return; }
|
||||
if (ctx.Request.Path.StartsWithSegments("/api"))
|
||||
{
|
||||
var session = ctx.Request.Cookies["finaltoken"];
|
||||
var csrf = sessions.Csrf(session, DateTimeOffset.UtcNow);
|
||||
if (csrf is null) { ctx.Response.StatusCode = 401; return; }
|
||||
if (ctx.Request.Method != "GET" && !BrowserSessions.Matches(ctx.Request.Headers["X-CSRF"], csrf))
|
||||
{ ctx.Response.StatusCode = 403; return; }
|
||||
ctx.Items["session"] = session; ctx.Items["csrf"] = csrf;
|
||||
}
|
||||
}
|
||||
try { await next(ctx); }
|
||||
catch (KeyNotFoundException) { ctx.Response.StatusCode = 404; }
|
||||
catch (InvalidDataException) { ctx.Response.StatusCode = 409; await ctx.Response.WriteAsync("Operation rejected: profile, login state or metadata is invalid."); }
|
||||
catch (BadHttpRequestException) { ctx.Response.StatusCode = 400; }
|
||||
catch (JsonException) { ctx.Response.StatusCode = 400; }
|
||||
catch (OperationCanceledException) when (ctx.RequestAborted.IsCancellationRequested) { }
|
||||
catch (Exception) { ctx.Response.StatusCode = 500; await ctx.Response.WriteAsync("Operation failed; no secret details are logged."); }
|
||||
});
|
||||
app.MapPost("/session", async (HttpContext ctx) =>
|
||||
{
|
||||
if (!sessions.AllowAttempt(ctx.Connection.RemoteIpAddress?.ToString() ?? "unknown", DateTimeOffset.UtcNow)) return Results.StatusCode(429);
|
||||
var input = await ctx.Request.ReadFromJsonAsync(FleetJsonContext.Default.SignIn, ctx.RequestAborted);
|
||||
if (!BrowserSessions.Matches(input?.Key, dashboardKey)) return Results.Unauthorized();
|
||||
sessions.Remove(ctx.Request.Cookies["finaltoken"]);
|
||||
var session = sessions.Create(DateTimeOffset.UtcNow);
|
||||
ctx.Response.Cookies.Append("finaltoken", session.Id, new CookieOptions { HttpOnly = true, Secure = origin.Scheme == "https", SameSite = SameSiteMode.Strict, Path = "/", MaxAge = TimeSpan.FromHours(8) });
|
||||
return Results.Json(new BrowserSession(session.Csrf), FleetJsonContext.Default.BrowserSession);
|
||||
});
|
||||
app.MapGet("/api/session", (HttpContext ctx) => Results.Json(new BrowserSession((string)ctx.Items["csrf"]!), FleetJsonContext.Default.BrowserSession));
|
||||
app.MapPost("/api/logout", (HttpContext ctx) => { sessions.Remove(ctx.Request.Cookies["finaltoken"]); ctx.Response.Cookies.Delete("finaltoken"); return Results.NoContent(); });
|
||||
app.MapGet("/api/dashboard", () => Results.Json(store.Dashboard(DateTimeOffset.UtcNow), FleetJsonContext.Default.DashboardView));
|
||||
app.MapPost("/api/logins", async (HttpContext ctx) =>
|
||||
{
|
||||
var input = await ctx.Request.ReadFromJsonAsync(FleetJsonContext.Default.StartLogin, ctx.RequestAborted) ?? throw new InvalidDataException();
|
||||
return Results.Json(logins.Start((string)ctx.Items["session"]!, input.MachineId, input.ProfileId, store.Current, DateTimeOffset.UtcNow), FleetJsonContext.Default.LoginView);
|
||||
});
|
||||
app.MapGet("/api/logins/{id}", (HttpContext ctx, string id) => Results.Json(logins.Get(id, (string)ctx.Items["session"]!, DateTimeOffset.UtcNow), FleetJsonContext.Default.LoginView));
|
||||
app.MapPost("/api/logins/{id}/response", async (HttpContext ctx, string id) =>
|
||||
{
|
||||
var input = await ctx.Request.ReadFromJsonAsync(FleetJsonContext.Default.LoginResponse, ctx.RequestAborted) ?? throw new InvalidDataException();
|
||||
logins.Respond(id, (string)ctx.Items["session"]!, input.Response, DateTimeOffset.UtcNow); return Results.NoContent();
|
||||
});
|
||||
app.MapPost("/api/logins/{id}/cancel", (HttpContext ctx, string id) => { logins.Cancel(id, (string)ctx.Items["session"]!, DateTimeOffset.UtcNow); return Results.NoContent(); });
|
||||
app.MapPost("/worker/report", async (HttpContext ctx) =>
|
||||
{
|
||||
var report = await ctx.Request.ReadFromJsonAsync(FleetJsonContext.Default.WorkerReport, ctx.RequestAborted) ?? throw new InvalidDataException();
|
||||
var machine = (string)ctx.Items["machine"]!;
|
||||
await store.AcceptAsync(report, machine, DateTimeOffset.UtcNow, ctx.RequestAborted);
|
||||
return Results.Json(logins.Exchange(machine, report.BootId, report.Logins, DateTimeOffset.UtcNow), FleetJsonContext.Default.WorkerReply);
|
||||
});
|
||||
// Explicit allowlist; never serve configuration, state files or a fallback path from the repository.
|
||||
foreach (var (route, file, mime) in new[] { ("/", "index.html", "text/html"), ("/app.js", "app.js", "text/javascript"), ("/style.css", "style.css", "text/css") })
|
||||
{
|
||||
var path = Path.Combine(app.Environment.ContentRootPath, "wwwroot", file);
|
||||
app.MapGet(route, () => Results.File(path, mime));
|
||||
}
|
||||
await app.RunAsync();
|
||||
@@ -0,0 +1,96 @@
|
||||
'use strict';
|
||||
const $ = id => document.getElementById(id);
|
||||
let csrf = null, dashboard = null, login = null, loginTimer = null;
|
||||
const fmt = n => n == null ? 'Unknown' : new Intl.NumberFormat(undefined, {maximumFractionDigits:1}).format(n);
|
||||
const pct = n => n == null ? 'Unknown' : `${fmt(n)}%`;
|
||||
const money = n => n == null ? 'Unpriced' : `≈ $${new Intl.NumberFormat(undefined,{minimumFractionDigits:2,maximumFractionDigits:6}).format(n)}`;
|
||||
const date = (t, zone) => t ? new Date(t).toLocaleString(undefined, {timeZone:zone, month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'}) : 'Unknown';
|
||||
const shortDate = (t, zone) => new Date(t).toLocaleDateString(undefined,{timeZone:zone,month:'short',day:'numeric'});
|
||||
const el = (tag, text, cls) => { const n = document.createElement(tag); if(text != null) n.textContent=text; if(cls) n.className=cls; return n; };
|
||||
function error(e) { $('error').textContent=e.message; $('error').hidden=false; }
|
||||
async function api(path, body) {
|
||||
const r = await fetch(path,{method:body === undefined?'GET':'POST',headers:{'Content-Type':'application/json','X-FinalToken':'1',...(csrf?{'X-CSRF':csrf}:{})},...(body===undefined?{}:{body:JSON.stringify(body)}),cache:'no-store'});
|
||||
if(!r.ok) { if(r.status===401) { csrf=null; $('signin').hidden=false; $('dashboard').hidden=true; $('logout').hidden=true; } throw new Error(r.status===409?'Operation rejected. Check profile, pending login state and machine status.':`Request failed (${r.status}).`); }
|
||||
return r.status===204?null:r.json();
|
||||
}
|
||||
async function load() {
|
||||
dashboard=await api('/api/dashboard'); $('signin').hidden=true; $('dashboard').hidden=false; $('logout').hidden=false; $('error').hidden=true;
|
||||
$('updated').textContent=`View updated ${new Date(dashboard.now).toLocaleTimeString()}`;
|
||||
$('accounts').replaceChildren(...dashboard.accounts.map(accountCard)); renderMachines();
|
||||
}
|
||||
function metric(label,value,detail) { const n=el('div',null,'metric'); n.append(el('div',label,'metric-label'),el('div',value,'metric-value'),el('div',detail,'metric-detail')); return n; }
|
||||
function table(headers,rows) { const wrap=el('div',null,'table-scroll'),t=el('table'),head=el('thead'),tr=el('tr'); headers.forEach(h=>tr.append(el('th',h))); head.append(tr);t.append(head);const body=el('tbody');rows.forEach(row=>{const r=el('tr');row.forEach(cell=>r.append(el('td',cell)));body.append(r);});t.append(body);wrap.append(t);return wrap; }
|
||||
function disclosure(title,child) { const d=el('details');d.append(el('summary',title),child);return d; }
|
||||
function svgNode(tag,attrs,text) { const n=document.createElementNS('http://www.w3.org/2000/svg',tag);Object.entries(attrs).forEach(([k,v])=>n.setAttribute(k,String(v)));if(text)n.textContent=text;return n; }
|
||||
function chartBase(title) { const box=el('div',null,'chart-frame');box.append(el('h4',title));const svg=svgNode('svg',{viewBox:'0 0 560 230',class:'chart',role:'img','aria-label':title});box.append(svg);return {box,svg}; }
|
||||
function burnChart(v,zone) {
|
||||
const {box,svg}=chartBase('Allowance used · current reset window');const a=v.analysis;
|
||||
if(!a){box.append(el('p',v.stale?'Stale allowance — fresh observation needed.':'Not enough reset information for a projection.','muted'));return box;}
|
||||
const start=+new Date(a.current.start),end=+new Date(a.current.reset),x=t=>40+480*(+new Date(t)-start)/(end-start);
|
||||
const top=Math.max(100,Math.min(200,v.useAtReset??100)),y=p=>190-160*p/top;
|
||||
[0,50,100].forEach(p=>{svg.append(svgNode('line',{x1:40,x2:520,y1:y(p),y2:y(p),class:'axis'}),svgNode('text',{x:4,y:y(p)+4},`${p}%`));});
|
||||
svg.append(svgNode('line',{x1:40,y1:y(0),x2:520,y2:y(100),class:'pace'}));
|
||||
const points=a.current.points;
|
||||
for(let i=1;i<points.length;i++) svg.append(svgNode('path',{d:`M ${x(points[i-1].time)} ${y(points[i-1].used)} L ${x(points[i].time)} ${y(points[i].used)}`,class:points[i].origin==='Estimated'||points[i-1].origin==='Estimated'?'estimated':'measured'}));
|
||||
if(v.useAtReset!=null) svg.append(svgNode('path',{d:`M ${x(dashboard.now)} ${y(v.window.usedPercent)} L 520 ${y(Math.min(top,v.useAtReset))}`,class:'projection'}));
|
||||
svg.append(svgNode('text',{x:40,y:215},shortDate(start,zone)),svgNode('text',{x:520,y:215,'text-anchor':'end'},`Reset ${date(end,zone)}`));
|
||||
box.append(el('p','Solid: measured · short dash: token estimate · grey: even pace · green dash: average projection','legend'));return box;
|
||||
}
|
||||
function accountCard(a) {
|
||||
const n=el('article',null,`account ${a.account.provider.toLowerCase()}`),head=el('div',null,'account-heading'),name=el('div');
|
||||
name.append(el('div',a.account.provider.toUpperCase(),'provider'),el('h2',a.account.label),el('p',`${a.account.expectedEmail} · account-wide allowance · ${a.account.timeZone}`));
|
||||
head.append(name,el('span',`${a.windows.length} observed limit${a.windows.length===1?'':'s'}`,'badge'));n.append(head);const content=el('div',null,'account-content');
|
||||
a.warnings.forEach(w=>content.append(el('p',w,'warning-note')));
|
||||
if(!a.windows.length) content.append(el('h3','Allowance unknown'),el('p','Connect a verified CLI profile with observed provider limits. Token totals alone cannot answer whether the week will last.','muted'));
|
||||
a.windows.forEach(w=>content.append(windowCard(w,a.account.timeZone)));
|
||||
const totals=el('div',null,'metrics');totals.append(metric('Collected history · deduplicated tokens',a.hasConsumptionData?fmt(a.total.total):'Unknown','Includes only attributed records and designated legacy history'),metric('Estimated API list-price value',money(a.apiValue),`USD · table checked ${a.pricesCheckedOn}`),metric('Unpriced tokens',a.hasConsumptionData?fmt(a.unpricedTokens):'Unknown','Not included in the price estimate'));content.append(totals);
|
||||
const tokenChart=chartBase('Token history · last 30 local days');const days=new Map();const cutoff=+new Date(dashboard.now)-30*86400000;
|
||||
a.tokens.filter(t=>+new Date(t.time)>=cutoff).forEach(t=>{const key=shortDate(t.time,a.account.timeZone);days.set(key,(days.get(key)||0)+t.counts.total);});
|
||||
const rows=[...days];const max=Math.max(1,...rows.map(r=>r[1]));rows.forEach(([day,value],i)=>{const width=480/Math.max(1,rows.length);const bar=svgNode('rect',{x:40+i*width,y:190-value/max*155,width:Math.max(1,width-4),height:value/max*155,class:'bar'});bar.append(svgNode('title',{},`${day}: ${fmt(value)} tokens`));tokenChart.svg.append(bar);if(i%Math.ceil(rows.length/6)===0)tokenChart.svg.append(svgNode('text',{x:40+i*width,y:215},day));});
|
||||
if(!rows.length)tokenChart.box.append(el('p','No attributed token history reported yet.','muted'));
|
||||
content.append(disclosure('Token history and API value',tokenChart.box));
|
||||
content.append(disclosure(`Session consumption · ${a.sessions.length} identified sessions`,table(['Session id','Tokens'],a.sessions.slice(0,50).map(s=>[s.id,fmt(s.tokens.total)]))));
|
||||
n.append(content);return n;
|
||||
}
|
||||
function windowCard(v,zone) {
|
||||
const w=v.window,n=el('section',null,'window'),heading=el('div',null,'window-title');
|
||||
const state=v.stale?'Stale':({Ahead:'Ahead of sustainable pace',Behind:'Below sustainable pace',OnTrack:'Within pace alert threshold',Unknown:'Pace unknown'}[v.pace.state]||'Unknown');
|
||||
heading.append(el('h3',w.label),el('span',state,`badge ${v.stale||v.pace.state==='Ahead'?'warning':''}`));n.append(heading);
|
||||
const verdict=v.stale?'Waiting for fresh allowance data':v.useAtReset==null?'Forecast needs more elapsed time or reset data':v.useAtReset>100?'At this average rate, you will run out before reset.':'At this average rate, your allowance will last until reset.';
|
||||
n.append(el('p',verdict,`verdict ${v.useAtReset>100?'warning':''}`));
|
||||
const m=el('div',null,'metrics');m.append(metric('Remaining now',pct(100-w.usedPercent),`${pct(w.usedPercent)} used · measured ${date(w.sampleTime,zone)}`),metric('Remaining at reset · projected',v.remainingAtReset==null?'Unknown':pct(Math.max(0,v.remainingAtReset)),v.useAtReset>100?`${pct(v.useAtReset-100)} over allowance at this rate`:'Constant average rate, not guaranteed'),metric('Estimated exhaustion',v.pace.projection?date(v.pace.projection,zone):'—',v.pace.projection?'Before reset at the average rate':'No predicted exhaustion / insufficient data'),metric('Allowance resets',date(w.resetsAt,zone),`${v.pace.delta==null?'Unknown':fmt(v.pace.delta)} percentage points versus even pace`));n.append(m);
|
||||
const grid=el('div',null,'chart-grid');grid.append(burnChart(v,zone));const side=el('div');const days=v.analysis?.days;
|
||||
const budget=el('div',null,'budget');budget.append(el('h3',`Today’s budget: ${pct(days?.todayBudget)}`),el('p',`Used today: ${pct(days?.today)} (${days?.todayOrigin??'unknown'}). Budget baseline: ${days?.budgetOrigin??'unknown'}.`),el('p',`Later daily budget: ${pct(days?.laterBudget)} per full day; partial days use their actual share.`));side.append(budget);
|
||||
side.append(el('h3','Recent rate · last 24 hours'),el('p',v.recent?`${fmt(v.recent.percentPerDay)} percentage points/day → ${pct(v.recent.useAtReset)} used at reset. ${v.recent.reachesLimit?'Exhaustion '+date(v.recent.reachesLimit,zone):'No exhaustion predicted.'}`:'Needs at least 3 hours of consistent samples in this reset instance.','muted'),el('p','Average and recent rates are separate estimates. Early forecasts can move sharply. Reset boundaries and partial days follow the provider’s actual window.','muted'));grid.append(side);n.append(grid);
|
||||
if(days)n.append(disclosure('Daily use and remaining daily plan',table(['Local day','Used','Even pace','Daily budget','Origin'],days.current.map(d=>[shortDate(d.start,zone)+(d.isToday?' · today':''),pct(d.used),pct(d.evenPace),pct(d.budget),d.origin+(d.budgetOrigin?` / budget ${d.budgetOrigin}`:'')]))));
|
||||
if(v.resets)n.append(disclosure(`Observed reset history · ${v.resets.totals.instances} windows · ${v.resets.totals.early} early resets`,table(['Start','End / reset','Final use','Tokens','API value','Reset'],v.resets.instances.map(r=>[date(r.start,zone),date(r.end,zone),r.running?'Running':pct(r.final?.used),fmt(r.tokens?.total),r.apiValue==null?'Unknown':`≈ $${fmt(r.apiValue)}`,r.early?'Early':'Scheduled']))));
|
||||
return n;
|
||||
}
|
||||
function renderMachines() {
|
||||
$('machine-list').replaceChildren(...dashboard.machines.map(m=>{
|
||||
const n=el('article',null,'machine');n.append(el('h3',m.label),el('span',m.online?'● Online':'○ Offline',`status ${m.online?'':'offline'}`),el('p',`${m.osUser} · last seen ${date(m.seenAt)}`,'muted'));
|
||||
m.bindings.forEach(b=>{const p=m.profiles.find(p=>p.id===b.id),a=dashboard.accounts.find(a=>a.account.id===b.accountId)?.account,c=m.consumption.find(c=>c.profileId===b.id);const row=el('div',null,'profile');row.append(el('strong',`${a?.provider??''} · ${b.id}`),el('p',`Expected: ${a?.expectedEmail??'Unknown'}`),el('p',`${p?.auth.state??'Not reported'} · actual: ${p?.auth.email??'Unknown'} · checked ${date(p?.auth.checkedAt)}`),el('p',p?.collectionError??p?.auth.reason??'Start the worker to report this profile.'),el('p',`Identified local consumption: ${fmt(c?.tokens?.total)} tokens · ${c?.sessions??0} sessions. Shared copies may appear on other machines; do not sum these totals.`));
|
||||
const button=el('button','Log in / renew');button.disabled=!m.online;button.addEventListener('click',()=>startLogin(m,b,a).catch(error));row.append(button);n.append(row);});return n;
|
||||
}));
|
||||
}
|
||||
async function startLogin(machine,binding,account) {
|
||||
login=await api('/api/logins',{machineId:machine.id,profileId:binding.id});$('login-target').textContent=`${machine.label} → OS user ${machine.osUser} → profile ${binding.id} → ${account?.expectedEmail}`;
|
||||
$('login-error').textContent='';$('code').value='';$('login-dialog').showModal();renderLogin();clearInterval(loginTimer);loginTimer=setInterval(pollLogin,1500);
|
||||
}
|
||||
function renderLogin() {
|
||||
$('login-state').textContent=`${login.state} · attempt expires ${date(login.expiresAt)}${login.email?' · CLI reports '+login.email:''}`;
|
||||
$('auth-link').hidden=!login.url;if(login.url)$('auth-link').href=login.url;else $('auth-link').removeAttribute('href');
|
||||
$('device-code').hidden=!login.deviceCode;$('device-code').textContent=login.deviceCode?`Device code: ${login.deviceCode}`:'';
|
||||
$('code-form').hidden=login.state!=='WaitingForCode';$('cancel-login').disabled=['Succeeded','Failed','Cancelled','TimedOut','AccountMismatch','IdentityUnknown','WorkerRestarted'].includes(login.state);
|
||||
if($('cancel-login').disabled){clearInterval(loginTimer);load().catch(error);}
|
||||
}
|
||||
async function pollLogin(){try{login=await api(`/api/logins/${login.id}`);renderLogin();}catch(e){$('login-error').textContent=e.message;}}
|
||||
$('signin-form').addEventListener('submit',async e=>{e.preventDefault();try{const r=await api('/session',{key:$('key').value});$('key').value='';csrf=r.csrf;await load();}catch(e){error(e);}});
|
||||
$('refresh').addEventListener('click',()=>load().catch(error));
|
||||
$('logout').addEventListener('click',async()=>{try{await api('/api/logout',{});csrf=null;$('signin').hidden=false;$('dashboard').hidden=true;$('logout').hidden=true;}catch(e){error(e);}});
|
||||
$('code-form').addEventListener('submit',async e=>{e.preventDefault();const response=$('code').value;$('code').value='';try{await api(`/api/logins/${login.id}/response`,{response});$('code-form').hidden=true;}catch(e){$('login-error').textContent=e.message;}});
|
||||
$('cancel-login').addEventListener('click',async()=>{try{await api(`/api/logins/${login.id}/cancel`,{});await pollLogin();}catch(e){$('login-error').textContent=e.message;}});
|
||||
$('close-login').addEventListener('click',()=>{$('login-dialog').close();clearInterval(loginTimer);});
|
||||
$('login-dialog').addEventListener('close',()=>clearInterval(loginTimer));
|
||||
api('/api/session').then(s=>{csrf=s.csrf;return load();}).catch(()=>{});
|
||||
setInterval(()=>{if(csrf&&!document.hidden)load().catch(error);},30000);
|
||||
@@ -0,0 +1,18 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>FinalToken · Weekly outlook</title><link rel="stylesheet" href="/style.css"><script src="/app.js" defer></script></head>
|
||||
<body>
|
||||
<header><a class="brand" href="/">F<span>FinalToken</span></a><span class="tag">YOUR WEEK, IN PERSPECTIVE</span><button id="logout" hidden>Sign out</button></header>
|
||||
<main>
|
||||
<section id="signin" class="signin"><p class="eyebrow">SELF-HOSTED / PRIVATE</p><h1>Make the week<br>work for you.</h1><p>Know whether your current usage will last until your allowance resets.</p><form id="signin-form"><label for="key">Dashboard access key</label><input id="key" type="password" autocomplete="current-password" required maxlength="512"><button class="primary">Open dashboard</button></form><p class="muted">Provider credentials stay with the official CLI on each machine.</p></section>
|
||||
<section id="dashboard" hidden>
|
||||
<div class="intro"><div><p class="eyebrow">WEEKLY OUTLOOK</p><h1>Will your allowance last?</h1><p>Measured limits. Your actual reset. FinalToken’s sustainability analysis.</p></div><div class="updated"><span id="updated">Waiting for data</span><button id="refresh">Refresh view</button></div></div>
|
||||
<nav aria-label="Dashboard sections"><a href="#accounts">Account outlook</a><a href="#machines">Machines & logins</a></nav>
|
||||
<div id="accounts"></div>
|
||||
<section class="machines-section" id="machines"><div class="section-heading"><div><p class="eyebrow">CONNECTED ENVIRONMENTS</p><h2>Machines & official CLI logins</h2></div><p>Login responses travel to the selected profile.<br>Credentials remain on that machine.</p></div><div id="machine-list" class="machine-grid"></div></section>
|
||||
<footer>Constant-rate projections are estimates, not guaranteed capacity. API list-price value is not your subscription allowance. Working-hour patterns are not modelled.</footer>
|
||||
</section>
|
||||
<p id="error" role="alert" hidden></p>
|
||||
</main>
|
||||
<dialog id="login-dialog" aria-labelledby="login-title"><div class="dialog-heading"><h2 id="login-title">Official CLI login</h2><button id="close-login" aria-label="Close login dialog">×</button></div><p id="login-target"></p><p class="muted">Use the intended provider account. A different account is reported as a mismatch; FinalToken will not silently reassign its history.</p><p id="login-state" role="status"></p><a id="auth-link" target="_blank" rel="noopener noreferrer" hidden>Open official authorization page ↗</a><p id="device-code" hidden></p><form id="code-form" hidden><label for="code">Authorization code shown by Claude</label><input id="code" autocomplete="off" spellcheck="false" maxlength="2048" required><button class="primary">Send once to this CLI</button></form><p id="login-error" role="alert"></p><p class="muted">No automatic remote localhost callback is assumed. If your CLI cannot accept the manual code through stdin, cancel and log in in that machine’s terminal.</p><button id="cancel-login">Cancel login</button></dialog>
|
||||
</body></html>
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
|
||||
# Worker
|
||||
Outbound authenticated HTTP only. Runs as its configured OS user; profile paths and CLI commands come from local configuration. No arbitrary remote commands, credential-file reads or inference. Persist metadata before scan cursors. See D14 and docs/web-dashboard.md.
|
||||
@@ -0,0 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><OutputType>Exe</OutputType><AssemblyName>finaltoken-worker</AssemblyName></PropertyGroup>
|
||||
<ItemGroup><ProjectReference Include="../FinalToken.Fleet/FinalToken.Fleet.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,71 @@
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using FinalToken.Core;
|
||||
using FinalToken.Fleet;
|
||||
|
||||
if (args.Length != 1) { Console.Error.WriteLine("Usage: finaltoken-worker <worker.json>"); return 2; }
|
||||
try
|
||||
{
|
||||
var config = JsonSerializer.Deserialize(File.ReadAllText(args[0]), FleetJsonContext.Default.WorkerConfig)
|
||||
?? throw new InvalidDataException("Missing worker configuration.");
|
||||
if (!FleetValidation.Identifier(config.MachineId) || config.Profiles is not { Count: > 0 } ||
|
||||
config.Profiles.Select(p => p.Id).Distinct().Count() != config.Profiles.Count ||
|
||||
config.Profiles.Any(p => !FleetValidation.Identifier(p.Id) || !Enum.IsDefined(p.Provider) ||
|
||||
string.IsNullOrWhiteSpace(p.ExpectedEmail) || !Path.IsPathFullyQualified(p.ConfigDirectory) || !Path.IsPathFullyQualified(p.DataDirectory)))
|
||||
throw new InvalidDataException("Invalid worker profile configuration.");
|
||||
if (!Uri.TryCreate(config.ServerUrl, UriKind.Absolute, out var uri) || uri.UserInfo.Length != 0 ||
|
||||
!(uri.Scheme == "https" || uri.Scheme == "http" && uri.IsLoopback))
|
||||
throw new InvalidDataException("Server must use HTTPS (loopback HTTP is permitted for local checks).");
|
||||
if (config.Profiles.Select(p => Path.GetFullPath(p.ConfigDirectory)).Distinct(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal).Count() != config.Profiles.Count ||
|
||||
config.Profiles.Select(p => Path.GetFullPath(p.DataDirectory)).Distinct(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal).Count() != config.Profiles.Count)
|
||||
throw new InvalidDataException("Each profile requires separate config and data directories.");
|
||||
Directory.CreateDirectory(config.StateDirectory);
|
||||
using var workerLock = StoreLock.TryAcquire(config.StateDirectory) ?? throw new InvalidDataException("Another worker owns this state directory.");
|
||||
var key = Environment.GetEnvironmentVariable("FINALTOKEN_WORKER_KEY");
|
||||
if (key is not { Length: >= 32 }) throw new InvalidDataException("FINALTOKEN_WORKER_KEY must contain at least 32 characters.");
|
||||
using var http = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { BaseAddress = uri, Timeout = TimeSpan.FromSeconds(30) };
|
||||
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key);
|
||||
http.DefaultRequestHeaders.Add("X-FinalToken-Machine", config.MachineId);
|
||||
using var stop = new CancellationTokenSource();
|
||||
Console.CancelKeyPress += (_, e) => { e.Cancel = true; stop.Cancel(); };
|
||||
var boot = Guid.NewGuid().ToString("N");
|
||||
var collectors = config.Profiles.Select(p => new ProfileCollector(p, config.StateDirectory)).ToArray();
|
||||
await using var logins = new WorkerLogins(config.Profiles);
|
||||
var profiles = config.Profiles.Select(p => new ProfileReport(p.Id, p.Provider,
|
||||
new("Unknown", null, DateTimeOffset.UtcNow, "First collection pending."), new(), [], [], [])).ToArray();
|
||||
Task<ProfileReport[]>? collection = null;
|
||||
var nextCollection = DateTimeOffset.MinValue;
|
||||
Console.WriteLine("FinalToken worker started. Only fixed metadata status is logged.");
|
||||
while (!stop.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (collection is { IsCompleted: true })
|
||||
{
|
||||
profiles = await collection; collection = null; nextCollection = DateTimeOffset.UtcNow.AddSeconds(60);
|
||||
}
|
||||
if (collection is null && DateTimeOffset.UtcNow >= nextCollection &&
|
||||
!logins.Updates.Any(u => u.State is "Starting" or "WaitingForBrowser" or "WaitingForCode" or "Verifying"))
|
||||
collection = Task.WhenAll(collectors.Select(c => c.CollectAsync(stop.Token)));
|
||||
var report = new WorkerReport(config.MachineId, Environment.UserName, boot, DateTimeOffset.UtcNow, profiles, logins.Updates);
|
||||
using var response = await http.PostAsJsonAsync("/worker/report", report, FleetJsonContext.Default.WorkerReport, stop.Token);
|
||||
response.EnsureSuccessStatusCode();
|
||||
var reply = await response.Content.ReadFromJsonAsync(FleetJsonContext.Default.WorkerReply, stop.Token)
|
||||
?? throw new InvalidDataException("Empty server response.");
|
||||
if (collection is not null && reply.Commands.Any(c => !c.Cancel))
|
||||
{
|
||||
// Finish metadata work before starting/feeding a login in the same CLI profile.
|
||||
profiles = await collection; collection = null; nextCollection = DateTimeOffset.UtcNow.AddSeconds(60);
|
||||
}
|
||||
await logins.ApplyAsync(reply, stop.Token);
|
||||
if (logins.TakeIdentityChanges()) nextCollection = DateTimeOffset.MinValue;
|
||||
}
|
||||
catch (OperationCanceledException) when (stop.IsCancellationRequested) { break; }
|
||||
catch (Exception) { Console.Error.WriteLine("Worker exchange failed; retaining local metadata and retrying."); }
|
||||
try { await Task.Delay(TimeSpan.FromSeconds(3), stop.Token); } catch (OperationCanceledException) { break; }
|
||||
}
|
||||
if (collection is not null) try { await collection; } catch (OperationCanceledException) { }
|
||||
return 0;
|
||||
}
|
||||
catch (Exception) { Console.Error.WriteLine("Worker stopped. Check configuration, local file access and CLI installation. Secret details are not logged."); return 1; }
|
||||
@@ -0,0 +1,2 @@
|
||||
# Synthetic CLI
|
||||
Only a deterministic provider-free test executable. Never point this at a real provider config directory. Emit fixed metadata and test URLs; do not call a network or handle actual provider credentials.
|
||||
@@ -0,0 +1 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType></PropertyGroup></Project>
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Text.Json;
|
||||
|
||||
// Test-only CLI. identity.txt contains a synthetic email, never a provider credential.
|
||||
var home=Environment.GetEnvironmentVariable("CLAUDE_CONFIG_DIR") ?? Environment.GetEnvironmentVariable("CODEX_HOME");
|
||||
if(home is null) return 2;
|
||||
Directory.CreateDirectory(home);
|
||||
var identity=Path.Combine(home,"identity.txt");
|
||||
if(args is ["auth","login",..])
|
||||
{
|
||||
if(File.Exists(Path.Combine(home,"overflow-login")))
|
||||
{
|
||||
Console.Write(new string('x',128*1024));Console.Out.Flush();
|
||||
_=Console.ReadLine();return 1;
|
||||
}
|
||||
Console.Write("https://claude.ai/oauth/authorize?state=fixture-state\nPaste code here if prompted: ");
|
||||
Console.Out.Flush();
|
||||
var response=Console.ReadLine();
|
||||
if(response is not ("fixture-code#fixture-state" or "wrong-code#fixture-state")) return 1;
|
||||
File.WriteAllText(identity,response.StartsWith("wrong",StringComparison.Ordinal)?"[email protected]":"[email protected]");
|
||||
Console.WriteLine("Login successful");return 0;
|
||||
}
|
||||
if(args is ["auth","status",..])
|
||||
{
|
||||
if(!File.Exists(identity)){Console.WriteLine("{\"loggedIn\":false}");return 1;}
|
||||
var email=File.ReadAllText(identity);
|
||||
Console.WriteLine(email=="[email protected]"?"{\"loggedIn\":true,\"email\":\"[email protected]\"}":"{\"loggedIn\":true,\"email\":\"[email protected]\"}");return 0;
|
||||
}
|
||||
if(args is ["login","--device-auth"])
|
||||
{
|
||||
Console.WriteLine("\u001b[94mhttps://auth.openai.com/codex/device\u001b[0m\n\u001b[94mABCD-12345\u001b[0m");
|
||||
while(!File.Exists(Path.Combine(home,"authorize-device")))await Task.Delay(50);
|
||||
File.WriteAllText(identity,"[email protected]");return 0;
|
||||
}
|
||||
if(args is ["app-server"])
|
||||
{
|
||||
while(Console.ReadLine() is {} line)
|
||||
{
|
||||
using var json=JsonDocument.Parse(line);
|
||||
var root=json.RootElement;
|
||||
if(!root.TryGetProperty("id",out var id))continue;
|
||||
var number=id.GetInt32();
|
||||
var method=root.GetProperty("method").GetString();
|
||||
if(method=="initialize")Console.WriteLine("{\"id\":1,\"result\":{}}");
|
||||
else if(method=="account/read")
|
||||
Console.WriteLine(File.Exists(identity)?"{\"id\":2,\"result\":{\"account\":{\"type\":\"chatgpt\",\"email\":\"[email protected]\"}}}":"{\"id\":2,\"result\":{\"account\":null}}");
|
||||
else if(method=="account/rateLimits/read")
|
||||
{
|
||||
var reset=DateTimeOffset.UtcNow.AddDays(3).ToUnixTimeSeconds();
|
||||
Console.WriteLine($"{{\"id\":{number},\"result\":{{\"rateLimits\":{{\"limitId\":\"codex\",\"secondary\":{{\"usedPercent\":65,\"windowDurationMins\":10080,\"resetsAt\":{reset}}}}}}}}}");
|
||||
}
|
||||
else return 2;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
@@ -0,0 +1,2 @@
|
||||
# Fleet tests
|
||||
Use synthetic metadata and fake CLI adapters. Cover account quota selection, source identity deduplication, reset forecasts, stale data, and session/profile login routing. No live provider credentials or login required.
|
||||
@@ -0,0 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><OutputType>Exe</OutputType><IsTestProject>true</IsTestProject><UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner><TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport></PropertyGroup>
|
||||
<ItemGroup><PackageReference Include="xunit.v3.aot.mtp-v2" /><ProjectReference Include="../../src/FinalToken.Fleet/FinalToken.Fleet.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,224 @@
|
||||
using System.Text.Json;
|
||||
using FinalToken.Core;
|
||||
using FinalToken.Fleet;
|
||||
using Xunit;
|
||||
|
||||
namespace FinalToken.Fleet.Tests;
|
||||
|
||||
public sealed class FleetTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 14, 12, 0, 0, TimeSpan.Zero);
|
||||
internal static ServerConfig Config(Provider provider = Provider.Claude) => new(
|
||||
[new("personal", provider, "Personal", "[email protected]")],
|
||||
[new("a", "Desktop", "tester", [new("main", "personal")]), new("b", "LXC", "tester", [new("main", "personal")])]);
|
||||
internal static LimitWindow Week(double used = 60, DateTimeOffset? sample = null) => new(Provider.Claude, "week", "Week", used,
|
||||
Now.AddDays(3.5), TimeSpan.FromDays(7), sample ?? Now, "fixture");
|
||||
internal static ProfileReport Profile(IReadOnlyList<SourceUsage>? usage = null, IReadOnlyList<LimitWindow>? limits = null, Provider provider = Provider.Claude) =>
|
||||
new("main", provider, new("Healthy", "[email protected]", Now, "CLI identity"), new(), usage ?? [], limits ?? [], [], DataEmail: "[email protected]");
|
||||
internal static MachineState Machine(string id, ProfileReport profile, DateTimeOffset? seen = null, string boot = "boot") =>
|
||||
new(id, seen ?? Now, new(id, "tester", boot, Now, [profile], []));
|
||||
private static AccountView Analyze(ProfileReport a, ProfileReport? b = null, ServerConfig? config = null, DateTimeOffset? now = null) =>
|
||||
FleetAnalysis.Build(config ?? Config(a.Provider), new(b is null ? [Machine("a", a)] : [Machine("a", a), Machine("b", b)]), now ?? Now).Accounts.Single();
|
||||
|
||||
[Fact] public void SameAccountQuotaIsNeverSummedAcrossMachines()
|
||||
{
|
||||
var a = Profile(limits: [Week(60)]); var b = Profile(limits: [Week(59, Now.AddMinutes(-1))]);
|
||||
var view = Analyze(a, b);
|
||||
Assert.Single(view.Windows); Assert.Equal(60, view.Windows[0].Window.UsedPercent);
|
||||
Assert.Equal(120d, view.Windows[0].UseAtReset); Assert.Equal(-20d, view.Windows[0].RemainingAtReset);
|
||||
Assert.Equal(Now.AddDays(7d / 3), view.Windows[0].Pace.Projection);
|
||||
}
|
||||
[Fact] public void ClaudeResponseIsCountedOnceAcrossMachinesAndRetries()
|
||||
{
|
||||
SourceUsage u = new("response-1", null, Now, "claude-opus-4-6", new(Input: 100, Total: 100));
|
||||
var account = Analyze(Profile([u, u]), Profile([u]));
|
||||
Assert.Equal(100, account.Total.Total); Assert.Equal(.0005m, account.ApiValue);
|
||||
}
|
||||
[Fact] public void CodexSessionCopiesUseOrderedCumulativeIncreases()
|
||||
{
|
||||
SourceUsage first = new("s:100", "s", Now.AddHours(-2), "gpt-5.4", new(Input: 100, Total: 100));
|
||||
var second = first with { Key = "s:180", Time = Now.AddHours(-1), Counts = new(Input: 180, Total: 180) };
|
||||
var view = Analyze(Profile([second, first], provider: Provider.Codex), Profile([first, second], provider: Provider.Codex));
|
||||
Assert.Equal(180, view.Total.Total);
|
||||
}
|
||||
[Fact] public void CodexCounterResetDoesNotEraseLaterUsage()
|
||||
{
|
||||
SourceUsage first = new("one", "s", Now.AddHours(-3), "gpt-5.4", new(Input: 100, Total: 100));
|
||||
var reset = first with { Key = "two", Time = Now.AddHours(-2), Counts = new(Input: 10, Total: 10) };
|
||||
var next = first with { Key = "three", Time = Now.AddHours(-1), Counts = new(Input: 30, Total: 30) };
|
||||
Assert.Equal(120, Analyze(Profile([first, reset, next], provider: Provider.Codex)).Total.Total);
|
||||
}
|
||||
[Fact] public void ConflictingResponseMetadataIsExcludedAndDiagnosed()
|
||||
{
|
||||
SourceUsage u = new("same", null, Now, null, new(Total: 10));
|
||||
var view = Analyze(Profile([u]), Profile([u with { Counts = new(Total: 20) }]));
|
||||
Assert.Equal(0, view.Total.Total); Assert.Contains(view.Warnings, w => w.Contains("Conflicting"));
|
||||
}
|
||||
[Fact] public void StaleQuotaDoesNotFabricateForecastOrZero()
|
||||
{
|
||||
var view = Analyze(Profile(limits: [Week(75, Now.AddHours(-1))]));
|
||||
Assert.True(view.Windows[0].Stale); Assert.Equal(75, view.Windows[0].Window.UsedPercent);
|
||||
Assert.Null(view.Windows[0].UseAtReset); Assert.Null(view.Windows[0].Analysis);
|
||||
}
|
||||
[Fact] public void ExpiredResetHasNoFutureProjection()
|
||||
{
|
||||
var view = Analyze(Profile(limits: [Week() with { ResetsAt = Now }]));
|
||||
Assert.True(view.Windows[0].Stale); Assert.Null(view.Windows[0].Pace.Projection);
|
||||
}
|
||||
[Fact] public void EarlyForecastRemainsUnknownBelowEligibility()
|
||||
{
|
||||
var week = Week(1) with { ResetsAt = Now.AddDays(7).AddMinutes(-10) };
|
||||
Assert.Null(Analyze(Profile(limits: [week])).Windows[0].UseAtReset);
|
||||
}
|
||||
[Fact] public void AheadEarlyWeekRetainsExistingD7Warning()
|
||||
{
|
||||
var week = Week(39) with { ResetsAt = Now.AddDays(7).AddHours(-10) };
|
||||
var view = Analyze(Profile(limits: [week])).Windows[0];
|
||||
Assert.Equal(PaceState.Ahead, view.Pace.State); Assert.NotNull(view.Pace.Projection);
|
||||
}
|
||||
[Fact] public void RecentForecastRequiresThreeHoursAndSameReset()
|
||||
{
|
||||
var week = Week(60);
|
||||
var view = Analyze(Profile(limits: [week with { UsedPercent = 50, SampleTime = Now.AddHours(-3) }, week])).Windows[0];
|
||||
Assert.NotNull(view.Recent); Assert.Equal(80, view.Recent.PercentPerDay);
|
||||
var shortSpan = Analyze(Profile(limits: [week with { UsedPercent = 50, SampleTime = Now.AddHours(-2) }, week])).Windows[0];
|
||||
Assert.Null(shortSpan.Recent);
|
||||
}
|
||||
[Fact] public void DailyBudgetAndPartialDaysComeFromExistingAnalysis()
|
||||
{
|
||||
var week = Week(); var midnight = new DateTimeOffset(2026, 11, 14, 0, 0, 0, TimeSpan.Zero);
|
||||
var view = Analyze(Profile(limits: [week with { UsedPercent = 50, SampleTime = midnight }, week])).Windows[0];
|
||||
Assert.NotNull(view.Analysis?.Days); Assert.Equal(12.5, view.Analysis.Days.TodayBudget);
|
||||
Assert.Equal(10, view.Analysis.Days.Today); Assert.Equal(7, view.Analysis.Days.Current.Count);
|
||||
}
|
||||
[Fact] public void LoggedOutProfileRetainsAttributedHistoryAndWithholdsForecast()
|
||||
{
|
||||
var p = Profile([new("one", null, Now, null, new(Total: 42))], [Week()]) with { Auth = new("Unavailable", null, Now, "Signed out") };
|
||||
var view = Analyze(p); Assert.Equal(42, view.Total.Total); Assert.True(view.Windows[0].Stale);
|
||||
}
|
||||
[Fact] public void WrongAccountCannotContributeToConfiguredAccount()
|
||||
{
|
||||
var p = Profile([new("one", null, Now, null, new(Total: 42))], [Week()]) with { DataEmail = "[email protected]" };
|
||||
var view = Analyze(p); Assert.Empty(view.Windows); Assert.Equal(0, view.Total.Total);
|
||||
Assert.False(view.HasConsumptionData);
|
||||
}
|
||||
[Fact] public void UnknownModelsRemainUnpricedAndDoNotImplyAllowance()
|
||||
{
|
||||
var view = Analyze(Profile([new("one", null, Now, "unknown-model", new(Total: 42))]));
|
||||
Assert.Null(view.ApiValue); Assert.Equal(42, view.UnpricedTokens); Assert.Empty(view.Windows);
|
||||
}
|
||||
[Fact] public void LegacyHistoryUsesOneSourceAndNonOverlappingCutoff()
|
||||
{
|
||||
var cutoff = Now.AddDays(-1); var cfg = Config();
|
||||
cfg = cfg with { Accounts = [cfg.Accounts[0] with { LegacyMachine = "a", LegacyProfile = "main", HistoryBefore = cutoff }] };
|
||||
var raw = new SourceUsage("one", null, cutoff, null, new(Total: 7));
|
||||
var a = Profile([raw, raw with { Key = "old", Time = cutoff.AddHours(-1) }]) with { LegacyTokens = [new(cutoff.AddHours(-1), null, new(Total: 100)), new(cutoff, null, new(Total: 999))] };
|
||||
var b = Profile([raw]) with { LegacyTokens = [new(cutoff.AddHours(-1), null, new(Total: 200))] };
|
||||
Assert.Equal(107, Analyze(a,b,cfg).Total.Total);
|
||||
}
|
||||
[Theory]
|
||||
[InlineData("[email protected]", Provider.Claude)]
|
||||
[InlineData(null, Provider.Claude)]
|
||||
[InlineData("[email protected]", Provider.Codex)]
|
||||
public void LegacyHistoryMustBelongToTheConfiguredAccount(string? email, Provider provider)
|
||||
{
|
||||
var cutoff = Now.AddDays(-1); var cfg = Config();
|
||||
cfg = cfg with { Accounts = [cfg.Accounts[0] with { LegacyMachine = "a", LegacyProfile = "main", HistoryBefore = cutoff }] };
|
||||
var p = Profile(provider: provider) with { DataEmail = email,
|
||||
LegacyTokens = [new(cutoff.AddHours(-1), "claude-opus-4-6", new(Input: 100, Total: 100))] };
|
||||
var view = Analyze(p, config: cfg);
|
||||
Assert.Equal(0, view.Total.Total); Assert.Empty(view.Tokens); Assert.Null(view.ApiValue);
|
||||
Assert.False(view.HasConsumptionData);
|
||||
Assert.Contains(view.Warnings, w => w.Contains("legacy", StringComparison.OrdinalIgnoreCase) &&
|
||||
w.Contains("unverified", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
[Fact] public void LoggedOutLegacySourceRetainsPreviouslyVerifiedAttribution()
|
||||
{
|
||||
var cutoff = Now.AddDays(-1); var cfg = Config();
|
||||
cfg = cfg with { Accounts = [cfg.Accounts[0] with { LegacyMachine = "a", LegacyProfile = "main", HistoryBefore = cutoff }] };
|
||||
var p = Profile() with { Auth = new("Unavailable", null, Now, "Signed out"),
|
||||
LegacyTokens = [new(cutoff.AddHours(-1), null, new(Total: 100))] };
|
||||
Assert.Equal(100, Analyze(p, config: cfg).Total.Total);
|
||||
}
|
||||
[Fact] public void DashboardJsonRoundTripsWithoutReflection()
|
||||
{
|
||||
var view = FleetAnalysis.Build(Config(),new([Machine("a",Profile(limits:[Week()]))]),Now);
|
||||
var json = JsonSerializer.Serialize(view,FleetJsonContext.Default.DashboardView);
|
||||
Assert.Contains("useAtReset",json); Assert.Contains("Ahead",json);
|
||||
Assert.NotNull(JsonSerializer.Deserialize(json,FleetJsonContext.Default.DashboardView));
|
||||
}
|
||||
[Fact] public async Task StorePersistsOfflineMetadataButNeverLoginPayloads()
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), "finaltoken-fleet-" + Guid.NewGuid().ToString("N"));
|
||||
try
|
||||
{
|
||||
var store = new FleetStore(path, Config()); var report = Machine("a",Profile()).Report with { Logins = [new("id","main","WaitingForCode","https://claude.ai/oauth/authorize?state=secret")] };
|
||||
await store.AcceptAsync(report,"a",Now,TestContext.Current.CancellationToken);
|
||||
Assert.DoesNotContain("secret",File.ReadAllText(Path.Combine(path,"fleet.json")));
|
||||
var loaded = new FleetStore(path,Config()).Dashboard(Now.AddMinutes(2));
|
||||
Assert.False(loaded.Machines[0].Online); Assert.NotNull(loaded.Machines[0].SeenAt);
|
||||
}
|
||||
finally { if(Directory.Exists(path)) Directory.Delete(path,true); }
|
||||
}
|
||||
[Fact] public void MachineUserAndProfileAreValidatedAtTrustBoundary()
|
||||
{
|
||||
var path=Path.Combine(Path.GetTempPath(),Guid.NewGuid().ToString("N")); var store=new FleetStore(path,Config());
|
||||
var report=Machine("a",Profile()).Report;
|
||||
Assert.Throws<InvalidDataException>(()=>store.Validate(report,"b",Now));
|
||||
Assert.Throws<InvalidDataException>(()=>store.Validate(report with {OsUser="root"},"a",Now));
|
||||
Assert.Throws<InvalidDataException>(()=>store.Validate(report with {Profiles=[Profile() with {Id="other"}]},"a",Now));
|
||||
}
|
||||
[Fact] public async Task EmptyRestartHeartbeatCannotErasePreviouslyAttributedHistory()
|
||||
{
|
||||
var path=Path.Combine(Path.GetTempPath(),"finaltoken-fleet-"+Guid.NewGuid().ToString("N"));
|
||||
try
|
||||
{
|
||||
var store=new FleetStore(path,Config());
|
||||
var original=Machine("a",Profile([new("one",null,Now,null,new(Total:42))],[Week()])).Report;
|
||||
await store.AcceptAsync(original,"a",Now,TestContext.Current.CancellationToken);
|
||||
var restart=original with {BootId="new",CollectedAt=Now.AddSeconds(1),Profiles=[Profile() with {DataEmail=null,Auth=new("Unknown",null,Now,"Starting")}]};
|
||||
await store.AcceptAsync(restart,"a",Now.AddSeconds(1),TestContext.Current.CancellationToken);
|
||||
var account=store.Dashboard(Now.AddSeconds(1)).Accounts.Single();
|
||||
Assert.Equal(42,account.Total.Total);Assert.True(account.Windows.Single().Stale);
|
||||
}
|
||||
finally {if(Directory.Exists(path))Directory.Delete(path,true);}
|
||||
}
|
||||
[Fact] public void CodexLegacyCutoffMustRetainPreCutoffCumulativeBaseline()
|
||||
{
|
||||
var cutoff=Now.AddDays(-1);var cfg=Config(Provider.Codex);
|
||||
cfg=cfg with {Accounts=[cfg.Accounts[0] with {LegacyMachine="a",LegacyProfile="main",HistoryBefore=cutoff}]};
|
||||
SourceUsage old=new("old","session",cutoff.AddHours(-1),null,new(Total:100));
|
||||
var next=old with {Key="next",Time=cutoff,Counts=new(Total:180)};
|
||||
var p=Profile([old,next],provider:Provider.Codex) with {LegacyTokens=[new(cutoff.AddHours(-1),null,new(Total:100))]};
|
||||
Assert.Equal(180,Analyze(p,config:cfg).Total.Total);
|
||||
}
|
||||
[Fact] public void SharedResponseSessionAttributionDoesNotMultiplyAccountConsumption()
|
||||
{
|
||||
SourceUsage u=new("response","session-a",Now,null,new(Total:100));
|
||||
var view=Analyze(Profile([u]),Profile([u with {Session="session-b"}]));
|
||||
Assert.Equal(100,view.Total.Total);Assert.Single(view.Sessions);Assert.Equal(100,view.Sessions[0].Tokens.Total);
|
||||
}
|
||||
[Fact] public void DisabledProfileCannotPresentLiveForecast()
|
||||
{
|
||||
var settings=new Settings {Claude=new ProviderSettings {Enabled=false}};
|
||||
var view=Analyze(Profile(limits:[Week()]) with {Settings=settings});
|
||||
Assert.True(view.Windows.Single().Stale);Assert.Null(view.Windows.Single().UseAtReset);
|
||||
}
|
||||
[Fact] public void MissingCodexMigrationBaselineCannotDoubleChargeUnknownPreCutoffUsage()
|
||||
{
|
||||
var cutoff=Now.AddDays(-1);var cfg=Config(Provider.Codex);
|
||||
cfg=cfg with {Accounts=[cfg.Accounts[0] with {LegacyMachine="a",LegacyProfile="main",HistoryBefore=cutoff}]};
|
||||
SourceUsage first=new("first","session",cutoff,null,new(Total:180));
|
||||
var next=first with {Key="next",Time=cutoff.AddHours(1),Counts=new(Total:200)};
|
||||
var p=Profile([first,next],provider:Provider.Codex) with {LegacyTokens=[new(cutoff.AddHours(-1),null,new(Total:100))]};
|
||||
var view=Analyze(p,config:cfg);
|
||||
Assert.Equal(120,view.Total.Total);Assert.Contains(view.Warnings,w=>w.Contains("baseline"));
|
||||
}
|
||||
[Fact] public void MalformedNestedMetadataIsRejectedBeforePersistence()
|
||||
{
|
||||
var store=new FleetStore(Path.Combine(Path.GetTempPath(),Guid.NewGuid().ToString("N")),Config());
|
||||
var report=Machine("a",Profile()).Report;
|
||||
Assert.Throws<InvalidDataException>(()=>store.Validate(report with {Profiles=[Profile() with {Auth=new("Healthy",null,Now,null!)}]},"a",Now));
|
||||
Assert.Throws<InvalidDataException>(()=>store.Validate(report with {Logins=[null!]},"a",Now));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using FinalToken.Core;
|
||||
using FinalToken.Core.Processes;
|
||||
using FinalToken.Fleet;
|
||||
using Xunit;
|
||||
|
||||
namespace FinalToken.Fleet.Tests;
|
||||
|
||||
public sealed class LoginTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now=new(2026,11,14,12,0,0,TimeSpan.Zero);
|
||||
private static FleetState State => new([FleetTests.Machine("a",FleetTests.Profile()),FleetTests.Machine("b",FleetTests.Profile())]);
|
||||
private static WorkerProfile Profile => new("main",Provider.Claude,"[email protected]",Path.GetTempPath(),Path.GetTempPath());
|
||||
[Fact] public void LoginBelongsToInitiatingBrowserSession()
|
||||
{
|
||||
var c=new LoginCoordinator(FleetTests.Config());var p=c.Start("browser-a","a","main",State,Now);
|
||||
Assert.Throws<KeyNotFoundException>(()=>c.Get(p.Id,"browser-b",Now));
|
||||
Assert.Throws<KeyNotFoundException>(()=>c.Respond(p.Id,"browser-b","code#state",Now));
|
||||
Assert.Throws<KeyNotFoundException>(()=>c.Cancel(p.Id,"browser-b",Now));
|
||||
}
|
||||
[Fact] public void ResponseTravelsOnlyToExactMachineProfileAndOnceAcknowledgedIsCleared()
|
||||
{
|
||||
var c=new LoginCoordinator(FleetTests.Config());var p=c.Start("browser","a","main",State,Now);
|
||||
c.Exchange("b","boot",[new(p.Id,"main","WaitingForCode")],Now);
|
||||
Assert.Equal("Queued",c.Get(p.Id,"browser",Now).State);
|
||||
c.Exchange("a","boot",[new(p.Id,"wrong","WaitingForCode")],Now);
|
||||
Assert.Equal("Queued",c.Get(p.Id,"browser",Now).State);
|
||||
c.Exchange("a","boot",[new(p.Id,"main","WaitingForCode","https://claude.ai/oauth/authorize?state=abc")],Now);
|
||||
c.Respond(p.Id,"browser","code#state",Now);
|
||||
Assert.Empty(c.Exchange("b","boot",[],Now).Commands);
|
||||
Assert.Equal("code#state",c.Exchange("a","boot",[],Now).Commands.Single().Response);
|
||||
Assert.Throws<InvalidDataException>(()=>c.Respond(p.Id,"browser","again",Now));
|
||||
c.Exchange("a","boot",[new(p.Id,"main","Verifying",InputAccepted:true)],Now);
|
||||
Assert.Null(c.Exchange("a","boot",[],Now).Commands.Single().Response);
|
||||
}
|
||||
[Fact] public void ConcurrentLoginOnOneProfileIsRejectedButOtherMachinesAreIndependent()
|
||||
{
|
||||
var c=new LoginCoordinator(FleetTests.Config());c.Start("browser","a","main",State,Now);
|
||||
Assert.Throws<InvalidDataException>(()=>c.Start("other","a","main",State,Now));
|
||||
Assert.NotNull(c.Start("browser","b","main",State,Now));
|
||||
}
|
||||
[Fact] public void TimeoutAndCancellationSendCancellationWithoutRetainingCode()
|
||||
{
|
||||
var c=new LoginCoordinator(FleetTests.Config());var p=c.Start("browser","a","main",State,Now);
|
||||
Assert.Equal("TimedOut",c.Get(p.Id,"browser",Now.AddMinutes(16)).State);
|
||||
Assert.True(c.Exchange("a","boot",[],Now.AddMinutes(16)).Commands.Single().Cancel);
|
||||
var second=c.Start("browser","a","main",State,Now);
|
||||
c.Cancel(second.Id,"browser",Now);Assert.Equal("Cancelling",c.Get(second.Id,"browser",Now).State);
|
||||
Assert.True(c.Exchange("a","boot",[],Now).Commands.Single(x=>x.Id==second.Id).Cancel);
|
||||
c.Exchange("a","boot",[new(second.Id,"main","Cancelled")],Now);
|
||||
Assert.Equal("Cancelled",c.Get(second.Id,"browser",Now).State);
|
||||
}
|
||||
[Fact] public void RestartDoesNotReplayOldLoginAgainstNewWorkerProcess()
|
||||
{
|
||||
var c=new LoginCoordinator(FleetTests.Config());var p=c.Start("browser","a","main",State,Now);
|
||||
Assert.Empty(c.Exchange("a","new-boot",[],Now).Commands);
|
||||
Assert.Equal("WorkerRestarted",c.Get(p.Id,"browser",Now).State);
|
||||
}
|
||||
[Fact] public void WrongAccountIsExplicitFailureEvenIfWorkerClaimsSuccess()
|
||||
{
|
||||
var c=new LoginCoordinator(FleetTests.Config());var p=c.Start("browser","a","main",State,Now);
|
||||
c.Exchange("a","boot",[new(p.Id,"main","Succeeded",Email:"[email protected]")],Now);
|
||||
Assert.Equal("AccountMismatch",c.Get(p.Id,"browser",Now).State);
|
||||
}
|
||||
[Fact] public void OnlyOfficialUrlsReachTheBrowser()
|
||||
{
|
||||
Assert.False(LoginOutput.OfficialUrl(Provider.Claude,"https://evil.test/oauth/authorize"));
|
||||
Assert.False(LoginOutput.OfficialUrl(Provider.Claude,"https://claude.ai.evil.test/oauth/authorize"));
|
||||
Assert.False(LoginOutput.OfficialUrl(Provider.Codex,"http://auth.openai.com/codex/device"));
|
||||
Assert.True(LoginOutput.OfficialUrl(Provider.Codex,"https://auth.openai.com/codex/device"));
|
||||
}
|
||||
[Fact] public void ClaudePromptWithoutNewlineAndAnsiDeviceOutputAreParsed()
|
||||
{
|
||||
var claude=LoginOutput.Parse("id",Profile,"Open https://claude.ai/oauth/authorize?state=abc\nPaste code here if prompted: ",false);
|
||||
Assert.Equal("WaitingForCode",claude.State);Assert.NotNull(claude.Url);
|
||||
var codex=LoginOutput.Parse("id",Profile with {Provider=Provider.Codex},"\u001b[94mhttps://auth.openai.com/codex/device\u001b[0m\n\u001b[94mABCD-12345\u001b[0m",false);
|
||||
Assert.Equal("ABCD-12345",codex.DeviceCode);Assert.Equal("WaitingForBrowser",codex.State);
|
||||
}
|
||||
[Fact] public void UnknownExpiryAndWrongIdentityRemainExplicit()
|
||||
{
|
||||
var health=CliAuthentication.Parse(Profile,new ProcessResult(0,"{\"loggedIn\":true,\"email\":\"[email protected]\"}"),Now);
|
||||
Assert.Equal("AccountMismatch",health.State);
|
||||
Assert.Equal("Unknown",CliAuthentication.Parse(Profile,new(0,"{}"),Now).State);
|
||||
Assert.Equal("Unknown",CliAuthentication.Parse(Profile,new(0,"{\"loggedIn\":true}"),Now).State);
|
||||
}
|
||||
[Fact] public async Task WorkerRetriesCannotStartTwoProcessesOrRouteInputToWrongProfile()
|
||||
{
|
||||
var count=0;FakeLogin? fake=null;
|
||||
await using var worker=new WorkerLogins([Profile],(c,p)=>{count++;return fake=new(c.Id,p.Id);});
|
||||
var command=new LoginCommand("id","main",Now.AddMinutes(15));
|
||||
await worker.ApplyAsync(new([command,command]),CancellationToken.None);
|
||||
Assert.Equal(1,count);
|
||||
await worker.ApplyAsync(new([command with {ProfileId="wrong",Response="secret"}]),CancellationToken.None);
|
||||
Assert.Null(fake!.Response);
|
||||
await worker.ApplyAsync(new([command with {Response="code#state"},command with {Response="code#state"}]),CancellationToken.None);
|
||||
Assert.Equal(1,fake.Inputs);
|
||||
fake.State="Succeeded";
|
||||
Assert.True(worker.TakeIdentityChanges());Assert.False(worker.TakeIdentityChanges());
|
||||
await worker.ApplyAsync(new([command with {Cancel=true}]),CancellationToken.None);Assert.True(fake.Cancelled);
|
||||
}
|
||||
private sealed class FakeLogin(string id,string profile):ILoginProcess
|
||||
{
|
||||
public string? Response;public int Inputs;public bool Cancelled;public string State="WaitingForCode";
|
||||
public LoginUpdate Current=>new(id,profile,State);
|
||||
public Task SubmitAsync(string response,CancellationToken token){if(Response is null){Response=response;Inputs++;}return Task.CompletedTask;}
|
||||
public void Cancel()=>Cancelled=true;
|
||||
public ValueTask DisposeAsync()=>ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Read-only publication check. Reports paths/pattern names, never matching secret values."""
|
||||
import argparse
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from source_policy import is_private_path as sensitive_path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
LIMIT = 2 * 1024 * 1024
|
||||
PATTERNS = (
|
||||
("private key", re.compile(rb"-----BEGIN (?:RSA |EC |OPENSSH |DSA |ENCRYPTED )?PRIVATE KEY-----")),
|
||||
("provider token", re.compile(rb"\bsk-(?:ant-|proj-|svcacct-)[A-Za-z0-9_-]{24,}")),
|
||||
("Git hosting token", re.compile(rb"\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,})")),
|
||||
("credential in URL", re.compile(rb"https?://[^\s/:@]+:[^\s/@]+@")),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Finding:
|
||||
path: str
|
||||
kind: str
|
||||
line: int = 0
|
||||
|
||||
|
||||
def inspect(path, data):
|
||||
if b"\0" in data[:8192]:
|
||||
return []
|
||||
return [Finding(path, kind, data.count(b"\n", 0, match.start()) + 1)
|
||||
for kind, pattern in PATTERNS for match in pattern.finditer(data)]
|
||||
|
||||
|
||||
def git(root, *arguments, data=None):
|
||||
return subprocess.run(["git", *arguments], cwd=root, input=data, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, check=True).stdout
|
||||
|
||||
|
||||
def working_tree(root):
|
||||
names = set(git(root, "ls-files", "-z", "--cached", "--others", "--exclude-standard").decode("utf-8").split("\0")) - {""}
|
||||
findings, skipped, scanned = [], [], 0
|
||||
for name in sorted(names):
|
||||
path = root / name
|
||||
if sensitive_path(name):
|
||||
findings.append(Finding(name, "local configuration/credential/runtime filename"))
|
||||
elif path.is_symlink() or not path.resolve().is_relative_to(root.resolve()):
|
||||
findings.append(Finding(name, "symlink/outside source tree"))
|
||||
elif not path.exists():
|
||||
continue # Removed tracked file; history is checked separately.
|
||||
elif not path.is_file() or path.stat().st_size > LIMIT:
|
||||
skipped.append(name)
|
||||
else:
|
||||
data = path.read_bytes()
|
||||
if b"\0" in data[:8192]:
|
||||
skipped.append(name)
|
||||
continue
|
||||
findings.extend(inspect(name, data))
|
||||
scanned += 1
|
||||
staged, staged_count, staged_skipped = index(root)
|
||||
return findings + staged, scanned + staged_count, skipped + staged_skipped
|
||||
|
||||
|
||||
def index(root):
|
||||
"""Audit actual index blobs, not their potentially different working copies. No staging changes."""
|
||||
records = git(root, "ls-files", "--stage", "-z").decode("utf-8").split("\0")
|
||||
findings, skipped, scanned = [], [], 0
|
||||
for record in filter(None, records):
|
||||
metadata, name = record.split("\t", 1)
|
||||
mode, oid, stage = metadata.split()
|
||||
label = "index:" + name
|
||||
if sensitive_path(name):
|
||||
findings.append(Finding(label, "staged local configuration/credential/runtime filename"))
|
||||
elif stage != "0" or mode not in ("100644", "100755"):
|
||||
findings.append(Finding(label, "unmerged index, symlink or submodule needs review"))
|
||||
elif int(git(root, "cat-file", "-s", oid)) > LIMIT:
|
||||
skipped.append(label)
|
||||
else:
|
||||
data = git(root, "cat-file", "blob", oid)
|
||||
if b"\0" in data[:8192]:
|
||||
skipped.append(label)
|
||||
else:
|
||||
findings.extend(inspect(label, data))
|
||||
scanned += 1
|
||||
return findings, scanned, skipped
|
||||
|
||||
|
||||
def historical_private_paths(root):
|
||||
# rev-list --objects gives only one name hint per blob. A blob can have been
|
||||
# renamed/copied under a private filename in another tree without changing its id.
|
||||
private = {}
|
||||
for commit in git(root, "rev-list", "--all").decode("ascii").splitlines():
|
||||
for record in git(root, "ls-tree", "-r", "-z", "--full-tree", commit).decode("utf-8").split("\0"):
|
||||
if not record:
|
||||
continue
|
||||
metadata, name = record.split("\t", 1)
|
||||
if sensitive_path(name):
|
||||
private.setdefault(metadata.split()[2], set()).add(name)
|
||||
return private
|
||||
|
||||
|
||||
def history(root):
|
||||
private = historical_private_paths(root)
|
||||
objects = {}
|
||||
for entry in git(root, "rev-list", "--objects", "--all").decode("utf-8").splitlines():
|
||||
oid, _, name = entry.partition(" ")
|
||||
objects[oid] = name
|
||||
findings, skipped, scanned = [], [], 0
|
||||
metadata = git(root, "cat-file", "--batch-check", data="".join(o + "\n" for o in objects).encode()).decode("ascii")
|
||||
candidates = []
|
||||
for row in metadata.splitlines():
|
||||
oid, kind, size = row.split()
|
||||
if kind not in ("blob", "commit", "tag"):
|
||||
continue
|
||||
name = objects[oid] or "<" + kind + ">"
|
||||
label = "history:" + oid[:12] + ":" + name
|
||||
if oid in private or sensitive_path(name):
|
||||
findings.extend(Finding("history:" + oid[:12] + ":" + p, "historical local configuration/credential/runtime filename")
|
||||
for p in sorted(private.get(oid, {name})))
|
||||
elif int(size) > LIMIT:
|
||||
skipped.append(label)
|
||||
else:
|
||||
candidates.append((oid, label))
|
||||
# One batch process avoids starting Git separately for every historical source blob.
|
||||
with subprocess.Popen(["git", "cat-file", "--batch"], cwd=root, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL) as process:
|
||||
for oid, label in candidates:
|
||||
process.stdin.write((oid + "\n").encode())
|
||||
process.stdin.flush()
|
||||
header = process.stdout.readline().split()
|
||||
if len(header) != 3 or header[1] not in (b"blob", b"commit", b"tag"):
|
||||
raise ValueError("Unexpected Git object response")
|
||||
data = process.stdout.read(int(header[2]))
|
||||
if process.stdout.read(1) != b"\n":
|
||||
raise ValueError("Truncated Git object response")
|
||||
if b"\0" in data[:8192]:
|
||||
skipped.append(label)
|
||||
else:
|
||||
findings.extend(inspect(label, data))
|
||||
scanned += 1
|
||||
process.stdin.close()
|
||||
if process.wait() != 0:
|
||||
raise ValueError("Git object read failed")
|
||||
return findings, scanned, skipped
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--history", action="store_true", help="Also inspect reachable Git source, commit and tag text")
|
||||
args = parser.parse_args(argv)
|
||||
findings, count, skipped = working_tree(ROOT)
|
||||
print(f"Worktree/index: {count} text versions scanned; {len(skipped)} binary/oversized versions skipped.")
|
||||
if args.history:
|
||||
old, count, old_skipped = history(ROOT)
|
||||
findings.extend(old)
|
||||
skipped.extend(old_skipped)
|
||||
print(f"Reachable history: {count} text objects; {len(old_skipped)} binary/oversized objects skipped.")
|
||||
print("Git author/committer identities remain unchanged; inspect them before publication.")
|
||||
for item in findings:
|
||||
print(f"{item.path}:{item.line}: {item.kind}")
|
||||
for path in skipped:
|
||||
print("Not content-scanned: " + path)
|
||||
print(f"Pattern findings: {len(findings)}. This targeted check cannot prove absence of arbitrary secrets.")
|
||||
return 1 if findings else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except (OSError, ValueError, subprocess.CalledProcessError):
|
||||
print("Publication check could not complete; no source/credential values are printed.", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
@@ -10,7 +10,7 @@ import sys
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
|
||||
SKIP = {".git", "bin", "obj", ".artifacts", "node_modules"}
|
||||
SKIP = {".git", "bin", "obj", ".artifacts", "artifacts", "node_modules"}
|
||||
IDENTIFIER = re.compile(r"\b[RD][0-9]+\b")
|
||||
LINK = re.compile(r"!?\[[^\]\n]*\]\((<[^>\n]+>|[^()\s]*(?:\([^()\s]*\)[^()\s]*)*)(?:\s+[\"'][^\n]*?[\"'])?\)")
|
||||
REFERENCE = re.compile(r"^\s{0,3}\[[^\]]+\]:\s*(<[^>]+>|\S+)")
|
||||
|
||||
@@ -69,7 +69,7 @@ class DocumentationCheck(unittest.TestCase):
|
||||
self.assertEqual(["notes.md:4: missing anchor: #hidden"], check(self.root))
|
||||
|
||||
def test_excluded_trees(self):
|
||||
for directory in (".git", "bin", "obj", ".artifacts", "node_modules"):
|
||||
for directory in (".git", "bin", "obj", ".artifacts", "artifacts", "node_modules"):
|
||||
self.write(f"{directory}/notes.md", "R99 [Gone](gone.md)\n")
|
||||
self.write("nested/.git", "gitdir: elsewhere\n")
|
||||
self.write("nested/notes.md", "R99\n")
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run from a dedicated trusted clone on the Proxmox host. Always enter the fetched installer.
|
||||
set -euo pipefail
|
||||
set +x
|
||||
|
||||
fail() { printf '%s\n' "FinalToken update: $*" >&2; exit 1; }
|
||||
usage() { printf '%s\n' 'Usage: bash /path/to/FinalToken/tools/proxmox-update.sh CTID [--dry-run]'; }
|
||||
|
||||
if [[ ${1:-} == --help || ${1:-} == -h ]]; then
|
||||
usage
|
||||
exit 0
|
||||
fi
|
||||
if [[ $# -lt 1 || $# -gt 2 || ! $1 =~ ^[1-9][0-9]{2,8}$ || ( $# == 2 && $2 != --dry-run ) ]]; then
|
||||
usage >&2
|
||||
exit 2
|
||||
fi
|
||||
ctid=$1
|
||||
dry_run=${2:-}
|
||||
source_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P)
|
||||
for program in git bash; do
|
||||
command -v "$program" >/dev/null || fail "Missing host command: $program"
|
||||
done
|
||||
|
||||
top=$(git -C "$source_dir" rev-parse --show-toplevel 2>/dev/null) || fail 'Use a dedicated Git clone of FinalToken.'
|
||||
[[ $(cd -- "$top" && pwd -P) == "$source_dir" ]] || fail 'Installer must be at the root of its own Git checkout.'
|
||||
git -C "$source_dir" symbolic-ref --quiet HEAD >/dev/null 2>&1 || fail 'Detached checkout; select the published branch first.'
|
||||
git -C "$source_dir" rev-parse --verify '@{upstream}' >/dev/null 2>&1 || fail 'The checked-out branch needs a tracking upstream.'
|
||||
|
||||
clean_checkout() {
|
||||
local changes
|
||||
changes=$(GIT_OPTIONAL_LOCKS=0 git -C "$source_dir" status --porcelain=v1 --untracked-files=all) || fail 'Cannot inspect checkout status.'
|
||||
[[ -z $changes ]] || fail 'Use a clean dedicated checkout; local tracked, staged or untracked changes were retained.'
|
||||
}
|
||||
clean_checkout
|
||||
|
||||
if [[ $dry_run == --dry-run ]]; then
|
||||
printf '%s\n' 'Plan: fast-forward the tracking branch, then deploy to the selected managed CT. No fetch or changes in dry-run.'
|
||||
exec bash "$source_dir/tools/proxmox.sh" update --ctid "$ctid" --source "$source_dir" --dry-run
|
||||
fi
|
||||
|
||||
command -v flock >/dev/null || fail 'Missing host command: flock (util-linux).'
|
||||
git_dir=$(git -C "$source_dir" rev-parse --absolute-git-dir)
|
||||
# Keep this checkout locked through the installer, in addition to host.py's deployment lock.
|
||||
exec 9>"$git_dir/finaltoken-proxmox-update.lock"
|
||||
flock -n 9 || fail 'Another update is using this checkout; wait for it to finish.'
|
||||
clean_checkout
|
||||
|
||||
printf '%s\n' 'Refreshing the published tracking branch (fast-forward only)...'
|
||||
# Git output can contain an operator-supplied credential URL. Never echo it or persist it.
|
||||
branch=$(git -C "$source_dir" symbolic-ref --quiet HEAD)
|
||||
remote=$(git -C "$source_dir" for-each-ref --format='%(upstream:remotename)' "$branch")
|
||||
[[ -n $remote && $remote != . ]] || fail 'Use a branch tracking a published remote, rather than another local branch.'
|
||||
if ! GIT_TERMINAL_PROMPT=0 GCM_INTERACTIVE=Never git -C "$source_dir" fetch --no-tags --no-recurse-submodules -- "$remote" >/dev/null 2>&1; then
|
||||
fail 'Source fetch failed; check Git access/network. No deployment was started; local work was not reset.'
|
||||
fi
|
||||
upstream=$(git -C "$source_dir" rev-parse '@{upstream}')
|
||||
git -C "$source_dir" merge-base --is-ancestor HEAD "$upstream" || fail 'Local-only or diverged commits were retained; use a checkout matching its published upstream. No deployment was started.'
|
||||
# Unlike plain git pull, this also refuses upstream paths that collide with ignored local data.
|
||||
if ! git -C "$source_dir" merge --ff-only --no-autostash --no-overwrite-ignore "$upstream" >/dev/null 2>&1; then
|
||||
fail 'Fast-forward failed; check for local or ignored files that conflict with upstream. Local work was not reset and no deployment was started.'
|
||||
fi
|
||||
head=$(git -C "$source_dir" rev-parse HEAD)
|
||||
[[ $head == "$upstream" ]] || fail 'Checkout does not match the fetched upstream; no deployment was started.'
|
||||
clean_checkout
|
||||
printf '%s\n' "Deploying source $head to CT $ctid; preserving existing configuration and data."
|
||||
exec bash "$source_dir/tools/proxmox.sh" update --ctid "$ctid" --source "$source_dir"
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run on the Proxmox host, from a trusted checkout. No curl-to-shell bootstrap.
|
||||
set -euo pipefail
|
||||
set +x
|
||||
exec python3 "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/proxmox/host.py" "$@"
|
||||
@@ -0,0 +1,2 @@
|
||||
# Proxmox deployment tools
|
||||
Host creates only a new explicitly selected CT; update requires this installer's marker. Never destroy a CT, alter host package repositories, overwrite existing configuration, or read provider credentials. Builds run inside the CT as an isolated user. Transport keys are FinalToken service keys, not provider tokens. Keep commands as argv lists; never shell-interpolate deployment inputs. Test with `python -B tools/proxmox/test_installer.py`.
|
||||
@@ -0,0 +1,386 @@
|
||||
"""Private guest provisioner, invoked by host.py inside the selected LXC. Not a host entry point."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import pwd
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
INSTALLER = "finaltoken-proxmox-v1"
|
||||
ETC = Path("/etc/finaltoken")
|
||||
APP = Path("/opt/finaltoken")
|
||||
BUILD = Path("/var/cache/finaltoken-build")
|
||||
SERVER_HOME = Path("/var/lib/finaltoken-server")
|
||||
WORKER_HOME = Path("/var/lib/finaltoken-worker")
|
||||
PROXY_HOME = Path("/var/lib/finaltoken-proxy")
|
||||
SYSTEMD = Path("/etc/systemd/system")
|
||||
|
||||
|
||||
def run(command, *, check=True, capture=False, cwd=None):
|
||||
return subprocess.run([str(a) for a in command], check=check, text=True,
|
||||
stdout=subprocess.PIPE if capture else None, stderr=subprocess.PIPE if capture else None, cwd=cwd)
|
||||
|
||||
|
||||
def atomic(path, data, mode=0o600, *, once=False):
|
||||
"""D5: same-directory replace; existing operator configuration is never overwritten."""
|
||||
if once and path.exists():
|
||||
return False
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_name(path.name + "." + uuid.uuid4().hex + ".tmp")
|
||||
try:
|
||||
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as stream:
|
||||
stream.write(data)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
return True
|
||||
|
||||
|
||||
def json_file(path, data, *, once=False):
|
||||
return atomic(path, json.dumps(data, indent=2) + "\n", once=once)
|
||||
|
||||
|
||||
def unpack(archive_path, destination):
|
||||
"""No links, devices, absolute paths, traversal or unbounded archive expansion."""
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
with tarfile.open(archive_path, "r:gz") as archive:
|
||||
members = archive.getmembers()
|
||||
if len(members) > 10000 or sum(m.size for m in members) > 256 * 1024 * 1024:
|
||||
raise ValueError("Source archive exceeds its metadata/size bound")
|
||||
for member in members:
|
||||
path = PurePosixPath(member.name)
|
||||
if path.is_absolute() or ".." in path.parts or not member.isfile() or member.size > 16 * 1024 * 1024:
|
||||
raise ValueError("Source archive has an unsafe entry")
|
||||
target = destination.joinpath(*path.parts)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
with archive.extractfile(member) as source, target.open("xb") as output:
|
||||
shutil.copyfileobj(source, output)
|
||||
target.chmod(0o644)
|
||||
|
||||
|
||||
def user(name, home):
|
||||
try:
|
||||
entry = pwd.getpwnam(name)
|
||||
if entry.pw_dir != str(home):
|
||||
raise ValueError("Existing service user has an unexpected home: " + name)
|
||||
except KeyError:
|
||||
run(["useradd", "--system", "--create-home", "--home-dir", home, "--shell", "/bin/bash", "--user-group", name])
|
||||
entry = pwd.getpwnam(name)
|
||||
home.mkdir(parents=True, exist_ok=True)
|
||||
os.chown(home, entry.pw_uid, entry.pw_gid)
|
||||
home.chmod(0o750)
|
||||
return entry
|
||||
|
||||
|
||||
def as_user(name, home, command, cwd=None):
|
||||
# Do not inherit host/root provider secrets, proxy overrides or build credentials.
|
||||
return run(["runuser", "--user", name, "--", "env", "-i", "HOME=" + str(home),
|
||||
"PATH=" + str(home / ".local/bin") + ":/usr/local/bin:/usr/bin:/bin",
|
||||
"DOTNET_CLI_HOME=" + str(home), "DOTNET_CLI_TELEMETRY_OPTOUT=1", "DOTNET_NOLOGO=1", *command], cwd=cwd or home)
|
||||
|
||||
|
||||
def packages(role, providers):
|
||||
run(["apt-get", "update"])
|
||||
wanted = ["ca-certificates", "curl", "clang", "zlib1g-dev", "libicu-dev", "libssl-dev", "tzdata"]
|
||||
if role != "worker":
|
||||
wanted.append("caddy")
|
||||
if role != "server" and "codex" in providers:
|
||||
wanted.extend(["nodejs", "npm"])
|
||||
run(["env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", *wanted])
|
||||
repository = Path("/etc/apt/sources.list.d/microsoft-prod.list")
|
||||
if not repository.exists():
|
||||
with tempfile.TemporaryDirectory(prefix="finaltoken-sdk-") as tmp:
|
||||
package = Path(tmp) / "packages-microsoft-prod.deb"
|
||||
run(["curl", "--fail", "--silent", "--show-error", "--location", "--proto", "=https", "--tlsv1.2",
|
||||
"https://packages.microsoft.com/config/debian/13/packages-microsoft-prod.deb", "--output", package])
|
||||
run(["dpkg", "-i", package])
|
||||
run(["apt-get", "update"])
|
||||
run(["env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", "dotnet-sdk-10.0"])
|
||||
|
||||
|
||||
def official_clis(providers):
|
||||
"""Install official clients as their own OS user; never run a login or read auth files."""
|
||||
if "claude" in providers and not (WORKER_HOME / ".local/bin/claude").exists():
|
||||
with tempfile.TemporaryDirectory(prefix="finaltoken-claude-") as tmp:
|
||||
os.chmod(tmp, 0o755)
|
||||
script = Path(tmp) / "install.sh"
|
||||
run(["curl", "--fail", "--silent", "--show-error", "--location", "--proto", "=https", "--tlsv1.2",
|
||||
"https://claude.ai/install.sh", "--output", script])
|
||||
script.chmod(0o644)
|
||||
as_user("finaltoken", WORKER_HOME, ["bash", str(script), "stable"])
|
||||
if "codex" in providers and not (WORKER_HOME / ".local/bin/codex").exists():
|
||||
as_user("finaltoken", WORKER_HOME, ["npm", "install", "--global", "--prefix", str(WORKER_HOME / ".local"), "@openai/codex@latest"])
|
||||
for provider in providers:
|
||||
as_user("finaltoken", WORKER_HOME, [str(WORKER_HOME / ".local/bin" / provider), "--version"])
|
||||
|
||||
|
||||
def service_unit(role):
|
||||
server = role == "server"
|
||||
home = SERVER_HOME if server else WORKER_HOME
|
||||
account = "finaltoken-server" if server else "finaltoken"
|
||||
executable = APP / "current" / ("web/FinalToken.Web" if server else "worker/finaltoken-worker")
|
||||
arguments = "" if server else " " + str(ETC / "worker.json")
|
||||
return f"""[Unit]
|
||||
Description=FinalToken {role}
|
||||
Wants=network-online.target
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=exec
|
||||
User={account}
|
||||
Group={account}
|
||||
WorkingDirectory={executable.parent}
|
||||
EnvironmentFile={ETC}/{role}.env
|
||||
Environment=HOME={home}
|
||||
Environment=PATH={WORKER_HOME}/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||
ExecStart={executable}{arguments}
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
TimeoutStopSec=75
|
||||
KillMode=control-group
|
||||
UMask=0077
|
||||
NoNewPrivileges=true
|
||||
StandardOutput=null
|
||||
StandardError=null
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
"""
|
||||
|
||||
|
||||
def proxy_unit():
|
||||
return f"""[Unit]
|
||||
Description=FinalToken HTTPS proxy
|
||||
After=network-online.target finaltoken-server.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=exec
|
||||
User=finaltoken-proxy
|
||||
Group=finaltoken-proxy
|
||||
Environment=HOME={PROXY_HOME}
|
||||
Environment=XDG_DATA_HOME={PROXY_HOME}
|
||||
ExecStart=/usr/bin/caddy run --config {ETC}/Caddyfile --adapter caddyfile
|
||||
ExecReload=/usr/bin/caddy reload --config {ETC}/Caddyfile --adapter caddyfile
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
AmbientCapabilities=CAP_NET_BIND_SERVICE
|
||||
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
|
||||
NoNewPrivileges=true
|
||||
UMask=0077
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
"""
|
||||
|
||||
|
||||
def configure(meta, enrollment_key=None):
|
||||
role, providers = meta["role"], meta["providers"]
|
||||
ETC.mkdir(parents=True, exist_ok=True)
|
||||
ETC.chmod(0o755)
|
||||
if role != "worker":
|
||||
user("finaltoken-server", SERVER_HOME)
|
||||
user("finaltoken-proxy", PROXY_HOME)
|
||||
if role != "server":
|
||||
user("finaltoken", WORKER_HOME)
|
||||
keys_path = ETC / "transport-keys.json"
|
||||
if not keys_path.exists():
|
||||
json_file(keys_path, {"dashboard": secrets.token_hex(32), "worker": enrollment_key or secrets.token_hex(32)}, once=True)
|
||||
keys = json.loads(keys_path.read_text(encoding="utf-8"))
|
||||
if role != "worker":
|
||||
accounts = [{"id": p, "provider": p.capitalize(), "label": p.capitalize(), "expectedEmail": meta["emails"][p], "timeZone": meta["timezone"]}
|
||||
for p in providers if meta["emails"].get(p)]
|
||||
machines = [] if role == "server" else [{"id": meta["machineId"], "label": f"LXC {meta['ctid']}", "osUser": "finaltoken",
|
||||
"profiles": [{"id": p, "accountId": p} for p in providers]}]
|
||||
json_file(ETC / "server.json", {"accounts": accounts, "machines": machines}, once=True)
|
||||
atomic(ETC / "server.env", f"FINALTOKEN_SERVER_CONFIG={ETC}/server.json\nFINALTOKEN_SERVER_DATA={SERVER_HOME}/data\n"
|
||||
f"FINALTOKEN_DASHBOARD_KEY={keys['dashboard']}\nFINALTOKEN_PUBLIC_ORIGIN=https://{meta['domain']}\n"
|
||||
f"ASPNETCORE_URLS=http://127.0.0.1:5187\nFINALTOKEN_MACHINE_{meta['machineId']}={keys['worker']}\n", once=True)
|
||||
atomic(ETC / "dashboard-key", keys["dashboard"] + "\n", once=True)
|
||||
atomic(ETC / "worker-key", keys["worker"] + "\n", once=True)
|
||||
tls = " tls internal\n" if meta["tls"] == "internal" else ""
|
||||
atomic(ETC / "Caddyfile", f"{meta['domain']} {{\n{tls} reverse_proxy 127.0.0.1:5187\n}}\n", 0o644, once=True)
|
||||
atomic(SYSTEMD / "finaltoken-server.service", service_unit("server"), 0o644, once=True)
|
||||
atomic(SYSTEMD / "finaltoken-proxy.service", proxy_unit(), 0o644, once=True)
|
||||
run(["systemctl", "disable", "--now", "caddy.service"])
|
||||
if role != "server":
|
||||
profiles = [{"id": p, "provider": p.capitalize(), "expectedEmail": meta["emails"][p],
|
||||
"configDirectory": str(WORKER_HOME / (".claude" if p == "claude" else ".codex")),
|
||||
"dataDirectory": str(WORKER_HOME / "history" / p), "cliPath": str(WORKER_HOME / ".local/bin" / p)} for p in providers]
|
||||
json_file(ETC / "worker.json", {"machineId": meta["machineId"], "serverUrl": "http://127.0.0.1:5187" if role == "both" else meta["serverUrl"],
|
||||
"stateDirectory": str(WORKER_HOME / "collector"), "profiles": profiles}, once=True)
|
||||
atomic(ETC / "worker.env", "FINALTOKEN_WORKER_KEY=" + keys["worker"] + "\n", once=True)
|
||||
atomic(SYSTEMD / "finaltoken-worker.service", service_unit("worker"), 0o644, once=True)
|
||||
# systemd reads env files as root. Only the intended service user can read its JSON config.
|
||||
for filename, account in (("server.json", "finaltoken-server"), ("worker.json", "finaltoken")):
|
||||
path = ETC / filename
|
||||
if path.exists():
|
||||
path.chmod(0o640)
|
||||
os.chown(path, 0, pwd.getpwnam(account).pw_gid)
|
||||
|
||||
|
||||
def build(archive, meta):
|
||||
entry = user("finaltoken-build", BUILD)
|
||||
temporary = Path(tempfile.mkdtemp(prefix="build-", dir=BUILD))
|
||||
try:
|
||||
source = temporary / "src"
|
||||
unpack(archive, source)
|
||||
for path in [temporary, *temporary.rglob("*")]:
|
||||
os.chown(path, entry.pw_uid, entry.pw_gid)
|
||||
release = temporary / "release"
|
||||
for project, output in (("FinalToken.Web", "web"), ("FinalToken.Worker", "worker")):
|
||||
if meta["role"] == "server" and output == "worker" or meta["role"] == "worker" and output == "web":
|
||||
continue
|
||||
# D1: build on target Linux with NativeAOT, never copy a Windows executable into LXC.
|
||||
as_user("finaltoken-build", BUILD, ["dotnet", "publish", str(source / "src" / project / (project + ".csproj")),
|
||||
"-c", "Release", "-r", "linux-x64", "--self-contained", "true", "-p:PublishAot=true", "-o", str(release / output)], cwd=source)
|
||||
if meta["role"] != "worker" and not (release / "web/wwwroot/index.html").is_file():
|
||||
shutil.copytree(source / "src/FinalToken.Web/wwwroot", release / "web/wwwroot", dirs_exist_ok=True)
|
||||
shutil.copy2(source / "LICENSE", release / "LICENSE")
|
||||
destination = APP / "releases" / (meta["sourceSha256"][:16] + "-" + uuid.uuid4().hex[:8])
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
APP.chmod(0o755)
|
||||
destination.parent.chmod(0o755)
|
||||
shutil.copytree(release, destination)
|
||||
destination.chmod(0o755)
|
||||
for path in destination.rglob("*"):
|
||||
path.chmod(0o755 if path.is_dir() else 0o644)
|
||||
for executable in (destination / "web/FinalToken.Web", destination / "worker/finaltoken-worker"):
|
||||
wanted = meta["role"] != ("worker" if executable.name == "FinalToken.Web" else "server")
|
||||
if wanted:
|
||||
if not executable.is_file():
|
||||
raise ValueError("Native build did not produce its expected executable")
|
||||
with executable.open("rb") as stream:
|
||||
header = stream.read(20)
|
||||
if header[:4] != b"\x7fELF" or header[18:20] != b"\x3e\x00":
|
||||
raise ValueError("Published executable is not a Linux x64 ELF binary")
|
||||
executable.chmod(0o755)
|
||||
return destination
|
||||
finally:
|
||||
# Only this invocation's fresh build directory, never profiles, state or previous releases.
|
||||
shutil.rmtree(temporary)
|
||||
|
||||
|
||||
def switch(release):
|
||||
if release.parent.resolve() != (APP / "releases").resolve() or not release.is_dir():
|
||||
raise ValueError("Release must be an existing direct child of the releases directory")
|
||||
pending = APP / (".current-" + uuid.uuid4().hex)
|
||||
try:
|
||||
pending.symlink_to(release, target_is_directory=True)
|
||||
os.replace(pending, APP / "current")
|
||||
finally:
|
||||
pending.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def units(role):
|
||||
return (["finaltoken-server.service", "finaltoken-proxy.service"] if role != "worker" else []) + (["finaltoken-worker.service"] if role != "server" else [])
|
||||
|
||||
|
||||
def healthy(services, meta):
|
||||
for _ in range(20):
|
||||
live = all(run(["systemctl", "is-active", "--quiet", s], check=False, capture=True).returncode == 0 for s in services)
|
||||
if live and "finaltoken-server.service" in services:
|
||||
try:
|
||||
request = urllib.request.Request("http://127.0.0.1:5187/", headers={"Host": meta["domain"]})
|
||||
with urllib.request.urlopen(request, timeout=2) as response:
|
||||
live = response.status == 200
|
||||
except OSError:
|
||||
live = False
|
||||
if live:
|
||||
# Catch immediate startup failures. Remote provider login is deliberately not a health probe.
|
||||
time.sleep(2)
|
||||
return all(run(["systemctl", "is-active", "--quiet", s], check=False, capture=True).returncode == 0 for s in services)
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def activate(release, meta, first):
|
||||
current = APP / "current"
|
||||
previous = current.resolve() if current.is_symlink() else None
|
||||
services = units(meta["role"])
|
||||
active = services if first else [s for s in services if run(["systemctl", "is-active", "--quiet", s], check=False, capture=True).returncode == 0]
|
||||
try:
|
||||
switch(release)
|
||||
run(["systemctl", "daemon-reload"])
|
||||
if first:
|
||||
run(["systemctl", "enable", *services])
|
||||
if active:
|
||||
run(["systemctl", "restart", *active])
|
||||
if not healthy(active, meta):
|
||||
raise ValueError("New release did not pass local service/HTTP health checks")
|
||||
except Exception:
|
||||
if previous is not None:
|
||||
switch(previous)
|
||||
if active:
|
||||
run(["systemctl", "restart", *active], check=False)
|
||||
print("Activation failed; previous binary release restored. State/configuration were not rewound.", file=sys.stderr)
|
||||
else:
|
||||
run(["systemctl", "disable", "--now", *services], check=False)
|
||||
raise
|
||||
|
||||
|
||||
def provision(manifest, archive):
|
||||
if os.geteuid() != 0 or os.uname().machine != "x86_64":
|
||||
raise ValueError("Guest setup requires root in a Linux x86_64 CT")
|
||||
os_release = Path("/etc/os-release").read_text(encoding="utf-8")
|
||||
if 'ID=debian' not in os_release or 'VERSION_ID="13"' not in os_release:
|
||||
raise ValueError("Only Debian 13 amd64 guests are supported")
|
||||
if manifest.get("installer") != INSTALLER or manifest.get("action") not in ("install", "update"):
|
||||
raise ValueError("Unsupported deployment manifest")
|
||||
with archive.open("rb") as stream:
|
||||
digest = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if digest != manifest.get("sourceSha256"):
|
||||
raise ValueError("Uploaded source checksum mismatch")
|
||||
marker = ETC / "install.json"
|
||||
if manifest["action"] == "update":
|
||||
meta = json.loads(marker.read_text(encoding="utf-8"))
|
||||
if meta.get("installer") != INSTALLER or meta.get("ctid") != manifest["ctid"]:
|
||||
raise ValueError("Guest marker does not match selected CT")
|
||||
meta["sourceSha256"] = digest
|
||||
else:
|
||||
if marker.exists():
|
||||
raise ValueError("An install marker already exists; use update")
|
||||
meta = {k: v for k, v in manifest.items() if k != "workerKey"}
|
||||
meta["installed"] = False
|
||||
json_file(ETC / "transport-keys.json", {"dashboard": secrets.token_hex(32),
|
||||
"worker": manifest.get("workerKey") or secrets.token_hex(32)}, once=True)
|
||||
json_file(marker, meta, once=True) # Partial installs can be resumed through update.
|
||||
first = not meta.get("installed", False)
|
||||
packages(meta["role"], meta["providers"])
|
||||
if first:
|
||||
configure(meta, manifest.get("workerKey"))
|
||||
if meta["role"] != "server":
|
||||
official_clis(meta["providers"])
|
||||
release = build(archive, meta)
|
||||
activate(release, meta, first)
|
||||
meta.update(installed=True, release=str(release))
|
||||
json_file(marker, meta)
|
||||
if meta["role"] != "worker":
|
||||
print("Dashboard: https://" + meta["domain"])
|
||||
print("Dashboard key is root-readable at /etc/finaltoken/dashboard-key (not printed).")
|
||||
print("Official CLI login still requires your browser authorization. No provider credentials were copied.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--manifest", type=Path, required=True)
|
||||
parser.add_argument("--archive", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
provision(json.loads(args.manifest.read_text(encoding="utf-8")), args.archive)
|
||||
except (ValueError, OSError, subprocess.CalledProcessError) as error:
|
||||
print("Guest setup failed: " + (str(error) if isinstance(error, ValueError) else type(error).__name__), file=sys.stderr)
|
||||
print("Configuration, history and CLI profiles were retained. Inspect services; retry with host update.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,290 @@
|
||||
"""Create/update an unprivileged Debian 13 LXC from a local FinalToken source snapshot."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from source_policy import is_private_path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PROJECTS = ("FinalToken.Core", "FinalToken.Fleet", "FinalToken.Web", "FinalToken.Worker")
|
||||
TEMPLATE = re.compile(r"debian-13-standard_[A-Za-z0-9.+_-]+_amd64\.tar\.(?:zst|xz|gz)\Z")
|
||||
|
||||
|
||||
def run(command, *, capture=False, check=True):
|
||||
command = [str(a) for a in command]
|
||||
if command[:2] == ["pct", "exec"]:
|
||||
# Proxmox defaults differ between versions; never forward the host's secret environment.
|
||||
command[3:3] = ["--keep-env", "0"]
|
||||
return subprocess.run(command, check=check, text=True,
|
||||
stdout=subprocess.PIPE if capture else None,
|
||||
stderr=subprocess.PIPE if capture else None)
|
||||
|
||||
|
||||
def identifier(value):
|
||||
if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{0,63}", value):
|
||||
raise ValueError("Machine id must start with a letter and contain only letters, digits and underscores")
|
||||
return value
|
||||
|
||||
|
||||
def domain_name(value):
|
||||
if len(value) > 253 or not all(re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?", p) for p in value.split(".")) or "." not in value:
|
||||
raise ValueError("Domain must be a DNS name without a scheme, port, path or shell syntax")
|
||||
return value.lower()
|
||||
|
||||
|
||||
def server_url(value):
|
||||
url = urlsplit(value)
|
||||
if url.scheme != "https" or not url.hostname or url.username or url.password or url.path not in ("", "/") or url.query or url.fragment:
|
||||
raise ValueError("Remote server URL must be an HTTPS origin")
|
||||
_ = url.port
|
||||
return value.rstrip("/")
|
||||
|
||||
|
||||
def parser():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("action", choices=("install", "update"))
|
||||
p.add_argument("--ctid", type=int, help="New CT id; defaults to Proxmox nextid. Required for update.")
|
||||
p.add_argument("--source", type=Path, default=ROOT, help="Local checkout including uncommitted source")
|
||||
p.add_argument("--storage", help="Proxmox rootdir storage, e.g. local-lvm (required for install)")
|
||||
p.add_argument("--template-storage", default="local")
|
||||
p.add_argument("--template", help="Optional Debian 13 amd64 standard template filename")
|
||||
p.add_argument("--bridge", default="vmbr0")
|
||||
p.add_argument("--ip", default="dhcp", help="dhcp or static IPv4 CIDR")
|
||||
p.add_argument("--gateway")
|
||||
p.add_argument("--vlan", type=int)
|
||||
p.add_argument("--memory", type=int, default=4096, help="MiB; builds need at least 4096")
|
||||
p.add_argument("--cores", type=int, default=2)
|
||||
p.add_argument("--disk", type=int, default=20, help="GiB")
|
||||
p.add_argument("--role", choices=("both", "server", "worker"), help="Install default: both; update preserves role")
|
||||
p.add_argument("--domain", help="Dashboard DNS name; required for server/both")
|
||||
p.add_argument("--tls", choices=("acme", "internal"), default="acme")
|
||||
p.add_argument("--email", help="Expected provider email for both selected providers")
|
||||
p.add_argument("--claude-email")
|
||||
p.add_argument("--codex-email")
|
||||
p.add_argument("--providers", default="claude,codex")
|
||||
p.add_argument("--machine-id", help="Default: lxc_<ctid>")
|
||||
p.add_argument("--timezone", default="UTC")
|
||||
p.add_argument("--server-url", help="Existing HTTPS dashboard, for worker-only install")
|
||||
p.add_argument("--worker-key-file", type=Path, help="Root-readable enrollment key file; never pass the key as an argument")
|
||||
p.add_argument("--dry-run", action="store_true", help="Print validated plan; do not run Proxmox or create files")
|
||||
return p
|
||||
|
||||
|
||||
def validate(args):
|
||||
if args.ctid is not None and not 100 <= args.ctid <= 999999999:
|
||||
raise ValueError("CT id must be between 100 and 999999999")
|
||||
if args.action == "update" and args.ctid is None:
|
||||
raise ValueError("Update requires --ctid")
|
||||
args.source = args.source.resolve()
|
||||
for project in PROJECTS:
|
||||
if not (args.source / "src" / project / (project + ".csproj")).is_file():
|
||||
raise ValueError("Source must include the web/worker implementation: " + project)
|
||||
if args.action == "update":
|
||||
if args.role or args.domain or args.email or args.claude_email or args.codex_email or args.machine_id or args.server_url or args.worker_key_file:
|
||||
raise ValueError("Update preserves identity/configuration; pass only CT id and source (plus --dry-run)")
|
||||
return
|
||||
args.role = args.role or "both"
|
||||
for value in (args.storage or "", args.template_storage, args.bridge):
|
||||
if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_-]{0,63}", value):
|
||||
raise ValueError("Install requires valid --storage, template-storage and bridge identifiers")
|
||||
if args.memory < 4096 or args.cores < 1 or args.disk < 12:
|
||||
raise ValueError("Require memory >=4096 MiB, cores >=1 and disk >=12 GiB for native builds")
|
||||
if args.vlan is not None and not 1 <= args.vlan <= 4094:
|
||||
raise ValueError("VLAN must be in 1..4094")
|
||||
if args.ip != "dhcp":
|
||||
if not isinstance(ipaddress.ip_interface(args.ip), ipaddress.IPv4Interface):
|
||||
raise ValueError("Use an IPv4 CIDR")
|
||||
if not args.gateway:
|
||||
raise ValueError("Static IP requires --gateway")
|
||||
if args.gateway:
|
||||
if args.ip == "dhcp" or not isinstance(ipaddress.ip_address(args.gateway), ipaddress.IPv4Address):
|
||||
raise ValueError("Gateway is only supported with static IPv4")
|
||||
if args.template and not TEMPLATE.fullmatch(args.template):
|
||||
raise ValueError("Template must be a Debian 13 standard amd64 template filename")
|
||||
if args.role != "worker":
|
||||
if not args.domain:
|
||||
raise ValueError("Server/both requires --domain for HTTPS; use --tls internal for a private CA")
|
||||
args.domain = domain_name(args.domain)
|
||||
else:
|
||||
if not args.server_url or not args.worker_key_file:
|
||||
raise ValueError("Worker-only install requires --server-url and --worker-key-file")
|
||||
args.server_url = server_url(args.server_url)
|
||||
args.providers = args.providers.split(",")
|
||||
if not args.providers or len(set(args.providers)) != len(args.providers) or any(p not in ("claude", "codex") for p in args.providers):
|
||||
raise ValueError("Providers must be claude, codex, or claude,codex")
|
||||
for provider in args.providers:
|
||||
email = getattr(args, provider + "_email") or args.email
|
||||
if args.role != "server" and (not email or not re.fullmatch(r"[^\s@\x00-\x1f]+@[^\s@\x00-\x1f]+", email) or len(email) > 320):
|
||||
raise ValueError("Worker/both requires --email or a provider-specific email for each selected provider")
|
||||
if args.machine_id:
|
||||
identifier(args.machine_id)
|
||||
if not re.fullmatch(r"[A-Za-z0-9_+/-]{1,100}", args.timezone) or ".." in args.timezone:
|
||||
raise ValueError("Invalid timezone id")
|
||||
if args.role == "worker" and not args.dry_run:
|
||||
key = args.worker_key_file.read_text(encoding="utf-8").strip()
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{32,512}", key):
|
||||
raise ValueError("Enrollment file must contain one 32+ character transport key")
|
||||
args.enrollment_key = key
|
||||
|
||||
|
||||
def create_command(args, ctid, template):
|
||||
network = f"name=eth0,bridge={args.bridge},ip={args.ip},type=veth,firewall=1"
|
||||
if args.gateway:
|
||||
network += ",gw=" + args.gateway
|
||||
if args.vlan:
|
||||
network += ",tag=" + str(args.vlan)
|
||||
return ["pct", "create", str(ctid), f"{args.template_storage}:vztmpl/{template}",
|
||||
"--hostname", f"finaltoken-{ctid}", "--ostype", "debian", "--arch", "amd64",
|
||||
"--unprivileged", "1", "--onboot", "1", "--memory", str(args.memory), "--swap", "2048",
|
||||
"--cores", str(args.cores), "--rootfs", f"{args.storage}:{args.disk}", "--net0", network,
|
||||
"--description", "FinalToken installer; retains configuration and CLI profiles on update"]
|
||||
|
||||
|
||||
def snapshot(source, destination):
|
||||
"""Allowlist source inputs, including uncommitted changes, excluding secrets, outputs and symlinks."""
|
||||
files = [source / n for n in ("Directory.Build.props", "Directory.Packages.props", "global.json", "LICENSE")]
|
||||
for project in PROJECTS:
|
||||
directory = source / "src" / project
|
||||
if directory.is_symlink() or directory.resolve() != directory.absolute():
|
||||
raise ValueError("Source snapshot refuses a symlinked project or parent: " + project)
|
||||
files.extend(directory.rglob("*"))
|
||||
total, count = 0, 0
|
||||
with tarfile.open(destination, "w:gz") as archive:
|
||||
for path in sorted(set(files)):
|
||||
relative = path.relative_to(source)
|
||||
if is_private_path(relative):
|
||||
continue # .gitignore does not apply to tarfile: do not copy local deployment data.
|
||||
if any(p in ("bin", "obj", "artifacts", ".git", "node_modules") or p.startswith(".") for p in relative.parts):
|
||||
continue
|
||||
if path.is_symlink():
|
||||
raise ValueError("Source snapshot refuses symlinks: " + str(relative))
|
||||
if path.is_dir():
|
||||
continue
|
||||
if not path.is_file():
|
||||
raise ValueError("Missing or non-regular source file: " + str(relative))
|
||||
size = path.stat().st_size
|
||||
total += size
|
||||
count += 1
|
||||
if size > 16 * 1024 * 1024 or total > 256 * 1024 * 1024 or count > 10000:
|
||||
raise ValueError("Source snapshot exceeds the guest archive bounds")
|
||||
archive.add(path, arcname=relative.as_posix(), recursive=False)
|
||||
return hashlib.sha256(destination.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def execute(args):
|
||||
if not sys.platform.startswith("linux") or os.geteuid() != 0:
|
||||
raise ValueError("Run as root on the Proxmox host; --dry-run works without Proxmox")
|
||||
for program in ("pct", "pvesh", "pveam", "pvesm"):
|
||||
if not shutil.which(program):
|
||||
raise ValueError("Missing Proxmox host command: " + program)
|
||||
import fcntl
|
||||
with open("/run/lock/finaltoken-proxmox.lock", "w", encoding="utf-8") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
# Prepare and validate the complete source bundle before creating any CT.
|
||||
with tempfile.TemporaryDirectory(prefix="finaltoken-source-") as directory:
|
||||
archive = Path(directory) / "source.tar.gz"
|
||||
sha = snapshot(args.source, archive)
|
||||
deploy(args, archive, sha)
|
||||
|
||||
|
||||
def deploy(args, archive, sha):
|
||||
ctid = args.ctid or int(json.loads(run(["pvesh", "get", "/cluster/nextid", "--output-format", "json"], capture=True).stdout))
|
||||
status = run(["pct", "status", ctid], capture=True, check=False)
|
||||
if args.action == "install":
|
||||
if status.returncode == 0:
|
||||
raise ValueError("CT already exists; refusing to overwrite it. Use update for a managed installation.")
|
||||
run(["pveam", "update"])
|
||||
template = args.template
|
||||
if not template:
|
||||
available = run(["pveam", "available", "--section", "system"], capture=True).stdout
|
||||
candidates = [word for word in available.split() if TEMPLATE.fullmatch(word)]
|
||||
if not candidates:
|
||||
raise ValueError("No Debian 13 amd64 template found; pass --template explicitly")
|
||||
template = sorted(candidates, key=lambda s: [int(p) if p.isdigit() else p for p in re.split(r"(\d+)", s)])[-1]
|
||||
path = run(["pvesm", "path", f"{args.template_storage}:vztmpl/{template}"], capture=True, check=False)
|
||||
if path.returncode or not Path(path.stdout.strip()).is_file():
|
||||
run(["pveam", "download", args.template_storage, template])
|
||||
run(create_command(args, ctid, template))
|
||||
else:
|
||||
if status.returncode:
|
||||
raise ValueError("Cannot access selected CT")
|
||||
# Reject foreign CTs before starting them or installing packages.
|
||||
metadata = json.loads(run(["pct", "exec", ctid, "--", "cat", "/etc/finaltoken/install.json"], capture=True).stdout) if "running" in status.stdout else None
|
||||
if metadata is None:
|
||||
raise ValueError("Start the existing managed CT before updating; stopped CTs are not modified")
|
||||
if metadata.get("installer") != "finaltoken-proxmox-v1" or metadata.get("ctid") != ctid:
|
||||
raise ValueError("Selected CT is not managed by this installer")
|
||||
if args.action == "install":
|
||||
run(["pct", "start", ctid])
|
||||
for _ in range(30):
|
||||
if run(["pct", "exec", ctid, "--", "test", "-d", "/run/systemd/system"], capture=True, check=False).returncode == 0:
|
||||
break
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise ValueError("CT did not become ready; it was retained for inspection")
|
||||
guest = Path(__file__).with_name("guest.py")
|
||||
token = uuid.uuid4().hex
|
||||
remote = "/tmp/finaltoken-" + token
|
||||
with tempfile.TemporaryDirectory(prefix="finaltoken-proxmox-") as tmp:
|
||||
tmp = Path(tmp)
|
||||
manifest = {"installer": "finaltoken-proxmox-v1", "ctid": ctid, "action": args.action, "sourceSha256": sha}
|
||||
if args.action == "install":
|
||||
manifest.update(role=args.role, domain=args.domain, tls=args.tls, machineId=args.machine_id or f"lxc_{ctid}",
|
||||
timezone=args.timezone, providers=args.providers, serverUrl=args.server_url,
|
||||
emails={p: getattr(args, p + "_email") or args.email for p in args.providers})
|
||||
if args.role == "worker":
|
||||
manifest["workerKey"] = args.enrollment_key
|
||||
manifest_path = tmp / "manifest.json"
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
manifest_path.chmod(0o600)
|
||||
# Only CT packages are changed. The Proxmox host package configuration is untouched.
|
||||
run(["pct", "exec", ctid, "--", "apt-get", "update"])
|
||||
run(["pct", "exec", ctid, "--", "env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", "python3", "ca-certificates"])
|
||||
try:
|
||||
for local, suffix in ((guest, ".py"), (archive, ".tar.gz"), (manifest_path, ".json")):
|
||||
run(["pct", "push", ctid, local, remote + suffix, "--perms", "0600"])
|
||||
run(["pct", "exec", ctid, "--", "python3", remote + ".py", "--manifest", remote + ".json", "--archive", remote + ".tar.gz"])
|
||||
finally:
|
||||
run(["pct", "exec", ctid, "--", "rm", "-f", remote + ".py", remote + ".json", remote + ".tar.gz"], capture=True, check=False)
|
||||
print(f"FinalToken {args.action} finished in CT {ctid}. Configuration and state are inside that CT.")
|
||||
print(f"Inspect services: pct exec {ctid} -- systemctl status 'finaltoken-*'")
|
||||
print(f"Read dashboard access key, when server installed: pct exec {ctid} -- cat /etc/finaltoken/dashboard-key")
|
||||
print("No container, profile or history is ever automatically deleted on failure.")
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
args = parser().parse_args(argv)
|
||||
validate(args)
|
||||
if args.dry_run:
|
||||
role = args.role or "preserve installed role"
|
||||
print(f"Plan: {args.action} CT {args.ctid or '<next free id>'}; role={role}; source={args.source}")
|
||||
print("Unprivileged Debian 13 amd64; build NativeAOT inside CT; preserve config, keys, history and CLI profiles.")
|
||||
if args.action == "install":
|
||||
print(f"Root storage={args.storage}; template storage={args.template_storage}; bridge={args.bridge}; IP={args.ip}")
|
||||
print(f"Dashboard={('https://' + args.domain) if args.domain else args.server_url}; TLS={args.tls}")
|
||||
return 0
|
||||
execute(args)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except (ValueError, OSError, subprocess.CalledProcessError) as error:
|
||||
# Never dump captured command output or the manifest (contains service keys).
|
||||
print("FinalToken setup failed: " + (str(error) if isinstance(error, ValueError) else type(error).__name__), file=sys.stderr)
|
||||
print("The CT and existing data were retained. Inspect it before retrying.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,442 @@
|
||||
"""Deterministic host/guest installer tests. No pct, apt, dotnet publish or service mutation."""
|
||||
import contextlib
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import patch, Mock
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(HERE))
|
||||
import host
|
||||
|
||||
# pwd is a Linux-only module; filesystem/command tests also run on the Windows development host.
|
||||
with patch.dict(sys.modules, {"pwd": types.SimpleNamespace(getpwnam=lambda _: types.SimpleNamespace(pw_gid=1000))} if os.name == "nt" else {}):
|
||||
spec = importlib.util.spec_from_file_location("guest", HERE / "guest.py")
|
||||
guest = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(guest)
|
||||
|
||||
|
||||
def install_args(*extra):
|
||||
args = host.parser().parse_args(["install", "--ctid", "201", "--storage", "local-lvm", "--domain", "usage.example.test", "--email", "[email protected]", *extra])
|
||||
host.validate(args)
|
||||
return args
|
||||
|
||||
|
||||
class HostTests(unittest.TestCase):
|
||||
def test_server_only_requires_no_provider_login_or_email(self):
|
||||
args = host.parser().parse_args(["install", "--role", "server", "--ctid", "201",
|
||||
"--storage", "local-lvm", "--domain", "usage.example.test"])
|
||||
host.validate(args)
|
||||
self.assertEqual("server", args.role)
|
||||
self.assertIsNone(args.email)
|
||||
|
||||
def test_default_creates_unprivileged_client_and_dashboard(self):
|
||||
args = install_args()
|
||||
command = host.create_command(args, 201, "debian-13-standard_13.1-1_amd64.tar.zst")
|
||||
self.assertEqual("both", args.role)
|
||||
self.assertEqual("1", command[command.index("--unprivileged") + 1])
|
||||
self.assertEqual("local-lvm:20", command[command.index("--rootfs") + 1])
|
||||
self.assertIn("ip=dhcp", command[command.index("--net0") + 1])
|
||||
self.assertNotIn("--features", command)
|
||||
|
||||
def test_static_network_and_vlan_are_separate_validated_values(self):
|
||||
args = install_args("--ip", "192.0.2.20/24", "--gateway", "192.0.2.1", "--vlan", "10")
|
||||
command = host.create_command(args, 201, "template")
|
||||
self.assertIn("gw=192.0.2.1,tag=10", command[command.index("--net0") + 1])
|
||||
|
||||
def test_rejects_injection_and_unsafe_configuration(self):
|
||||
for flags in (("--domain", "x.test;touch /tmp/no"), ("--machine-id", "x-201"),
|
||||
("--bridge", "vmbr0,ip=evil"), ("--ip", "192.0.2.2/24"), ("--vlan", "4095"),
|
||||
("--template", "../../template.tar.zst"), ("--memory", "512"), ("--providers", "claude,unknown")):
|
||||
with self.subTest(flags=flags), self.assertRaises(ValueError):
|
||||
install_args(*flags)
|
||||
|
||||
def test_worker_only_requires_https_and_enrollment_file(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
key = Path(tmp) / "enrollment"
|
||||
key.write_text("a" * 64)
|
||||
args = install_args("--role", "worker", "--server-url", "https://usage.example.test", "--worker-key-file", str(key))
|
||||
self.assertEqual("worker", args.role)
|
||||
with self.assertRaises(ValueError):
|
||||
install_args("--role", "worker", "--server-url", "http://usage.example.test", "--worker-key-file", str(key))
|
||||
key.write_text("short")
|
||||
with self.assertRaises(ValueError):
|
||||
install_args("--role", "worker", "--server-url", "https://usage.example.test", "--worker-key-file", str(key))
|
||||
|
||||
def test_dry_run_never_invokes_proxmox_or_reads_service_keys(self):
|
||||
with patch.object(host, "run", side_effect=AssertionError("must not execute")), contextlib.redirect_stdout(io.StringIO()) as output:
|
||||
self.assertEqual(0, host.main(["install", "--ctid", "201", "--storage", "local-lvm", "--domain", "usage.example.test", "--email", "[email protected]", "--dry-run"]))
|
||||
self.assertIn("Plan:", output.getvalue())
|
||||
|
||||
def test_pct_exec_explicitly_drops_host_environment(self):
|
||||
with patch.object(host.subprocess, "run") as runner:
|
||||
host.run(["pct", "exec", 201, "--", "true"])
|
||||
self.assertEqual(["pct", "exec", "201", "--keep-env", "0", "--", "true"], runner.call_args.args[0])
|
||||
|
||||
def test_update_cannot_silently_change_identity(self):
|
||||
args = host.parser().parse_args(["update", "--ctid", "201", "--email", "[email protected]"])
|
||||
with self.assertRaises(ValueError):
|
||||
host.validate(args)
|
||||
|
||||
def test_snapshot_includes_uncommitted_source_but_excludes_outputs_and_hidden_files(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp) / "repo"
|
||||
for project in host.PROJECTS:
|
||||
path = root / "src" / project
|
||||
path.mkdir(parents=True)
|
||||
(path / "New.cs").write_text("// uncommitted implementation")
|
||||
(path / ".env").write_text("never bundle")
|
||||
(path / "bin").mkdir()
|
||||
(path / "bin/out").write_text("not source")
|
||||
(path / "server.json").write_text('{"synthetic":"local runtime config"}')
|
||||
(path / "operator.env").write_text("SYNTHETIC_LOCAL_CONFIGURATION=placeholder")
|
||||
(path / "private.key").write_text("synthetic local key fixture")
|
||||
for name in ("Directory.Build.props", "Directory.Packages.props", "global.json", "LICENSE"):
|
||||
(root / name).write_text("fixture")
|
||||
archive = Path(tmp) / "source.tgz"
|
||||
digest = host.snapshot(root, archive)
|
||||
self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), digest)
|
||||
with tarfile.open(archive) as stream:
|
||||
names = stream.getnames()
|
||||
self.assertIn("src/FinalToken.Web/New.cs", names)
|
||||
self.assertIn("LICENSE", names)
|
||||
self.assertFalse(any(".env" in n or "/bin/" in n for n in names))
|
||||
self.assertFalse(any(n.endswith(("server.json", "operator.env", "private.key")) for n in names))
|
||||
|
||||
def test_existing_ct_is_never_overwritten(self):
|
||||
with patch.object(host, "run", return_value=subprocess.CompletedProcess([], 0, "status: running")) as runner:
|
||||
with self.assertRaises(ValueError):
|
||||
host.deploy(install_args(), Path("unused"), "0" * 64)
|
||||
self.assertEqual(1, runner.call_count)
|
||||
|
||||
def test_snapshot_refuses_a_symlinked_project_before_traversing_it(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp) / "repo"
|
||||
project = root / "src/FinalToken.Core"
|
||||
project.mkdir(parents=True)
|
||||
(project / "outside.txt").write_text("must not read")
|
||||
for name in ("Directory.Build.props", "Directory.Packages.props", "global.json", "LICENSE"):
|
||||
(root / name).write_text("fixture")
|
||||
original = Path.is_symlink
|
||||
with patch.object(Path, "is_symlink", lambda path: path == project or original(path)), self.assertRaises(ValueError):
|
||||
host.snapshot(root, Path(tmp) / "source.tgz")
|
||||
|
||||
def test_foreign_or_stopped_ct_is_not_updated(self):
|
||||
args = host.parser().parse_args(["update", "--ctid", "201"])
|
||||
host.validate(args)
|
||||
for status in ("status: stopped", "status: running"):
|
||||
calls = []
|
||||
def fake(command, **kwargs):
|
||||
calls.append(command)
|
||||
return subprocess.CompletedProcess(command, 0, status if command[1] == "status" else '{"installer":"foreign"}')
|
||||
with patch.object(host, "run", side_effect=fake), self.assertRaises(ValueError):
|
||||
host.deploy(args, Path("unused"), "0" * 64)
|
||||
self.assertFalse(any("apt-get" in c or "start" in c or "create" in c for c in calls))
|
||||
|
||||
def test_update_uploads_new_source_without_install_identity_or_ct_creation(self):
|
||||
args = host.parser().parse_args(["update", "--ctid", "201"])
|
||||
host.validate(args)
|
||||
calls, manifests = [], []
|
||||
def fake(command, **kwargs):
|
||||
command = list(map(str, command))
|
||||
calls.append(command)
|
||||
text = "status: running" if command[:2] == ["pct", "status"] else ""
|
||||
if command[-1] == "/etc/finaltoken/install.json":
|
||||
text = json.dumps({"installer": "finaltoken-proxmox-v1", "ctid": 201, "role": "server"})
|
||||
if command[:2] == ["pct", "push"] and command[3].endswith("manifest.json"):
|
||||
manifests.append(json.loads(Path(command[3]).read_text()))
|
||||
return subprocess.CompletedProcess(command, 0, text)
|
||||
with tempfile.TemporaryDirectory() as tmp, patch.object(host, "run", side_effect=fake), contextlib.redirect_stdout(io.StringIO()):
|
||||
archive = Path(tmp) / "source.tgz"
|
||||
archive.write_bytes(b"updated source fixture")
|
||||
host.deploy(args, archive, "a" * 64)
|
||||
self.assertEqual([{"installer": "finaltoken-proxmox-v1", "ctid": 201, "action": "update", "sourceSha256": "a" * 64}], manifests)
|
||||
self.assertFalse(any("create" in c or "start" in c or "destroy" in c for c in calls))
|
||||
self.assertTrue(any("python3" in c and "--manifest" in c for c in calls))
|
||||
|
||||
def test_install_orders_create_start_push_and_guest_without_shell_or_destroy(self):
|
||||
calls = []
|
||||
def fake(command, **kwargs):
|
||||
command = list(map(str, command))
|
||||
calls.append(command)
|
||||
text, code = "", 0
|
||||
if command[:2] == ["pct", "status"]:
|
||||
code = 1
|
||||
elif command[:2] == ["pveam", "available"]:
|
||||
text = "system debian-13-standard_13.1-1_amd64.tar.zst\nsystem debian-13-standard_13.2-1_amd64.tar.zst"
|
||||
elif command[:2] == ["pvesm", "path"]:
|
||||
code = 1
|
||||
return subprocess.CompletedProcess(command, code, text)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
archive = Path(tmp) / "source.tgz"
|
||||
archive.write_bytes(b"fixture")
|
||||
with patch.object(host, "run", side_effect=fake), contextlib.redirect_stdout(io.StringIO()):
|
||||
host.deploy(install_args(), archive, "0" * 64)
|
||||
verbs = [c[1] for c in calls if c[0] == "pct"]
|
||||
self.assertLess(verbs.index("create"), verbs.index("start"))
|
||||
self.assertLess(verbs.index("start"), verbs.index("push"))
|
||||
self.assertNotIn("destroy", verbs)
|
||||
self.assertTrue(any("local:vztmpl/debian-13-standard_13.2-1_amd64.tar.zst" in c for c in calls))
|
||||
self.assertFalse(any("sh" in c or "bash" in c for c in calls))
|
||||
|
||||
def test_guest_failure_cleans_uploads_and_never_destroys_container(self):
|
||||
calls = []
|
||||
def fake(command, **kwargs):
|
||||
command = list(map(str, command))
|
||||
calls.append(command)
|
||||
if "python3" in command and "--manifest" in command:
|
||||
raise subprocess.CalledProcessError(1, command)
|
||||
code = 1 if command[:2] in (["pct", "status"], ["pvesm", "path"]) else 0
|
||||
return subprocess.CompletedProcess(command, code, "")
|
||||
args = install_args("--template", "debian-13-standard_13.1-1_amd64.tar.zst")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
archive = Path(tmp) / "source.tgz"
|
||||
archive.write_bytes(b"fixture")
|
||||
with patch.object(host, "run", side_effect=fake), self.assertRaises(subprocess.CalledProcessError):
|
||||
host.deploy(args, archive, "0" * 64)
|
||||
self.assertIn("rm", calls[-1])
|
||||
self.assertNotIn("destroy", [c[1] for c in calls])
|
||||
|
||||
|
||||
class GuestTests(unittest.TestCase):
|
||||
def test_codex_npm_install_creates_the_configured_launcher(self):
|
||||
node, npm = shutil.which("node"), shutil.which("npm")
|
||||
if not node or not npm:
|
||||
self.skipTest("Offline npm launcher integration requires Node.js and npm")
|
||||
npm_path = Path(npm).resolve()
|
||||
npm_cli = npm_path if npm_path.suffix == ".js" else npm_path.parent / "node_modules/npm/bin/npm-cli.js"
|
||||
self.assertTrue(npm_cli.is_file(), "Cannot locate the installed npm CLI")
|
||||
with tempfile.TemporaryDirectory(prefix="finaltoken-npm-fixture-") as tmp:
|
||||
root = Path(tmp)
|
||||
package = root / "codex-fixture.tgz"
|
||||
with tarfile.open(package, "w:gz") as archive:
|
||||
files = {"package/package.json": json.dumps({"name": "@finaltoken/offline-codex-fixture", "version": "1.0.0",
|
||||
"bin": {"codex": "cli.js"}}), "package/cli.js": "#!/usr/bin/env node\nconsole.log('synthetic codex fixture');\n"}
|
||||
for name, value in files.items():
|
||||
content = value.encode("utf-8")
|
||||
item = tarfile.TarInfo(name)
|
||||
item.size, item.mode = len(content), 0o755
|
||||
archive.addfile(item, io.BytesIO(content))
|
||||
user_config, global_config = root / "user.npmrc", root / "global.npmrc"
|
||||
user_config.write_text(""); global_config.write_text("")
|
||||
env = {name: os.environ[name] for name in ("PATH", "SystemRoot", "TEMP", "TMP", "ComSpec", "PATHEXT") if name in os.environ}
|
||||
env.update(NPM_CONFIG_USERCONFIG=str(user_config), NPM_CONFIG_GLOBALCONFIG=str(global_config))
|
||||
home = root / "worker"
|
||||
home.mkdir()
|
||||
versions = []
|
||||
def local_user(name, directory, command, **kwargs):
|
||||
self.assertEqual("finaltoken", name)
|
||||
self.assertEqual(home, directory)
|
||||
if command[0] == "npm":
|
||||
arguments = list(command[1:-1])
|
||||
prefix_index = arguments.index("--prefix") + 1
|
||||
prefix = Path(arguments[prefix_index])
|
||||
# npm puts global launchers directly in the prefix on Windows;
|
||||
# adapt that platform boundary to exercise the guest's Linux bin path.
|
||||
if os.name == "nt":
|
||||
arguments[prefix_index] = str(prefix / "bin")
|
||||
return subprocess.run([node, str(npm_cli), *arguments, str(package), "--offline", "--ignore-scripts",
|
||||
"--no-audit", "--no-fund", "--cache", str(root / "cache")], env=env, cwd=root,
|
||||
text=True, capture_output=True, check=True, timeout=30)
|
||||
launcher = home / ".local/bin/codex"
|
||||
self.assertEqual([str(launcher), "--version"], command)
|
||||
self.assertTrue(launcher.is_file(), "npm did not install the configured Codex launcher")
|
||||
installed = home / (".local/bin/node_modules" if os.name == "nt" else ".local/lib/node_modules")
|
||||
result = subprocess.run([node, str(installed / "@finaltoken/offline-codex-fixture/cli.js"), "--version"],
|
||||
env=env, cwd=root, text=True, capture_output=True, check=True, timeout=10)
|
||||
versions.append(result.stdout.strip())
|
||||
with patch.object(guest, "WORKER_HOME", home), patch.object(guest, "as_user", side_effect=local_user):
|
||||
guest.official_clis(["codex"])
|
||||
guest.official_clis(["codex"]) # Existing launcher is used on subsequent runs.
|
||||
self.assertEqual(["synthetic codex fixture"] * 2, versions)
|
||||
|
||||
def test_server_update_uses_persisted_identity_and_preserves_config_and_history(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
etc = root / "etc"
|
||||
etc.mkdir()
|
||||
archive = root / "source.tgz"
|
||||
archive.write_bytes(b"updated server fixture")
|
||||
digest = hashlib.sha256(archive.read_bytes()).hexdigest()
|
||||
identity = {"installer": guest.INSTALLER, "ctid": 201, "installed": True,
|
||||
"role": "server", "providers": [], "domain": "usage.example.test",
|
||||
"sourceSha256": "0" * 64, "release": "previous"}
|
||||
(etc / "install.json").write_text(json.dumps(identity))
|
||||
config, history = etc / "server.json", root / "history.json"
|
||||
config.write_text('{"operator":"custom"}')
|
||||
history.write_text("synthetic retained history")
|
||||
manifest = {"installer": guest.INSTALLER, "ctid": 201, "action": "update", "sourceSha256": digest}
|
||||
original_read = Path.read_text
|
||||
def read(path, *a, **kw):
|
||||
return 'ID=debian\nVERSION_ID="13"\n' if path.as_posix() == "/etc/os-release" else original_read(path, *a, **kw)
|
||||
with patch.object(guest, "ETC", etc), patch.object(guest.os, "geteuid", return_value=0, create=True), \
|
||||
patch.object(guest.os, "uname", return_value=types.SimpleNamespace(machine="x86_64"), create=True), \
|
||||
patch.object(Path, "read_text", read), patch.object(guest, "packages") as packages, \
|
||||
patch.object(guest, "configure") as configure, patch.object(guest, "official_clis") as clis, \
|
||||
patch.object(guest, "build", return_value=root / "release-v2") as build, \
|
||||
patch.object(guest, "activate") as activate, contextlib.redirect_stdout(io.StringIO()):
|
||||
guest.provision(manifest, archive)
|
||||
packages.assert_called_once_with("server", [])
|
||||
configure.assert_not_called()
|
||||
clis.assert_not_called()
|
||||
activate.assert_called_once_with(root / "release-v2", build.call_args.args[1], False)
|
||||
updated = json.loads((etc / "install.json").read_text())
|
||||
self.assertEqual("server", updated["role"])
|
||||
self.assertEqual("usage.example.test", updated["domain"])
|
||||
self.assertEqual(digest, updated["sourceSha256"])
|
||||
self.assertEqual(str(root / "release-v2"), updated["release"])
|
||||
self.assertEqual('{"operator":"custom"}', config.read_text())
|
||||
self.assertEqual("synthetic retained history", history.read_text())
|
||||
|
||||
def test_native_release_preserves_source_license(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
archive = root / "source.tgz"
|
||||
license_text = b"Synthetic MIT notice\n"
|
||||
with tarfile.open(archive, "w:gz") as stream:
|
||||
item = tarfile.TarInfo("LICENSE")
|
||||
item.size = len(license_text)
|
||||
stream.addfile(item, io.BytesIO(license_text))
|
||||
home = root / "build"
|
||||
home.mkdir()
|
||||
def fake_publish(name, home, command, **kwargs):
|
||||
target = Path(command[command.index("-o") + 1])
|
||||
target.mkdir(parents=True)
|
||||
header = b"\x7fELF" + b"\0" * 14 + b"\x3e\x00"
|
||||
(target / "finaltoken-worker").write_bytes(header)
|
||||
with patch.object(guest, "APP", root / "app"), patch.object(guest, "BUILD", home), \
|
||||
patch.object(guest, "user", return_value=types.SimpleNamespace(pw_uid=0, pw_gid=0)), \
|
||||
patch.object(guest.os, "chown", create=True), patch.object(guest, "as_user", side_effect=fake_publish):
|
||||
release = guest.build(archive, {"role": "worker", "sourceSha256": "0" * 64})
|
||||
self.assertEqual(license_text, (release / "LICENSE").read_bytes())
|
||||
|
||||
def test_atomic_configuration_is_never_replaced_on_update(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
target = Path(tmp) / "config.json"
|
||||
guest.atomic(target, "original", once=True)
|
||||
self.assertFalse(guest.atomic(target, "replacement", once=True))
|
||||
self.assertEqual("original", target.read_text())
|
||||
guest.atomic(target, "explicit replacement")
|
||||
self.assertEqual("explicit replacement", target.read_text())
|
||||
self.assertEqual([target], list(target.parent.iterdir()))
|
||||
|
||||
def test_archive_rejects_traversal_links_and_devices(self):
|
||||
for name, kind in (("../escape", tarfile.REGTYPE), ("/absolute", tarfile.REGTYPE), ("link", tarfile.SYMTYPE), ("device", tarfile.CHRTYPE)):
|
||||
with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp:
|
||||
archive = Path(tmp) / "source.tgz"
|
||||
with tarfile.open(archive, "w:gz") as stream:
|
||||
item = tarfile.TarInfo(name)
|
||||
item.type = kind
|
||||
stream.addfile(item)
|
||||
with self.assertRaises(ValueError):
|
||||
guest.unpack(archive, Path(tmp) / "extract")
|
||||
self.assertFalse((Path(tmp) / "escape").exists())
|
||||
|
||||
def test_config_generates_bound_profiles_and_preserves_keys_and_settings(self):
|
||||
with tempfile.TemporaryDirectory() as tmp, contextlib.ExitStack() as stack:
|
||||
root = Path(tmp)
|
||||
for name, relative in (("ETC", "etc"), ("WORKER_HOME", "worker"), ("SERVER_HOME", "server"), ("PROXY_HOME", "proxy"), ("SYSTEMD", "units")):
|
||||
stack.enter_context(patch.object(guest, name, root / relative))
|
||||
stack.enter_context(patch.object(guest, "run"))
|
||||
stack.enter_context(patch.object(guest, "user"))
|
||||
stack.enter_context(patch.object(guest.pwd, "getpwnam", return_value=types.SimpleNamespace(pw_gid=1000)))
|
||||
stack.enter_context(patch.object(guest.os, "chown", create=True))
|
||||
meta = {"role": "both", "providers": ["claude", "codex"], "ctid": 201, "machineId": "lxc_201", "timezone": "UTC",
|
||||
"domain": "usage.example.test", "tls": "internal", "emails": {"claude": "[email protected]", "codex": "[email protected]"}}
|
||||
guest.configure(meta)
|
||||
config = json.loads((guest.ETC / "server.json").read_text())
|
||||
self.assertEqual("finaltoken", config["machines"][0]["osUser"])
|
||||
self.assertEqual("lxc_201", config["machines"][0]["id"])
|
||||
worker = json.loads((guest.ETC / "worker.json").read_text())
|
||||
self.assertEqual("http://127.0.0.1:5187", worker["serverUrl"])
|
||||
self.assertEqual(2, len(worker["profiles"]))
|
||||
keys = (guest.ETC / "transport-keys.json").read_bytes()
|
||||
(guest.ETC / "worker.json").write_text('{"operator":"custom"}')
|
||||
guest.configure(meta)
|
||||
self.assertEqual(keys, (guest.ETC / "transport-keys.json").read_bytes())
|
||||
self.assertEqual({"operator": "custom"}, json.loads((guest.ETC / "worker.json").read_text()))
|
||||
self.assertIn("tls internal", (guest.ETC / "Caddyfile").read_text())
|
||||
|
||||
def test_units_use_profile_owner_and_kill_child_processes(self):
|
||||
worker = guest.service_unit("worker")
|
||||
self.assertIn("User=finaltoken\n", worker)
|
||||
self.assertIn("KillMode=control-group", worker)
|
||||
self.assertIn("NoNewPrivileges=true", worker)
|
||||
self.assertIn("User=finaltoken-server", guest.service_unit("server"))
|
||||
self.assertNotIn("MemoryDenyWriteExecute", worker) # Node-based CLIs can need JIT.
|
||||
|
||||
def test_worker_commands_do_not_inherit_root_environment(self):
|
||||
with patch.object(guest, "run") as runner:
|
||||
guest.as_user("finaltoken", PurePosixPath("/worker"), ["claude", "--version"])
|
||||
command = runner.call_args.args[0]
|
||||
self.assertIn("-i", command)
|
||||
self.assertIn("HOME=/worker", command)
|
||||
self.assertNotIn("shell", runner.call_args.kwargs)
|
||||
|
||||
def test_failed_activation_restores_previous_release_without_touching_data(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
old = root / "releases/old"
|
||||
old.mkdir(parents=True)
|
||||
new = root / "releases/new"
|
||||
new.mkdir()
|
||||
history = root / "history.json"
|
||||
history.write_text("unchanged")
|
||||
fake_current = Mock()
|
||||
fake_current.is_symlink.return_value = True
|
||||
fake_current.resolve.return_value = old
|
||||
fake_app = Mock()
|
||||
fake_app.__truediv__ = Mock(return_value=fake_current)
|
||||
with patch.object(guest, "APP", fake_app), patch.object(guest, "switch") as switch, \
|
||||
patch.object(guest, "run", return_value=subprocess.CompletedProcess([], 0)), patch.object(guest, "healthy", return_value=False), \
|
||||
contextlib.redirect_stderr(io.StringIO()), self.assertRaises(ValueError):
|
||||
guest.activate(new, {"role": "both"}, False)
|
||||
self.assertEqual([new, old], [c.args[0] for c in switch.call_args_list])
|
||||
self.assertEqual("unchanged", history.read_text())
|
||||
|
||||
def test_update_does_not_start_intentionally_stopped_services(self):
|
||||
current = Mock()
|
||||
current.is_symlink.return_value = False
|
||||
app = Mock()
|
||||
app.__truediv__ = Mock(return_value=current)
|
||||
with patch.object(guest, "APP", app), patch.object(guest, "switch"), patch.object(guest, "healthy") as health, \
|
||||
patch.object(guest, "run", return_value=subprocess.CompletedProcess([], 3)) as runner:
|
||||
guest.activate(Path("unused"), {"role": "worker"}, False)
|
||||
health.assert_not_called()
|
||||
self.assertFalse(any("restart" in call.args[0] or "enable" in call.args[0] for call in runner.call_args_list))
|
||||
|
||||
def test_enrollment_key_survives_partial_install_before_packages_fail(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
directory = Path(tmp)
|
||||
archive = directory / "source.tgz"
|
||||
archive.write_bytes(b"fixture")
|
||||
meta = {"installer": guest.INSTALLER, "action": "install", "ctid": 201,
|
||||
"sourceSha256": hashlib.sha256(b"fixture").hexdigest(), "workerKey": "a" * 64}
|
||||
original_read = Path.read_text
|
||||
def read(path, *a, **kw):
|
||||
return 'ID=debian\nVERSION_ID="13"\n' if path.as_posix() == "/etc/os-release" else original_read(path, *a, **kw)
|
||||
with patch.object(guest, "ETC", directory / "etc"), patch.object(guest.os, "geteuid", return_value=0, create=True), \
|
||||
patch.object(guest.os, "uname", return_value=types.SimpleNamespace(machine="x86_64"), create=True), \
|
||||
patch.object(Path, "read_text", read), patch.object(guest, "packages", side_effect=ValueError("network failure")):
|
||||
meta.update(role="worker", providers=["codex"])
|
||||
with self.assertRaises(ValueError):
|
||||
guest.provision(meta, archive)
|
||||
marker = json.loads((directory / "etc/install.json").read_text())
|
||||
keys = json.loads((directory / "etc/transport-keys.json").read_text())
|
||||
self.assertFalse(marker["installed"])
|
||||
self.assertNotIn("workerKey", marker)
|
||||
self.assertEqual("a" * 64, keys["worker"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,189 @@
|
||||
"""Real local Git/Bash updater checks. No network, Proxmox, package or service changes."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "proxmox-update.sh"
|
||||
GIT = shutil.which("git")
|
||||
WINDOWS_BASH = Path(GIT).resolve().parents[1] / "bin/bash.exe" if GIT else Path("missing")
|
||||
BASH = str(WINDOWS_BASH) if os.name == "nt" and WINDOWS_BASH.is_file() else shutil.which("bash")
|
||||
|
||||
|
||||
class UpdaterTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
if not GIT or not BASH:
|
||||
self.fail("Git and Bash are required for the updater integration checks")
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix="finaltoken-update-")
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name)
|
||||
self.seed, self.remote, self.clone = (self.root / n for n in ("seed", "remote.git", "clone"))
|
||||
self.output = self.root / "invocation"
|
||||
self.env = dict(os.environ, GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_SYSTEM=os.devnull,
|
||||
GIT_CONFIG_NOSYSTEM="1", GIT_TERMINAL_PROMPT="0", GCM_INTERACTIVE="Never",
|
||||
FT_TEST_RESULT=self.output.as_posix())
|
||||
self.git(self.root, "init", "--bare", "--initial-branch=master", str(self.remote))
|
||||
self.git(self.root, "init", "--initial-branch=master", str(self.seed))
|
||||
(self.seed / "tools").mkdir()
|
||||
(self.seed / "tools/proxmox-update.sh").write_bytes(SCRIPT.read_bytes())
|
||||
(self.seed / ".gitignore").write_text("ignored-state/\n")
|
||||
self.installer("v1")
|
||||
self.commit(self.seed, "Initial fixture")
|
||||
self.git(self.seed, "remote", "add", "origin", str(self.remote))
|
||||
self.git(self.seed, "push", "-u", "origin", "master")
|
||||
self.git(self.root, "clone", str(self.remote), str(self.clone))
|
||||
# Git Bash has no flock. Exercise its refusal path with this command seam;
|
||||
# Linux advisory locking itself is deliberately not claimed by these tests.
|
||||
self.bin = self.root / "bin"
|
||||
self.bin.mkdir()
|
||||
(self.bin / "flock").write_text('#!/usr/bin/env bash\nexit "${FT_TEST_LOCK_EXIT:-0}"\n')
|
||||
(self.bin / "flock").chmod(0o755)
|
||||
self.env["PATH"] = str(self.bin) + os.pathsep + self.env["PATH"]
|
||||
|
||||
def git(self, directory, *arguments):
|
||||
return subprocess.run([GIT, "-c", "user.name=Fixture", "-c", "[email protected]",
|
||||
"-c", "commit.gpgsign=false", "-c", "core.hooksPath=", "-C", str(directory),
|
||||
*arguments], env=self.env, text=True, capture_output=True, check=True)
|
||||
|
||||
def commit(self, directory, message):
|
||||
self.git(directory, "add", ".")
|
||||
self.git(directory, "commit", "-m", message)
|
||||
|
||||
def installer(self, version):
|
||||
(self.seed / "tools/proxmox.sh").write_text(
|
||||
'#!/usr/bin/env bash\nset -euo pipefail\n'
|
||||
f'printf "%s\\n" "{version}" "$@" > "$FT_TEST_RESULT"\n'
|
||||
'exit "${FT_TEST_EXIT:-0}"\n')
|
||||
|
||||
def publish(self):
|
||||
self.installer("v2")
|
||||
self.commit(self.seed, "Update fixture installer")
|
||||
self.git(self.seed, "push")
|
||||
|
||||
def update(self, *arguments):
|
||||
# The caller's cwd deliberately differs from the checkout location.
|
||||
return subprocess.run([BASH, str(self.clone / "tools/proxmox-update.sh"), *arguments],
|
||||
cwd=self.root, env=self.env, text=True, capture_output=True)
|
||||
|
||||
def test_refresh_executes_new_installer_and_passes_exact_ctid_and_source(self):
|
||||
self.publish()
|
||||
result = self.update("201")
|
||||
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
lines = self.output.read_text().splitlines()
|
||||
self.assertEqual(["v2", "update", "--ctid", "201", "--source"], lines[:-1])
|
||||
# Git Bash reports /c/... while native Windows Python uses C:/....
|
||||
self.assertTrue(lines[-1].replace("\\", "/").endswith("/clone"))
|
||||
self.assertEqual(self.git(self.seed, "rev-parse", "HEAD").stdout,
|
||||
self.git(self.clone, "rev-parse", "HEAD").stdout)
|
||||
|
||||
def test_no_new_commit_still_runs_installer_to_resume_failed_deployment(self):
|
||||
result = self.update("201")
|
||||
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
self.assertEqual("v1", self.output.read_text().splitlines()[0])
|
||||
|
||||
def test_dry_run_never_fetches_or_changes_checkout(self):
|
||||
before = self.git(self.clone, "rev-parse", "HEAD").stdout
|
||||
self.publish()
|
||||
result = self.update("201", "--dry-run")
|
||||
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
self.assertIn("--dry-run", self.output.read_text().splitlines())
|
||||
self.assertEqual(before, self.git(self.clone, "rev-parse", "HEAD").stdout)
|
||||
self.assertFalse((self.clone / ".git/FETCH_HEAD").exists())
|
||||
self.assertFalse((self.clone / ".git/finaltoken-proxmox-update.lock").exists())
|
||||
|
||||
def test_dirty_tracked_staged_or_untracked_source_is_retained_and_not_deployed(self):
|
||||
for state in ("tracked", "staged", "untracked"):
|
||||
with self.subTest(state=state):
|
||||
path = self.clone / ("local.txt" if state == "untracked" else ".gitignore")
|
||||
original = path.read_bytes() if path.exists() else None
|
||||
path.write_text("operator local change\n")
|
||||
if state == "staged":
|
||||
self.git(self.clone, "add", str(path))
|
||||
result = self.update("201")
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertIn("clean", result.stderr)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual("operator local change\n", path.read_text())
|
||||
self.git(self.clone, "reset", "--", str(path))
|
||||
if original is None:
|
||||
path.unlink()
|
||||
else:
|
||||
path.write_bytes(original)
|
||||
|
||||
def test_diverged_or_ahead_branch_is_not_deployed_or_reset(self):
|
||||
(self.clone / "operator.txt").write_text("local commit fixture")
|
||||
self.commit(self.clone, "Local-only fixture")
|
||||
before = self.git(self.clone, "rev-parse", "HEAD").stdout
|
||||
for diverged in (False, True):
|
||||
with self.subTest(diverged=diverged):
|
||||
if diverged:
|
||||
self.publish()
|
||||
result = self.update("201")
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(before, self.git(self.clone, "rev-parse", "HEAD").stdout)
|
||||
self.assertEqual("local commit fixture", (self.clone / "operator.txt").read_text())
|
||||
|
||||
def test_no_upstream_or_detached_head_never_deploys(self):
|
||||
self.git(self.clone, "branch", "--unset-upstream")
|
||||
self.assertNotEqual(0, self.update("201").returncode)
|
||||
self.git(self.clone, "checkout", "--detach")
|
||||
self.assertNotEqual(0, self.update("201").returncode)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
def test_fetch_failure_leaves_checkout_and_does_not_deploy_or_echo_remote(self):
|
||||
self.git(self.clone, "remote", "set-url", "origin", str(self.root / "private-origin-not-available"))
|
||||
before = self.git(self.clone, "rev-parse", "HEAD").stdout
|
||||
result = self.update("201")
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertNotIn("private-origin-not-available", result.stdout + result.stderr)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(before, self.git(self.clone, "rev-parse", "HEAD").stdout)
|
||||
|
||||
def test_busy_checkout_never_pulls_or_deploys(self):
|
||||
self.env["FT_TEST_LOCK_EXIT"] = "1"
|
||||
self.publish()
|
||||
before = self.git(self.clone, "rev-parse", "HEAD").stdout
|
||||
self.assertNotEqual(0, self.update("201").returncode)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(before, self.git(self.clone, "rev-parse", "HEAD").stdout)
|
||||
|
||||
def test_installer_failure_propagates_and_keeps_ignored_local_state(self):
|
||||
state = self.clone / "ignored-state/history.json"
|
||||
state.parent.mkdir()
|
||||
state.write_text("synthetic local history")
|
||||
self.env["FT_TEST_EXIT"] = "17"
|
||||
result = self.update("201")
|
||||
self.assertEqual(17, result.returncode, result.stdout + result.stderr)
|
||||
self.assertEqual("synthetic local history", state.read_text())
|
||||
|
||||
def test_upstream_cannot_overwrite_ignored_operator_state(self):
|
||||
relative = "ignored-state/history.json"
|
||||
local = self.clone / relative
|
||||
local.parent.mkdir()
|
||||
local.write_text("synthetic retained operator history")
|
||||
upstream = self.seed / relative
|
||||
upstream.parent.mkdir()
|
||||
upstream.write_text("upstream fixture must not overwrite operator data")
|
||||
self.git(self.seed, "add", "--force", relative)
|
||||
self.publish()
|
||||
before = self.git(self.clone, "rev-parse", "HEAD").stdout
|
||||
result = self.update("201")
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(before, self.git(self.clone, "rev-parse", "HEAD").stdout)
|
||||
self.assertEqual("synthetic retained operator history", local.read_text())
|
||||
|
||||
def test_invalid_arguments_are_rejected_before_fetch(self):
|
||||
for arguments in ((), ("99",), ("201", "--source", "/tmp/other"), ("201;touch /tmp/no",), ("201", "--unknown")):
|
||||
with self.subTest(arguments=arguments):
|
||||
self.assertNotEqual(0, self.update(*arguments).returncode)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertFalse((self.clone / ".git/FETCH_HEAD").exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -51,6 +51,8 @@ def main():
|
||||
else:
|
||||
shutil.copy2(file, target)
|
||||
shutil.copytree(root / 'src' / 'FinalToken.StreamDeck' / 'plugin', plugin, dirs_exist_ok=True)
|
||||
shutil.copy2(root / 'LICENSE', output / 'LICENSE')
|
||||
shutil.copy2(root / 'LICENSE', plugin / 'LICENSE')
|
||||
manifest_path = plugin / 'manifest.json'
|
||||
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
|
||||
manifest['Version'] = plugin_version
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Shared publication/deployment policy for local runtime files; never read their contents."""
|
||||
from pathlib import PurePosixPath
|
||||
|
||||
PRIVATE_NAMES = {"server.json", "worker.json", "server.env", "worker.env", "transport-keys.json", "dashboard-key", "worker-key",
|
||||
"auth.json", ".credentials.json", "snapshot.json", "fleet.json", "history.json", "history.state.json",
|
||||
"history.journal.jsonl", "usage.json", "profile.json", "settings.json", "id_rsa", "id_ecdsa", "id_ed25519"}
|
||||
|
||||
|
||||
def is_private_path(path):
|
||||
p = PurePosixPath(str(path).replace("\\", "/").lower())
|
||||
return (p.name in PRIVATE_NAMES or p.name == ".env" or p.name.startswith(".env.") and p.name != ".env.example"
|
||||
or p.suffix in (".env", ".key", ".pem", ".pfx", ".p12")
|
||||
or any(part in (".claude", ".codex", ".ssh", ".aws", ".azure") for part in p.parts)
|
||||
or len(p.parts) > 1 and p.parts[0] in ("data", "state", "logs", "runs", "history"))
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Publication guard tests use synthetic values and read-only Git ignore queries."""
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import check_public
|
||||
|
||||
|
||||
class PublicCheckTests(unittest.TestCase):
|
||||
def test_private_names_are_reported_without_reading_them(self):
|
||||
for path in ("server.json", "deploy/worker.env", "profiles/.codex/auth.json", "fleet.json", "private.pem", ".env.production"):
|
||||
with self.subTest(path=path):
|
||||
self.assertTrue(check_public.sensitive_path(path))
|
||||
|
||||
def test_source_and_placeholder_examples_are_allowed(self):
|
||||
for path in ("server.example.json", "src/FinalToken.Core/HistoryStore.cs", "docs/web-dashboard.md", ".env.example", "LICENSE"):
|
||||
self.assertFalse(check_public.sensitive_path(path))
|
||||
|
||||
def test_matching_values_never_appear_in_findings(self):
|
||||
synthetic = "sk-" + "ant-" + "x" * 32
|
||||
findings = check_public.inspect("synthetic.txt", ("header\n" + synthetic).encode())
|
||||
self.assertEqual(1, len(findings))
|
||||
self.assertEqual(2, findings[0].line)
|
||||
self.assertEqual("provider token", findings[0].kind)
|
||||
self.assertNotIn(synthetic, repr(findings))
|
||||
|
||||
def test_private_key_and_url_credentials_are_detected(self):
|
||||
key = b"-----BEGIN " + b"PRIVATE KEY-----"
|
||||
url = b"https://" + b"fixture:[email protected]/repo.git"
|
||||
self.assertEqual({"private key", "credential in URL"}, {f.kind for f in check_public.inspect("fixture", key + b"\n" + url)})
|
||||
|
||||
def test_binary_input_is_not_treated_as_source(self):
|
||||
self.assertEqual([], check_public.inspect("image.png", b"\0" + b"sk-" + b"ant-" + b"x" * 32))
|
||||
|
||||
def test_staged_secret_is_found_even_when_working_copy_is_clean(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / "source.txt").write_text("clean working copy")
|
||||
staged = ("sk-" + "proj-" + "x" * 32).encode()
|
||||
oid = "a" * 40
|
||||
def fake_git(where, *args, data=None):
|
||||
if args[0] == "ls-files" and "--stage" in args:
|
||||
return f"100644 {oid} 0\tsource.txt\0".encode()
|
||||
if args[0] == "ls-files":
|
||||
return b"source.txt\0"
|
||||
if args[:2] == ("cat-file", "-s"):
|
||||
return str(len(staged)).encode()
|
||||
if args[:2] == ("cat-file", "blob"):
|
||||
return staged
|
||||
self.fail("Unexpected Git read")
|
||||
with patch.object(check_public, "git", side_effect=fake_git):
|
||||
findings, _, _ = check_public.working_tree(root)
|
||||
self.assertTrue(any(f.path.startswith("index:") and f.kind == "provider token" for f in findings))
|
||||
|
||||
def test_working_tree_symlink_is_rejected_before_resolving_its_target(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
with patch.object(check_public, "git", return_value=b"link.cs\0"), \
|
||||
patch.object(check_public, "index", return_value=([], 0, [])), \
|
||||
patch.object(Path, "is_symlink", return_value=True), patch.object(Path, "read_bytes", side_effect=AssertionError("must not read")):
|
||||
findings, _, _ = check_public.working_tree(root)
|
||||
self.assertEqual("symlink/outside source tree", findings[0].kind)
|
||||
|
||||
def test_historical_private_name_is_detected_when_same_blob_had_a_public_name(self):
|
||||
oid = "c" * 40
|
||||
def fake_git(root, *args, data=None):
|
||||
if args[0] == "rev-list":
|
||||
return b"first\nsecond\n"
|
||||
name = "examples/example.json" if args[-1] == "first" else "auth.json"
|
||||
return f"100644 blob {oid}\t{name}\0".encode()
|
||||
with patch.object(check_public, "git", side_effect=fake_git):
|
||||
paths = check_public.historical_private_paths(Path("unused"))
|
||||
self.assertEqual({oid: {"auth.json"}}, paths)
|
||||
|
||||
def test_staged_private_file_is_reported_without_opening_its_blob(self):
|
||||
def fake_git(root, *args, data=None):
|
||||
self.assertEqual("ls-files", args[0])
|
||||
return ("100644 " + "a" * 40 + " 0\tserver.env\0").encode()
|
||||
with patch.object(check_public, "git", side_effect=fake_git):
|
||||
findings, count, _ = check_public.index(Path("unused"))
|
||||
self.assertEqual(0, count)
|
||||
self.assertEqual("index:server.env", findings[0].path)
|
||||
|
||||
def test_git_ignores_live_runtime_data_but_keeps_examples(self):
|
||||
paths = ["server.json", "deploy/worker.json", "server.env", ".env.production", "transport-keys.json", "fleet.json",
|
||||
"snapshot.json", "history.journal.jsonl", "profiles/.codex/auth.json", "private.key", "logs/session.log"]
|
||||
result = subprocess.run(["git", "check-ignore", "-z", "--stdin"], cwd=check_public.ROOT,
|
||||
input=("\0".join(paths) + "\0").encode(), capture_output=True, check=True)
|
||||
self.assertEqual(set(paths), set(result.stdout.decode().strip("\0").split("\0")))
|
||||
examples = subprocess.run(["git", "check-ignore", "-z", "--stdin"], cwd=check_public.ROOT,
|
||||
input=b".env.example\0server.example.json\0LICENSE\0", capture_output=True)
|
||||
self.assertEqual(1, examples.returncode)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -7,12 +7,28 @@ import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import xml.etree.ElementTree as ET
|
||||
import zipfile
|
||||
|
||||
import publish
|
||||
|
||||
|
||||
class PublishTests(unittest.TestCase):
|
||||
def test_published_manifest_uses_shared_version(self):
|
||||
self.check_package()
|
||||
|
||||
def test_license_copy_preserves_lf_and_crlf_bytes(self):
|
||||
for newline in (b'\n', b'\r\n'):
|
||||
with self.subTest(newline=newline), tempfile.TemporaryDirectory(prefix='finaltoken-license-') as temporary:
|
||||
root = Path(temporary)
|
||||
(root / 'Directory.Build.props').write_text('<Project><Version>1.2.3</Version></Project>')
|
||||
(root / 'LICENSE').write_bytes(newline.join([b'Synthetic MIT notice', b'Copyright fixture', b'']))
|
||||
plugin = root / 'src/FinalToken.StreamDeck/plugin'
|
||||
plugin.mkdir(parents=True)
|
||||
(plugin / 'manifest.json').write_text('{"Version":"0.0.0.0"}')
|
||||
with patch.object(publish, '__file__', str(root / 'tools/publish.py')):
|
||||
self.check_package()
|
||||
|
||||
def check_package(self):
|
||||
def fake_publish(command, **kwargs):
|
||||
stage = Path(command[command.index('-o') + 1])
|
||||
stage.mkdir(parents=True)
|
||||
@@ -28,6 +44,11 @@ class PublishTests(unittest.TestCase):
|
||||
self.assertIsNotNone(version)
|
||||
manifest = json.loads((output / 'streamdeck/de.finalfactory.finaltoken.sdPlugin/manifest.json').read_text(encoding='utf-8'))
|
||||
self.assertEqual(version + '.0', manifest['Version'])
|
||||
license_bytes = (Path(publish.__file__).resolve().parent.parent / 'LICENSE').read_bytes()
|
||||
self.assertEqual(license_bytes, (output / 'LICENSE').read_bytes())
|
||||
self.assertEqual(license_bytes, (output / 'streamdeck/de.finalfactory.finaltoken.sdPlugin/LICENSE').read_bytes())
|
||||
with zipfile.ZipFile(output.with_suffix('.zip')) as bundle:
|
||||
self.assertEqual(license_bytes, bundle.read('LICENSE'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
"""Provider-free HTTP + real worker/process integration. Build the solution first. Never uses installed providers."""
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import getpass
|
||||
import http.cookiejar
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
KEY = "synthetic-dashboard-key-for-local-tests-only-123456"
|
||||
WORKER_KEY = "synthetic-worker-key-for-local-tests-only-abcdef"
|
||||
|
||||
|
||||
def wait_for(check, timeout=30):
|
||||
end = time.monotonic() + timeout
|
||||
while time.monotonic() < end:
|
||||
value = check()
|
||||
if value:
|
||||
return value
|
||||
time.sleep(.1)
|
||||
raise AssertionError("Timed out waiting for synthetic integration condition")
|
||||
|
||||
|
||||
class Fixture:
|
||||
def __init__(self, port=None):
|
||||
self.temp = tempfile.TemporaryDirectory(prefix="finaltoken-web-test-")
|
||||
self.path = Path(self.temp.name)
|
||||
self.processes = []
|
||||
if port is None:
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
self.url = f"http://127.0.0.1:{port}"
|
||||
self.jar = http.cookiejar.CookieJar()
|
||||
self.browser = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.jar))
|
||||
self.csrf = None
|
||||
self.now = dt.datetime.now(dt.timezone.utc)
|
||||
self.claude = self.path / "claude"
|
||||
self.codex = self.path / "codex"
|
||||
self.claude.mkdir()
|
||||
self.codex.mkdir()
|
||||
# Windows locks loaded assemblies. Run fixture-owned copies so builds can continue during visual QA.
|
||||
for project in ("FinalToken.Web", "FinalToken.Worker", "FinalToken.FakeCli"):
|
||||
shutil.copytree(ROOT / "artifacts/bin" / project / "Release/net10.0", self.path / project)
|
||||
self.json(self.path / "server.json", {
|
||||
"accounts": [{"id": "claude", "provider": "Claude", "label": "Personal Claude", "expectedEmail": "[email protected]"},
|
||||
{"id": "codex", "provider": "Codex", "label": "Personal Codex", "expectedEmail": "[email protected]"}],
|
||||
"machines": [{"id": "a", "label": "Synthetic workstation", "osUser": getpass.getuser(),
|
||||
"profiles": [{"id": "main", "accountId": "claude"}, {"id": "code", "accountId": "codex"}]}]})
|
||||
fake = self.path / "FinalToken.FakeCli" / ("FinalToken.FakeCli.exe" if os.name == "nt" else "FinalToken.FakeCli")
|
||||
if not fake.exists():
|
||||
raise RuntimeError("Build FinalToken.slnx in Release before running this check")
|
||||
self.json(self.path / "worker.json", {"machineId": "a", "serverUrl": self.url,
|
||||
"stateDirectory": str(self.path / "worker-state"), "profiles": [
|
||||
{"id": "main", "provider": "Claude", "expectedEmail": "[email protected]", "configDirectory": str(self.claude), "dataDirectory": str(self.path / "claude-data"), "cliPath": str(fake)},
|
||||
{"id": "code", "provider": "Codex", "expectedEmail": "[email protected]", "configDirectory": str(self.codex), "dataDirectory": str(self.path / "codex-data"), "cliPath": str(fake)}]})
|
||||
# Handwritten transcript/rollout metadata. No real messages or credentials.
|
||||
projects = self.claude / "projects" / "fixture"
|
||||
projects.mkdir(parents=True)
|
||||
transcript = {"type": "assistant", "timestamp": self.now.isoformat(), "requestId": "req-fixture",
|
||||
"message": {"id": "msg-fixture", "model": "claude-opus-4-6", "usage": {"input_tokens": 100, "output_tokens": 20}}}
|
||||
(projects / "fixture.jsonl").write_text(json.dumps(transcript) + "\n" + json.dumps(transcript) + "\n", encoding="utf-8")
|
||||
sessions = self.codex / "sessions"
|
||||
sessions.mkdir()
|
||||
rows = [{"type": "session_meta", "payload": {"id": "fixture-session"}},
|
||||
{"type": "turn_context", "payload": {"model": "gpt-5.4"}},
|
||||
{"type": "event_msg", "timestamp": self.now.isoformat(), "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 100, "output_tokens": 20, "total_tokens": 120}}}}]
|
||||
(sessions / "rollout-fixture.jsonl").write_text("\n".join(map(json.dumps, rows)) + "\n", encoding="utf-8")
|
||||
env = os.environ.copy()
|
||||
env.update(FINALTOKEN_SERVER_CONFIG=str(self.path / "server.json"), FINALTOKEN_SERVER_DATA=str(self.path / "server-data"),
|
||||
FINALTOKEN_DASHBOARD_KEY=KEY, FINALTOKEN_MACHINE_a=WORKER_KEY, FINALTOKEN_PUBLIC_ORIGIN=self.url, ASPNETCORE_URLS=self.url)
|
||||
self.spawn(["dotnet", str(self.path / "FinalToken.Web/FinalToken.Web.dll")], env, ROOT / "src/FinalToken.Web")
|
||||
wait_for(self.ready)
|
||||
worker_env = os.environ.copy()
|
||||
# Synthetic CLI must not inherit either real profile override from the host.
|
||||
worker_env.pop("CLAUDE_CONFIG_DIR", None)
|
||||
worker_env.pop("CODEX_HOME", None)
|
||||
worker_env["FINALTOKEN_WORKER_KEY"] = WORKER_KEY
|
||||
self.spawn(["dotnet", str(self.path / "FinalToken.Worker/finaltoken-worker.dll"), str(self.path / "worker.json")], worker_env, ROOT)
|
||||
|
||||
@staticmethod
|
||||
def json(path, value):
|
||||
path.write_text(json.dumps(value), encoding="utf-8")
|
||||
|
||||
def spawn(self, command, env, cwd):
|
||||
self.processes.append(subprocess.Popen(command, env=env, cwd=cwd, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
|
||||
start_new_session=os.name != "nt"))
|
||||
|
||||
def ready(self):
|
||||
try:
|
||||
return urllib.request.urlopen(self.url, timeout=1).status == 200
|
||||
except (OSError, urllib.error.URLError):
|
||||
return False
|
||||
|
||||
def call(self, path, body=None, opener=None, headers=None):
|
||||
h = {"Content-Type": "application/json", "X-FinalToken": "1"}
|
||||
if self.csrf:
|
||||
h["X-CSRF"] = self.csrf
|
||||
h.update(headers or {})
|
||||
request = urllib.request.Request(self.url + path, data=None if body is None else json.dumps(body).encode(), headers=h)
|
||||
with (opener or self.browser).open(request, timeout=10) as response:
|
||||
data = response.read()
|
||||
return json.loads(data) if data else None
|
||||
|
||||
def sign_in(self):
|
||||
self.csrf = self.call("/session", {"key": KEY})["csrf"]
|
||||
|
||||
def online(self):
|
||||
return self.call("/api/dashboard")["machines"][0]["online"]
|
||||
|
||||
def login_state(self, login, state):
|
||||
view = self.call("/api/logins/" + login["id"])
|
||||
return view if view["state"] == state else None
|
||||
|
||||
def authorize(self):
|
||||
self.sign_in()
|
||||
wait_for(self.online)
|
||||
login = self.call("/api/logins", {"machineId": "a", "profileId": "main"})
|
||||
wait_for(lambda: self.login_state(login, "WaitingForCode"))
|
||||
self.call(f"/api/logins/{login['id']}/response", {"response": "fixture-code#fixture-state"})
|
||||
wait_for(lambda: self.login_state(login, "Succeeded"))
|
||||
device = self.call("/api/logins", {"machineId": "a", "profileId": "code"})
|
||||
wait_for(lambda: self.login_state(device, "WaitingForBrowser"))
|
||||
(self.codex / "authorize-device").touch()
|
||||
wait_for(lambda: self.login_state(device, "Succeeded"))
|
||||
return login, device
|
||||
|
||||
def close(self):
|
||||
for process in reversed(self.processes):
|
||||
if process.poll() is None:
|
||||
if os.name == "nt":
|
||||
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
|
||||
else:
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
process.wait(timeout=10)
|
||||
self.temp.cleanup()
|
||||
|
||||
|
||||
class WebIntegration(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.fixture = Fixture()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.fixture.close()
|
||||
|
||||
def test_end_to_end(self):
|
||||
f = self.fixture
|
||||
anonymous = urllib.request.build_opener()
|
||||
with self.assertRaises(urllib.error.HTTPError) as error:
|
||||
f.call("/api/dashboard", opener=anonymous)
|
||||
self.assertEqual(401, error.exception.code)
|
||||
f.sign_in()
|
||||
with self.assertRaises(urllib.error.HTTPError) as error:
|
||||
f.call("/api/logins", {"machineId": "a", "profileId": "main"}, headers={"X-CSRF": "wrong"})
|
||||
self.assertEqual(403, error.exception.code)
|
||||
with self.assertRaises(urllib.error.HTTPError) as error:
|
||||
f.call("/api/logins", {}, headers={"Origin": "https://evil.test"})
|
||||
self.assertEqual(403, error.exception.code)
|
||||
with self.assertRaises(urllib.error.HTTPError) as error:
|
||||
f.call("/worker/report", {}, opener=anonymous)
|
||||
self.assertEqual(401, error.exception.code)
|
||||
login, device = f.authorize()
|
||||
self.assertEqual("[email protected]", f.login_state(login, "Succeeded")["email"])
|
||||
self.assertIsNone(f.login_state(login, "Succeeded")["url"])
|
||||
wait_for(lambda: all(a["total"]["total"] == 120 for a in f.call("/api/dashboard")["accounts"]))
|
||||
dashboard = f.call("/api/dashboard")
|
||||
codex = next(a for a in dashboard["accounts"] if a["account"]["id"] == "codex")
|
||||
self.assertEqual(65, codex["windows"][0]["window"]["usedPercent"])
|
||||
self.assertGreater(codex["windows"][0]["useAtReset"], 100)
|
||||
other = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
|
||||
f.call("/session", {"key": KEY}, opener=other)
|
||||
with self.assertRaises(urllib.error.HTTPError) as error:
|
||||
f.call("/api/logins/" + login["id"], opener=other)
|
||||
self.assertEqual(404, error.exception.code)
|
||||
for path in (f.path / "server-data").rglob("*"):
|
||||
if path.is_file() and path.suffix == ".json":
|
||||
data = path.read_bytes()
|
||||
self.assertNotIn(b"fixture-code", data)
|
||||
self.assertNotIn(b"fixture-state", data)
|
||||
self.assertNotIn(b"ABCD-12345", data)
|
||||
# Real child process cancellation, then wrong-account verification.
|
||||
(f.codex / "authorize-device").unlink()
|
||||
cancel = f.call("/api/logins", {"machineId": "a", "profileId": "code"})
|
||||
wait_for(lambda: f.login_state(cancel, "WaitingForBrowser"))
|
||||
f.call(f"/api/logins/{cancel['id']}/cancel", {})
|
||||
wait_for(lambda: f.login_state(cancel, "Cancelled"))
|
||||
mismatch = f.call("/api/logins", {"machineId": "a", "profileId": "main"})
|
||||
wait_for(lambda: f.login_state(mismatch, "WaitingForCode"))
|
||||
f.call(f"/api/logins/{mismatch['id']}/response", {"response": "wrong-code#fixture-state"})
|
||||
wait_for(lambda: f.login_state(mismatch, "AccountMismatch"))
|
||||
(f.claude / "overflow-login").touch()
|
||||
overflow = f.call("/api/logins", {"machineId": "a", "profileId": "main"})
|
||||
wait_for(lambda: f.login_state(overflow, "Failed"), timeout=15)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--serve-fixture", action="store_true", help="Keep synthetic server/worker running for local visual QA")
|
||||
args = parser.parse_args()
|
||||
if args.serve_fixture:
|
||||
fixture = Fixture(port=5187)
|
||||
try:
|
||||
fixture.authorize()
|
||||
print("Synthetic dashboard ready at " + fixture.url, flush=True)
|
||||
print("Access key: " + KEY, flush=True)
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
fixture.close()
|
||||
else:
|
||||
unittest.main(argv=[__file__])
|
||||
Reference in New Issue
Block a user