@chroxy/server 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- package/src/ws-server.js +2866 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// #5665 — monthly programmatic-credit budget meter.
|
|
2
|
+
//
|
|
3
|
+
// As of 2026-06-15, `claude -p` (CLI) and the Agent SDK draw from a separate
|
|
4
|
+
// monthly programmatic-usage credit pool (billed at API rates, refreshing
|
|
5
|
+
// monthly with no rollover). This module tracks the *chroxy-observed* spend
|
|
6
|
+
// against that pool: the sum of `programmatic-credit`-billed session cost this
|
|
7
|
+
// daemon has seen in the current UTC calendar month, versus a configured cap.
|
|
8
|
+
//
|
|
9
|
+
// IMPORTANT — this is chroxy-observed, NOT an authoritative Anthropic balance.
|
|
10
|
+
// It only counts sessions THIS daemon ran; sessions on other machines or
|
|
11
|
+
// outside chroxy are invisible to it. The dashboard surfaces that caveat.
|
|
12
|
+
//
|
|
13
|
+
// The cap is configured (chroxy cannot detect the user's plan tier):
|
|
14
|
+
// billing.creditTier pro | max5x | max20x -> $20 / $100 / $200
|
|
15
|
+
// billing.monthlyCreditBudgetUsd raw USD override (wins over the tier preset)
|
|
16
|
+
// billing.budgetWarningPercent warn threshold (default 80)
|
|
17
|
+
|
|
18
|
+
import { readFileSync, writeFileSync, renameSync, mkdirSync, rmSync } from 'node:fs'
|
|
19
|
+
import { dirname } from 'node:path'
|
|
20
|
+
|
|
21
|
+
/** Per-tier monthly programmatic-credit caps (USD), per Anthropic's 2026-06-15 change. */
|
|
22
|
+
export const CREDIT_TIER_BUDGETS_USD = Object.freeze({
|
|
23
|
+
pro: 20,
|
|
24
|
+
max5x: 100,
|
|
25
|
+
max20x: 200,
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
export const DEFAULT_BUDGET_WARNING_PERCENT = 80
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* UTC calendar-month key, "YYYY-MM". The reset boundary matches the era
|
|
32
|
+
* boundary's timezone semantics (billing-class.js uses Date.UTC).
|
|
33
|
+
*/
|
|
34
|
+
export function monthKeyUtc(now = Date.now()) {
|
|
35
|
+
const d = new Date(now)
|
|
36
|
+
const y = d.getUTCFullYear()
|
|
37
|
+
const m = d.getUTCMonth() + 1
|
|
38
|
+
return `${y}-${m < 10 ? '0' : ''}${m}`
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Resolve the configured monthly cap in USD. The raw override wins; otherwise
|
|
43
|
+
* a recognised tier preset; otherwise null — "no cap configured", in which case
|
|
44
|
+
* the meter reports spend with no percentage/warning (chroxy can't guess it).
|
|
45
|
+
*/
|
|
46
|
+
export function resolveMonthlyCreditBudgetUsd(billingConfig = {}) {
|
|
47
|
+
const override = billingConfig?.monthlyCreditBudgetUsd
|
|
48
|
+
// Require a POSITIVE override. `0` is treated as "no override" (fall through
|
|
49
|
+
// to the tier preset / null) rather than a real $0 cap — a $0 cap would
|
|
50
|
+
// render a permanently-"exceeded" $0/$0 meter the moment any session billed.
|
|
51
|
+
if (Number.isFinite(override) && override > 0) return override
|
|
52
|
+
const tier = billingConfig?.creditTier
|
|
53
|
+
if (typeof tier === 'string' && Object.prototype.hasOwnProperty.call(CREDIT_TIER_BUDGETS_USD, tier)) {
|
|
54
|
+
return CREDIT_TIER_BUDGETS_USD[tier]
|
|
55
|
+
}
|
|
56
|
+
return null
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Resolve the warning threshold percent (1–100), defaulting to 80. */
|
|
60
|
+
export function resolveWarningPercent(billingConfig = {}) {
|
|
61
|
+
const p = billingConfig?.budgetWarningPercent
|
|
62
|
+
if (Number.isFinite(p) && p > 0 && p <= 100) return p
|
|
63
|
+
return DEFAULT_BUDGET_WARNING_PERCENT
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Tracks chroxy-observed programmatic-credit spend for the current UTC month
|
|
68
|
+
* against a configured cap. The cap/warning come from config (stable per
|
|
69
|
+
* process); only the running spend total is persisted, so changing tier
|
|
70
|
+
* mid-month re-evaluates the percentage against the new cap on restart.
|
|
71
|
+
*/
|
|
72
|
+
export class MonthlyProgrammaticBudgetManager {
|
|
73
|
+
/**
|
|
74
|
+
* @param {object} opts
|
|
75
|
+
* @param {object} [opts.billingConfig] the `billing` config block
|
|
76
|
+
* @param {string|null} [opts.statePath] JSON file for the running total;
|
|
77
|
+
* null keeps it in-memory only (tests / no-persist). Production points it
|
|
78
|
+
* next to the session-state file so a temp stateFilePath redirects it out
|
|
79
|
+
* of the real ~/.chroxy (test-sandbox safe).
|
|
80
|
+
* @param {number} [opts.now] injected clock for determinism
|
|
81
|
+
*/
|
|
82
|
+
constructor({ billingConfig = {}, statePath = null, now = Date.now() } = {}) {
|
|
83
|
+
this._budgetUsd = resolveMonthlyCreditBudgetUsd(billingConfig)
|
|
84
|
+
this._warningPercent = resolveWarningPercent(billingConfig)
|
|
85
|
+
this._statePath = statePath || null
|
|
86
|
+
this._state = { month: monthKeyUtc(now), spentUsd: 0, turnsBilled: 0, warnNotified: false, exceededNotified: false }
|
|
87
|
+
this._load()
|
|
88
|
+
this._rollIfNeeded(now)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** True iff a cap is configured (tier or override). */
|
|
92
|
+
get hasBudget() {
|
|
93
|
+
return this._budgetUsd != null
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
_load() {
|
|
97
|
+
if (!this._statePath) return
|
|
98
|
+
try {
|
|
99
|
+
const raw = JSON.parse(readFileSync(this._statePath, 'utf8'))
|
|
100
|
+
if (raw && typeof raw === 'object' && typeof raw.month === 'string') {
|
|
101
|
+
this._state = {
|
|
102
|
+
month: raw.month,
|
|
103
|
+
spentUsd: Number.isFinite(raw.spentUsd) ? raw.spentUsd : 0,
|
|
104
|
+
turnsBilled: Number.isFinite(raw.turnsBilled) && raw.turnsBilled >= 0 ? raw.turnsBilled : 0,
|
|
105
|
+
warnNotified: raw.warnNotified === true,
|
|
106
|
+
exceededNotified: raw.exceededNotified === true,
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
} catch {
|
|
110
|
+
// Missing / malformed file → start fresh (already initialised in ctor).
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
_save() {
|
|
115
|
+
if (!this._statePath) return
|
|
116
|
+
const tmp = `${this._statePath}.tmp`
|
|
117
|
+
try {
|
|
118
|
+
mkdirSync(dirname(this._statePath), { recursive: true })
|
|
119
|
+
writeFileSync(tmp, JSON.stringify(this._state), 'utf8')
|
|
120
|
+
renameSync(tmp, this._statePath)
|
|
121
|
+
} catch {
|
|
122
|
+
// Persistence is best-effort; a write failure must not break the turn.
|
|
123
|
+
// Clean up the temp file so a failed rename can't orphan a `.tmp` next
|
|
124
|
+
// to the state file (which would also block the atomic-write contract on
|
|
125
|
+
// the next save). Best-effort — ignore if it's already gone.
|
|
126
|
+
try { rmSync(tmp, { force: true }) } catch { /* ignore */ }
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Reset the running total when the UTC month rolls over. */
|
|
131
|
+
_rollIfNeeded(now) {
|
|
132
|
+
const key = monthKeyUtc(now)
|
|
133
|
+
if (this._state.month !== key) {
|
|
134
|
+
this._state = { month: key, spentUsd: 0, turnsBilled: 0, warnNotified: false, exceededNotified: false }
|
|
135
|
+
this._save()
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Record a programmatic-credit turn's cost. Callers MUST gate on
|
|
141
|
+
* billingClass === 'programmatic-credit' — this manager does not re-check it.
|
|
142
|
+
* @returns {{ status: object, justWarned: boolean, justExceeded: boolean }}
|
|
143
|
+
*/
|
|
144
|
+
recordSpend(costUsd, now = Date.now()) {
|
|
145
|
+
this._rollIfNeeded(now)
|
|
146
|
+
if (Number.isFinite(costUsd)) {
|
|
147
|
+
// Floor the running total at 0: a refund/credit turn (#4099, signed cost)
|
|
148
|
+
// reduces this month's spend but can never carry a NEGATIVE balance into
|
|
149
|
+
// later turns (which would silently mask subsequent real spend). "Spend
|
|
150
|
+
// this month" is a non-negative quantity.
|
|
151
|
+
this._state.spentUsd = Math.max(0, this._state.spentUsd + costUsd)
|
|
152
|
+
this._state.turnsBilled += 1
|
|
153
|
+
}
|
|
154
|
+
const status = this.getStatus(now)
|
|
155
|
+
let justWarned = false
|
|
156
|
+
let justExceeded = false
|
|
157
|
+
if (status.warning && !this._state.warnNotified) {
|
|
158
|
+
this._state.warnNotified = true
|
|
159
|
+
justWarned = true
|
|
160
|
+
}
|
|
161
|
+
if (status.exceeded && !this._state.exceededNotified) {
|
|
162
|
+
this._state.exceededNotified = true
|
|
163
|
+
justExceeded = true
|
|
164
|
+
}
|
|
165
|
+
this._save()
|
|
166
|
+
return { status, justWarned, justExceeded }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Current meter snapshot. `spentUsd` floors at 0 (a refund turn can drive the
|
|
171
|
+
* raw total negative; a negative pool reading would be nonsense to surface).
|
|
172
|
+
*/
|
|
173
|
+
getStatus(now = Date.now()) {
|
|
174
|
+
this._rollIfNeeded(now)
|
|
175
|
+
const spentUsd = Math.max(0, this._state.spentUsd)
|
|
176
|
+
const budgetUsd = this._budgetUsd
|
|
177
|
+
const percent = budgetUsd != null && budgetUsd > 0 ? (spentUsd / budgetUsd) * 100 : null
|
|
178
|
+
const warning = percent != null && percent >= this._warningPercent
|
|
179
|
+
const exceeded = budgetUsd != null && spentUsd >= budgetUsd
|
|
180
|
+
return {
|
|
181
|
+
month: this._state.month,
|
|
182
|
+
spentUsd,
|
|
183
|
+
turnsBilled: this._state.turnsBilled,
|
|
184
|
+
budgetUsd,
|
|
185
|
+
warningPercent: this._warningPercent,
|
|
186
|
+
percent,
|
|
187
|
+
warning,
|
|
188
|
+
exceeded,
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// billing-canary-monitor.js — live wiring for the billing canary (#5821).
|
|
2
|
+
//
|
|
3
|
+
// Runs the pure checks in doctor-billing.js inside the running daemon and
|
|
4
|
+
// broadcasts a `billing_canary` message to clients when the result changes, so
|
|
5
|
+
// the dashboard can surface a banner during the 2026-06-15 programmatic-credit
|
|
6
|
+
// window. The same snapshot seeds `auth_ok` (via `current()`) so a freshly
|
|
7
|
+
// connected client renders the banner immediately instead of waiting for the
|
|
8
|
+
// next broadcast.
|
|
9
|
+
//
|
|
10
|
+
// Scope: this monitor always runs the two checks that need only local daemon
|
|
11
|
+
// state — `detectSilentMeteredDefault` (the live signal: a programmatic config
|
|
12
|
+
// default without a key) and `detectBillingReclassification` (a zero-false-positive
|
|
13
|
+
// tripwire, dormant today because claude-tui reports `cost: null` so its
|
|
14
|
+
// cumulative costUsd stays 0). The datacenter-egress check (#5828) is OPT-IN:
|
|
15
|
+
// it needs an outbound public-IP lookup, so it only runs when the caller wires a
|
|
16
|
+
// `resolveEgressIp` resolver (gated on `config.billing.egressCheck`). When a
|
|
17
|
+
// warning set appears it can also fire a `notify` callback (push notification).
|
|
18
|
+
import { runBillingCanary } from './doctor-billing.js'
|
|
19
|
+
import { billingClassForProvider } from './billing-class.js'
|
|
20
|
+
import { DEFAULT_PROVIDER } from '@chroxy/protocol'
|
|
21
|
+
|
|
22
|
+
const DEFAULT_INTERVAL_MS = 10 * 60 * 1000 // 10 minutes
|
|
23
|
+
|
|
24
|
+
export class BillingCanaryMonitor {
|
|
25
|
+
/**
|
|
26
|
+
* @param {object} opts
|
|
27
|
+
* @param {() => Array} opts.getSessions - returns the live session list
|
|
28
|
+
* (SessionManager.listSessions() shape: { sessionId, provider, cumulativeUsage:{costUsd} }).
|
|
29
|
+
* @param {() => string} opts.getDefaultProvider - resolved default provider id.
|
|
30
|
+
* @param {() => boolean} [opts.getApiKeyAuth] - whether the default would auth via an
|
|
31
|
+
* explicit ANTHROPIC_API_KEY and thus bill raw API (api-key), suppressing the
|
|
32
|
+
* silent-metered warning. NOTE: billing-class's apiKeyAuth refinement nominally
|
|
33
|
+
* covers both claude-cli and claude-sdk, but only claude-sdk honours an env key —
|
|
34
|
+
* claude-cli strips ANTHROPIC_API_KEY before spawn, so it still meters with a key
|
|
35
|
+
* set. The caller (server-cli) reflects that by setting this true ONLY for claude-sdk.
|
|
36
|
+
* @param {(message: object) => void} opts.broadcast - global client broadcast.
|
|
37
|
+
* @param {number} [opts.intervalMs] - recompute cadence (default 10 min).
|
|
38
|
+
* @param {() => number} [opts.nowFn] - injectable clock for tests.
|
|
39
|
+
* @param {{warn?: Function}} [opts.logger]
|
|
40
|
+
* @param {() => Promise<string|null>} [opts.resolveEgressIp] - #5828: when provided,
|
|
41
|
+
* datacenter-egress detection is ON. The monitor resolves the public IP out-of-band
|
|
42
|
+
* (best-effort, cached) and folds it into the canary. Absent = egress check OFF
|
|
43
|
+
* (default) — the daemon makes no outbound lookup. The CALLER only provides this when
|
|
44
|
+
* config.billing.egressCheck is true, so providing it IS the opt-in.
|
|
45
|
+
* @param {() => string[]} [opts.getDatacenterPrefixes] - extra IPv4 prefixes
|
|
46
|
+
* (config.billing.datacenterPrefixes) merged into the egress classifier.
|
|
47
|
+
* @param {(warnings: Array) => void} [opts.notify] - #5828: fired when the warning
|
|
48
|
+
* SET changes (e.g. push notification). Called with the non-empty warning array
|
|
49
|
+
* for each distinct alert state, and once with an EMPTY array on the
|
|
50
|
+
* non-empty→empty (all-clear) transition so a sink can repaint "resolved". Not
|
|
51
|
+
* fired on an unchanged re-broadcast, nor on a clear that follows startup.
|
|
52
|
+
*/
|
|
53
|
+
constructor({ getSessions, getDefaultProvider, getApiKeyAuth, broadcast, intervalMs = DEFAULT_INTERVAL_MS, nowFn = Date.now, logger, resolveEgressIp, getDatacenterPrefixes, notify } = {}) {
|
|
54
|
+
this._getSessions = getSessions || (() => [])
|
|
55
|
+
this._getDefaultProvider = getDefaultProvider || (() => DEFAULT_PROVIDER)
|
|
56
|
+
this._getApiKeyAuth = getApiKeyAuth || (() => false)
|
|
57
|
+
this._broadcast = broadcast || (() => {})
|
|
58
|
+
this._intervalMs = intervalMs
|
|
59
|
+
this._now = nowFn
|
|
60
|
+
this._log = logger
|
|
61
|
+
this._resolveEgressIp = typeof resolveEgressIp === 'function' ? resolveEgressIp : null
|
|
62
|
+
this._getDatacenterPrefixes = getDatacenterPrefixes || (() => [])
|
|
63
|
+
this._notify = typeof notify === 'function' ? notify : null
|
|
64
|
+
this._timer = null
|
|
65
|
+
this._last = null // last computed snapshot
|
|
66
|
+
this._lastKey = null // JSON of the last snapshot, for broadcast change-detection
|
|
67
|
+
this._lastWarnKey = null // signature of the last warning SET, for notify change-detection
|
|
68
|
+
this._egressIp = null // cached public egress IP (null until resolved / when disabled)
|
|
69
|
+
this._stopped = false // true after stop(); guards an in-flight egress tick from refreshing
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Compute the current billing-canary snapshot. Pure — no broadcast, no state
|
|
74
|
+
* mutation. Maps the live session list to the {id, provider, totalCostUsd}
|
|
75
|
+
* shape the canary expects.
|
|
76
|
+
* @returns {{eraStarted:boolean, defaultProvider:string, defaultBillingClass:string, warnings:Array}}
|
|
77
|
+
*/
|
|
78
|
+
compute() {
|
|
79
|
+
const now = this._now()
|
|
80
|
+
const defaultProvider = this._getDefaultProvider() || DEFAULT_PROVIDER
|
|
81
|
+
const apiKeyAuth = Boolean(this._getApiKeyAuth())
|
|
82
|
+
const sessions = (this._getSessions() || []).map((s) => ({
|
|
83
|
+
id: s.sessionId || s.id,
|
|
84
|
+
provider: s.provider,
|
|
85
|
+
totalCostUsd: s && s.cumulativeUsage ? s.cumulativeUsage.costUsd : undefined,
|
|
86
|
+
}))
|
|
87
|
+
// egressIp is the cached value from the out-of-band resolver — null when the
|
|
88
|
+
// egress check is OFF (default) or not yet resolved, so no egress warning.
|
|
89
|
+
const datacenterPrefixes = this._getDatacenterPrefixes() || []
|
|
90
|
+
const { eraStarted, warnings } = runBillingCanary({ sessions, defaultProvider, now, apiKeyAuth, egressIp: this._egressIp, datacenterPrefixes })
|
|
91
|
+
const defaultBillingClass = billingClassForProvider(defaultProvider, now, { apiKeyAuth })
|
|
92
|
+
return { eraStarted, defaultProvider, defaultBillingClass, warnings }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Recompute and broadcast a `billing_canary` message IF the snapshot changed
|
|
97
|
+
* (including a transition back to all-clear, so the client clears its banner).
|
|
98
|
+
* Always updates `current()`.
|
|
99
|
+
* @returns {object} the fresh snapshot
|
|
100
|
+
*/
|
|
101
|
+
refresh() {
|
|
102
|
+
const snapshot = this.compute()
|
|
103
|
+
const key = JSON.stringify(snapshot)
|
|
104
|
+
this._last = snapshot
|
|
105
|
+
if (key !== this._lastKey) {
|
|
106
|
+
this._lastKey = key
|
|
107
|
+
try {
|
|
108
|
+
this._broadcast({ type: 'billing_canary', ...snapshot })
|
|
109
|
+
} catch (err) {
|
|
110
|
+
this._log?.warn?.(`billing-canary broadcast failed: ${String(err?.message || err)}`)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
// #5828: fire `notify` (e.g. push) when the warning SET changes — once per
|
|
114
|
+
// distinct non-empty state, AND once on the non-empty→empty (all-clear)
|
|
115
|
+
// transition with an empty array, so a downstream sink can repaint a
|
|
116
|
+
// "resolved" state. NOT fired on an unchanged re-broadcast, and NOT fired on
|
|
117
|
+
// a clear that follows startup (never warned → no spurious all-clear). The
|
|
118
|
+
// signature includes the message so a meaning change with the same code
|
|
119
|
+
// re-notifies (e.g. DATACENTER_EGRESS with a new egress IP, or
|
|
120
|
+
// SILENT_METERED_DEFAULT for a different provider) — mirrors the dashboard
|
|
121
|
+
// dismissal signature.
|
|
122
|
+
const warnKey = snapshot.warnings
|
|
123
|
+
.map((w) => `${w.code} ${w.sessionId ?? ''} ${w.costUsd ?? ''} ${w.message ?? ''}`)
|
|
124
|
+
.sort()
|
|
125
|
+
.join('|')
|
|
126
|
+
if (warnKey !== this._lastWarnKey) {
|
|
127
|
+
const prevKey = this._lastWarnKey // null on startup; a non-empty signature otherwise
|
|
128
|
+
this._lastWarnKey = warnKey
|
|
129
|
+
if (this._notify) {
|
|
130
|
+
try {
|
|
131
|
+
if (snapshot.warnings.length > 0) {
|
|
132
|
+
this._notify(snapshot.warnings)
|
|
133
|
+
} else if (prevKey) {
|
|
134
|
+
// Transition from a non-empty set to all-clear. prevKey is null only
|
|
135
|
+
// at startup (never warned), so a fresh clean daemon never fires a
|
|
136
|
+
// spurious all-clear; prevKey can never be '' here (that would equal
|
|
137
|
+
// the current empty warnKey and skip this branch).
|
|
138
|
+
this._notify([])
|
|
139
|
+
}
|
|
140
|
+
} catch (err) {
|
|
141
|
+
this._log?.warn?.(`billing-canary notify failed: ${String(err?.message || err)}`)
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return snapshot
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* One recompute cycle: refresh the cached egress IP first (best-effort, only
|
|
150
|
+
* when the egress check is enabled), then refresh the snapshot. Async because
|
|
151
|
+
* the egress lookup is a network call; never rejects (fail-open).
|
|
152
|
+
*/
|
|
153
|
+
async _tick() {
|
|
154
|
+
if (this._resolveEgressIp) {
|
|
155
|
+
try {
|
|
156
|
+
this._egressIp = await this._resolveEgressIp()
|
|
157
|
+
} catch {
|
|
158
|
+
this._egressIp = null
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
// The egress lookup is async (up to ~5s); if stop() landed while it was in
|
|
162
|
+
// flight, skip the trailing refresh so a shut-down monitor doesn't broadcast.
|
|
163
|
+
// `_stopped` (not `_timer`) is the signal — `_timer` is briefly null during
|
|
164
|
+
// start()'s first tick, before setInterval runs.
|
|
165
|
+
if (this._stopped) return
|
|
166
|
+
try {
|
|
167
|
+
this.refresh()
|
|
168
|
+
} catch (err) {
|
|
169
|
+
this._log?.warn?.(`billing-canary refresh failed: ${String(err?.message || err)}`)
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The latest snapshot, for seeding auth_ok. Computes once if never refreshed. */
|
|
174
|
+
current() {
|
|
175
|
+
return this._last || this.compute()
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Start the periodic recompute. Initial refresh runs immediately. */
|
|
179
|
+
start() {
|
|
180
|
+
this._stopped = false
|
|
181
|
+
// Immediate synchronous refresh so current() is populated for the auth_ok
|
|
182
|
+
// seed right away (egress, if enabled, folds in on the async tick below).
|
|
183
|
+
this.refresh()
|
|
184
|
+
// Kick the first egress-aware tick (no-op extra refresh when egress is off).
|
|
185
|
+
this._tick().catch(() => {})
|
|
186
|
+
this._timer = setInterval(() => {
|
|
187
|
+
this._tick().catch((err) => this._log?.warn?.(`billing-canary tick failed: ${String(err?.message || err)}`))
|
|
188
|
+
}, this._intervalMs)
|
|
189
|
+
// Don't keep the event loop alive for this; clean shutdown calls stop() and
|
|
190
|
+
// the leaked-timer test guard (--test-force-exit) shouldn't trip on it.
|
|
191
|
+
if (this._timer && typeof this._timer.unref === 'function') this._timer.unref()
|
|
192
|
+
return this
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Stop the periodic recompute. Idempotent. */
|
|
196
|
+
stop() {
|
|
197
|
+
this._stopped = true
|
|
198
|
+
if (this._timer) {
|
|
199
|
+
clearInterval(this._timer)
|
|
200
|
+
this._timer = null
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Era-aware billing classification (#5630 / #5629).
|
|
3
|
+
*
|
|
4
|
+
* Chroxy bills Claude usage three different ways depending on the provider
|
|
5
|
+
* and (for the programmatic providers) the date. Historically the dashboard
|
|
6
|
+
* labelled every dollar figure "Cost (BYOK)" — wrong for subscription and
|
|
7
|
+
* programmatic-credit sessions (#5630) — and the provider copy still said
|
|
8
|
+
* "subscription" for claude-cli / claude-sdk even though Anthropic moves
|
|
9
|
+
* those onto a metered programmatic-credit pool on 2026-06-15 (#5629).
|
|
10
|
+
*
|
|
11
|
+
* This module is the single source of truth for "which billing class is
|
|
12
|
+
* this session/provider in right now?" Every provider `resolveAuth()` and the
|
|
13
|
+
* session-list builder route through it so the wire shape (`auth.billingClass`,
|
|
14
|
+
* per-session `billingClass`) and the human copy (`detail`) stay consistent.
|
|
15
|
+
*
|
|
16
|
+
* Three classes:
|
|
17
|
+
* - api-key — your own ANTHROPIC_API_KEY (claude-byok, docker-byok)
|
|
18
|
+
* AND every non-Claude provider (codex/gemini/deepseek/
|
|
19
|
+
* ollama/anthropic-compatible). Real per-token dollar
|
|
20
|
+
* spend. Era-independent.
|
|
21
|
+
* - subscription — flat Claude subscription billing (claude-tui,
|
|
22
|
+
* claude-channel). No per-turn dollar figure. Era-
|
|
23
|
+
* independent.
|
|
24
|
+
* - programmatic-credit — host claude-cli / claude-sdk when auth is the
|
|
25
|
+
* OAuth/subscription pool. BEFORE 2026-06-15 these
|
|
26
|
+
* bill as flat `subscription`; ON/AFTER they draw from
|
|
27
|
+
* Anthropic's monthly metered programmatic-credit pool,
|
|
28
|
+
* so spend becomes a real dollar figure.
|
|
29
|
+
*
|
|
30
|
+
* Refinement: a claude-cli / claude-sdk session authed with an explicit
|
|
31
|
+
* ANTHROPIC_API_KEY (the raw-API branch in resolveAuth, source === 'env') is
|
|
32
|
+
* a real per-token API account, NOT the credit pool — it classifies as
|
|
33
|
+
* `api-key` in BOTH eras.
|
|
34
|
+
*
|
|
35
|
+
* docker-cli / docker-sdk are NOT in the programmatic set: they forward the
|
|
36
|
+
* host's ANTHROPIC_API_KEY into the container and have no OAuth fallback (the
|
|
37
|
+
* container has no ~/.claude state), so they always bill the raw API account
|
|
38
|
+
* (`api-key`), era-independent — the host's credit pool never applies inside
|
|
39
|
+
* the container.
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
export const BILLING_CLASSES = Object.freeze({
|
|
43
|
+
API_KEY: 'api-key',
|
|
44
|
+
SUBSCRIPTION: 'subscription',
|
|
45
|
+
PROGRAMMATIC_CREDIT: 'programmatic-credit',
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The instant the programmatic-credit era begins.
|
|
50
|
+
*
|
|
51
|
+
* 2026-06-15 00:00:00 UTC. `Date.UTC(2026, 5, 15)` — the month arg is
|
|
52
|
+
* 0-indexed, so `5` is June. We anchor to a UTC midnight boundary (NOT local
|
|
53
|
+
* time) deliberately: the cutover is a single global instant for every
|
|
54
|
+
* daemon regardless of the host's timezone, so a daemon in UTC-8 and one in
|
|
55
|
+
* UTC+9 flip at the same wall-clock moment in UTC rather than 17 hours apart.
|
|
56
|
+
* The dashboard mirrors this constant client-side (CreateSessionModal.tsx) —
|
|
57
|
+
* keep the two in sync if this ever moves.
|
|
58
|
+
*/
|
|
59
|
+
export const PROGRAMMATIC_CREDIT_ERA_START = Date.UTC(2026, 5, 15)
|
|
60
|
+
|
|
61
|
+
// Host providers whose OAuth/subscription auth flips from `subscription` to
|
|
62
|
+
// `programmatic-credit` at the era boundary. (When authed with an explicit
|
|
63
|
+
// API key, claude-cli / claude-sdk are reclassified to `api-key` by the
|
|
64
|
+
// caller via opts.apiKeyAuth — see billingClassForProvider.)
|
|
65
|
+
const PROGRAMMATIC_PROVIDERS = new Set([
|
|
66
|
+
'claude-cli',
|
|
67
|
+
'claude-sdk',
|
|
68
|
+
])
|
|
69
|
+
|
|
70
|
+
// Providers that always bill as a flat Claude subscription, era-independent.
|
|
71
|
+
const SUBSCRIPTION_PROVIDERS = new Set([
|
|
72
|
+
'claude-tui',
|
|
73
|
+
'claude-channel',
|
|
74
|
+
])
|
|
75
|
+
|
|
76
|
+
// Providers that always bill against your own key / per-token, era-independent.
|
|
77
|
+
// docker-cli / docker-sdk forward ANTHROPIC_API_KEY into the container with no
|
|
78
|
+
// OAuth fallback, so they bill the raw API account just like BYOK.
|
|
79
|
+
const API_KEY_PROVIDERS = new Set([
|
|
80
|
+
'claude-byok',
|
|
81
|
+
'docker-byok',
|
|
82
|
+
'docker-cli',
|
|
83
|
+
'docker-sdk',
|
|
84
|
+
])
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Is the given instant on/after the programmatic-credit era boundary?
|
|
88
|
+
*
|
|
89
|
+
* The comparator takes an injectable `now` so tests pass explicit timestamps
|
|
90
|
+
* (no fake timers). It NEVER calls Date.now() internally except as the default
|
|
91
|
+
* argument value — pass a fixed timestamp to make the result deterministic.
|
|
92
|
+
*
|
|
93
|
+
* @param {number} [now] - Epoch millis. Defaults to Date.now() at call time.
|
|
94
|
+
* @returns {boolean}
|
|
95
|
+
*/
|
|
96
|
+
export function isProgrammaticCreditEra(now = Date.now()) {
|
|
97
|
+
return now >= PROGRAMMATIC_CREDIT_ERA_START
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Classify a provider into one of the three billing classes for a given
|
|
102
|
+
* instant.
|
|
103
|
+
*
|
|
104
|
+
* @param {string} providerType - Provider id (e.g. 'claude-cli', 'codex').
|
|
105
|
+
* @param {number} [now] - Epoch millis; defaults to Date.now(). Injectable
|
|
106
|
+
* for deterministic tests.
|
|
107
|
+
* @param {{ apiKeyAuth?: boolean }} [opts] - `apiKeyAuth: true` forces the
|
|
108
|
+
* `api-key` class for claude-sdk / claude-cli when the session is authed
|
|
109
|
+
* with an explicit ANTHROPIC_API_KEY (the raw-API branch in resolveAuth).
|
|
110
|
+
* @returns {'api-key'|'subscription'|'programmatic-credit'}
|
|
111
|
+
*/
|
|
112
|
+
export function billingClassForProvider(providerType, now = Date.now(), opts = {}) {
|
|
113
|
+
if (API_KEY_PROVIDERS.has(providerType)) return BILLING_CLASSES.API_KEY
|
|
114
|
+
if (SUBSCRIPTION_PROVIDERS.has(providerType)) return BILLING_CLASSES.SUBSCRIPTION
|
|
115
|
+
if (PROGRAMMATIC_PROVIDERS.has(providerType)) {
|
|
116
|
+
// claude-cli / claude-sdk authed via an explicit API key is a raw API
|
|
117
|
+
// account, not the credit pool — bill as api-key in both eras. (docker-cli
|
|
118
|
+
// / docker-sdk are already in API_KEY_PROVIDERS above and never reach here.)
|
|
119
|
+
if (opts.apiKeyAuth) return BILLING_CLASSES.API_KEY
|
|
120
|
+
return isProgrammaticCreditEra(now)
|
|
121
|
+
? BILLING_CLASSES.PROGRAMMATIC_CREDIT
|
|
122
|
+
: BILLING_CLASSES.SUBSCRIPTION
|
|
123
|
+
}
|
|
124
|
+
// Every other provider (codex/gemini/deepseek/ollama/anthropic-compatible,
|
|
125
|
+
// plus any future custom provider) is per-token api-key billing.
|
|
126
|
+
return BILLING_CLASSES.API_KEY
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Human-readable billing copy for a class. Used as the `detail` summary the
|
|
131
|
+
* dashboard renders under the provider picker and in the cost tooltips.
|
|
132
|
+
*
|
|
133
|
+
* @param {string} billingClass
|
|
134
|
+
* @param {{ providerLabel?: string }} [opts]
|
|
135
|
+
* @returns {string}
|
|
136
|
+
*/
|
|
137
|
+
export function billingDetailForClass(billingClass, { providerLabel } = {}) {
|
|
138
|
+
const who = providerLabel ? `${providerLabel}: ` : ''
|
|
139
|
+
switch (billingClass) {
|
|
140
|
+
case BILLING_CLASSES.API_KEY:
|
|
141
|
+
return `${who}Your own API key — per-token billing`
|
|
142
|
+
case BILLING_CLASSES.PROGRAMMATIC_CREDIT:
|
|
143
|
+
return `${who}Programmatic credit pool — monthly metered credits`
|
|
144
|
+
case BILLING_CLASSES.SUBSCRIPTION:
|
|
145
|
+
return `${who}Included (subscription) — no per-turn dollar charge`
|
|
146
|
+
default:
|
|
147
|
+
return who || 'Unknown billing class'
|
|
148
|
+
}
|
|
149
|
+
}
|
package/src/bind-host.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bind-address resolution for the chroxy server.
|
|
3
|
+
*
|
|
4
|
+
* Default behaviour (unchanged): with auth on and no explicit host, the
|
|
5
|
+
* server binds 0.0.0.0 (all interfaces) so the mobile app and LAN clients can
|
|
6
|
+
* reach it. `--no-auth` forces loopback. An explicit `config.host` (e.g.
|
|
7
|
+
* `--host 127.0.0.1` or `CHROXY_HOST=127.0.0.1`) binds that interface with
|
|
8
|
+
* auth STILL enabled — opt-in loopback-only for single-device setups that
|
|
9
|
+
* want defence-in-depth on top of the bearer token.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { isIPv4, isIPv6 } from 'node:net'
|
|
13
|
+
|
|
14
|
+
const LOOPBACK_HOSTS = new Set(['localhost', '::1'])
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* True for any loopback bind address (127.0.0.0/8, ::1, localhost).
|
|
18
|
+
* Hostname comparison is case-insensitive; the 127.* check applies only to
|
|
19
|
+
* valid IPv4 literals so a hostname like `127.example.com` is not mistaken
|
|
20
|
+
* for loopback.
|
|
21
|
+
* @param {*} host
|
|
22
|
+
* @returns {boolean}
|
|
23
|
+
*/
|
|
24
|
+
export function isLoopbackHost(host) {
|
|
25
|
+
if (typeof host !== 'string' || host.length === 0) return false
|
|
26
|
+
const h = host.toLowerCase()
|
|
27
|
+
if (LOOPBACK_HOSTS.has(h)) return true
|
|
28
|
+
// 127.0.0.0/8, but only for real IPv4 literals.
|
|
29
|
+
if (isIPv4(h) && h.startsWith('127.')) return true
|
|
30
|
+
// IPv4-mapped IPv6 loopback, e.g. ::ffff:127.0.0.1 or ::ffff:7f00:1.
|
|
31
|
+
if (h.startsWith('::ffff:127.') || h.startsWith('::ffff:7f')) return true
|
|
32
|
+
return false
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Format a host for use in a URL authority — bracketing IPv6 literals so
|
|
37
|
+
* `ws://[::1]:8765` is well-formed (a bare `ws://::1:8765` is not).
|
|
38
|
+
* @param {string} host
|
|
39
|
+
* @returns {string}
|
|
40
|
+
*/
|
|
41
|
+
export function formatHostForUrl(host) {
|
|
42
|
+
return isIPv6(host) ? `[${host}]` : host
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Resolve the address to pass to `httpServer.listen()`.
|
|
47
|
+
*
|
|
48
|
+
* @param {object} opts
|
|
49
|
+
* @param {boolean} opts.noAuth - `--no-auth` forces loopback.
|
|
50
|
+
* @param {string} [opts.host] - explicit `config.host` override.
|
|
51
|
+
* @returns {string|undefined} bind address, or `undefined` for the default
|
|
52
|
+
* 0.0.0.0 bind (so behaviour is unchanged when no host is configured).
|
|
53
|
+
*/
|
|
54
|
+
export function resolveBindHost({ noAuth, host } = {}) {
|
|
55
|
+
if (noAuth) return '127.0.0.1'
|
|
56
|
+
if (typeof host === 'string' && host.length > 0) return host
|
|
57
|
+
return undefined
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* #5356 (visibility layer): emit a single startup warning when the server is
|
|
62
|
+
* about to bind a non-loopback interface — the default `undefined` →
|
|
63
|
+
* 0.0.0.0 bind included. LAN peers can then reach the unauthenticated
|
|
64
|
+
* surface (`/health` fingerprint, dashboard assets, rate-limited auth and
|
|
65
|
+
* pairing attempts). This does NOT change any default — it only makes the
|
|
66
|
+
* existing posture visible and points at the existing restriction knob.
|
|
67
|
+
*
|
|
68
|
+
* @param {object} opts
|
|
69
|
+
* @param {string} [opts.bindHost] - resolved bind host (`undefined` = 0.0.0.0).
|
|
70
|
+
* @param {{ warn: (msg: string) => void }} opts.log - logger to warn through.
|
|
71
|
+
* @returns {boolean} true when the warning was emitted.
|
|
72
|
+
*/
|
|
73
|
+
export function maybeWarnNonLoopbackBind({ bindHost, log }) {
|
|
74
|
+
if (isLoopbackHost(bindHost)) return false
|
|
75
|
+
const shown = bindHost || '0.0.0.0 (all interfaces)'
|
|
76
|
+
log.warn(
|
|
77
|
+
`Listening on ${shown} — devices on your local network can reach this server's ` +
|
|
78
|
+
'auth and pairing endpoints (bearer-token gated, but the server is fingerprintable via /health). ' +
|
|
79
|
+
'To restrict to this machine only, start with --host 127.0.0.1, set CHROXY_HOST=127.0.0.1, or set "host": "127.0.0.1" in ~/.chroxy/config.json'
|
|
80
|
+
)
|
|
81
|
+
return true
|
|
82
|
+
}
|