core: publish self-hosted weekly dashboard and Proxmox deployment #20
@@ -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" />
|
||||
|
||||
+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
|
||||
|
||||
@@ -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": "you@example.com", "timeZone": "Europe/Berlin" },
|
||||
{ "id": "personal-codex", "provider": "Codex", "label": "Personal Codex", "expectedEmail": "you@example.com", "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": "you@example.com", "configDirectory": "<absolute Claude config directory>", "dataDirectory": "<absolute existing FinalToken data directory>" },
|
||||
{ "id": "codex", "provider": "Codex", "expectedEmail": "you@example.com", "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 = profiles.SingleOrDefault(p => p.Machine == account.LegacyMachine && p.Profile.Id == account.LegacyProfile).Profile;
|
||||
if (legacy is null) warnings.Add("Designated legacy history source has not reported.");
|
||||
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,200 @@
|
||||
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);
|
||||
}
|
||||
[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,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