@askalf/dario 6.18.2 → 6.18.3
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/README.md +14 -10
- package/dist/browser-guard.d.ts +56 -0
- package/dist/browser-guard.js +147 -0
- package/dist/proxy.js +33 -0
- package/docs/commands.md +2 -4
- package/docs/docker.md +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
<div align="center">
|
|
2
2
|
|
|
3
|
-
<img src=".github/readme/hero.jpg" alt="dario routes every AI tool you use to the subscriptions you already pay for. Claude Code, Cursor, Cline, Aider, Codex CLI and the Agent SDK send requests to dario at localhost:3456, which forwards each one to your Claude plan or your ChatGPT plan and fails over between them on a 429." width="100%">
|
|
3
|
+
<img src=".github/readme/hero.jpg" alt="dario routes every AI tool you use to the subscriptions you already pay for. Claude Code, Cursor, Cline, Aider, Codex CLI and the Agent SDK send requests to dario at localhost:3456, which forwards each one to your Claude plan or your ChatGPT plan and, with a fallback chain configured, fails over between them on a 429." width="100%">
|
|
4
4
|
|
|
5
5
|
# `dario`
|
|
6
6
|
|
|
@@ -51,12 +51,12 @@ Prefer Homebrew? `brew install askalf/tap/dario` installs the same npm release t
|
|
|
51
51
|
|
|
52
52
|
- **Every tool, one URL.** No per-tool keys and no second bill: anything with a base-URL setting runs on the plan you already pay for. [Per-tool setup](docs/tools.md)
|
|
53
53
|
- **Knows who paid.** A ledger prices every request at API rates and splits it by plan, by key and by model: what the seats absorbed, what went to extra usage or an API key. In the TUI, the dashboard at `/analytics/ui`, `/analytics`, Prometheus `/metrics` and `dario usage`. [Analytics](docs/pool-keys-and-analytics.md#what-it-would-have-cost)
|
|
54
|
-
- **Spends the plan before the meter.** Seats with headroom first, then the `--pool-fallback` chain you configure: the other plan on a 429, a metered rung last (your Max plan's API credits through a Console key, or an openai-compat backend). No chain means no substitution, a drained pool returns its honest 429. Nothing is swapped silently: every substituted response says so in a header. [Failover](docs/two-plans.md#failover-between-subscriptions)
|
|
54
|
+
- **Spends the plan before the meter.** Seats with headroom first, then the `--pool-fallback` chain you configure: the other plan on a 429, a metered rung last (your Max plan's API credits through a Console key, or an openai-compat backend). No chain means no substitution, a drained pool returns its honest 429. When one model family is parked but the seat still has room, `--family-fallback=fable=claude-opus-5-5` serves it as another Claude model instead of a 429 ([how](docs/multi-account-pool.md#family-fallback)). Nothing is swapped silently: every substituted response says so in a header. [Failover](docs/two-plans.md#failover-between-subscriptions)
|
|
55
55
|
- **Either plan, either wire shape.** Your ChatGPT plan behind Claude Code and the Anthropic SDKs; Codex CLI on your Claude plan. [Two plans](docs/two-plans.md)
|
|
56
|
-
- **Failover that finishes the answer.**
|
|
57
|
-
- **Many seats, one endpoint.** Per-model headroom routing, session-sticky prompt cache, in-flight 429 failover across every seat you hold. New conversations go to the seat with the most headroom by default; `--pool-strategy=fill-first` fills seats in alias order
|
|
58
|
-
- **One key per developer.** Named keys with a preferred seat, a model allowlist and a daily budget. [Keys](docs/pool-keys-and-analytics.md#one-key-per-developer)
|
|
59
|
-
- **Tracks Claude Code on its own.**
|
|
56
|
+
- **Failover that finishes the answer.** With a `--pool-fallback` chain, a 429 on one plan is re-served by the other. A stream that dies mid-answer is completed on the same model first, chain or not. [Failover](docs/two-plans.md#failover-between-subscriptions)
|
|
57
|
+
- **Many seats, one endpoint.** Per-model headroom routing, session-sticky prompt cache, in-flight 429 failover across every seat you hold. New conversations go to the seat with the most headroom by default; `--pool-strategy=fill-first` fills seats in alias order, `expiring-first` spends the seat whose weekly window resets soonest, and `headroom-by-plan` counts each seat's headroom by its plan size. The active strategy shows in the startup banner, `GET /status`, `dario doctor` and `dario accounts list`. [The pool](docs/pool-keys-and-analytics.md)
|
|
58
|
+
- **One key per developer.** Named keys with a preferred seat, a model allowlist and a daily budget. A CI job or a sandboxed agent can be a key with no secret to hold: `--key-socket` binds a unix socket to one key ([key sockets](docs/keys.md#a-key-with-no-secret-key-sockets)). [Keys](docs/pool-keys-and-analytics.md#one-key-per-developer)
|
|
59
|
+
- **Tracks Claude Code on its own.** Ten unattended watchers catch wire-shape drift and ship the fix, usually the same day. [Drift](docs/tracking-claude-code.md)
|
|
60
60
|
- **Stops before it costs you.** The overage guard halts the proxy the moment a response bills outside your subscription. [Guardrails](docs/guardrails.md)
|
|
61
61
|
- **Your traffic as the benchmark.** Shadow-compare any request against another model and read the results with `dario compare`. [Shadow compare](docs/two-plans.md#shadow-compare)
|
|
62
62
|
|
|
@@ -113,13 +113,13 @@ dario runs entirely on your machine, authenticates as you with your own Claude l
|
|
|
113
113
|
|
|
114
114
|
| Signal | Status |
|
|
115
115
|
|---|---|
|
|
116
|
-
| Source | **~42k** lines of TypeScript across **
|
|
116
|
+
| Source | **~42k** lines of TypeScript across **87** files, auditable in a weekend. One credential path since v5: the pool. |
|
|
117
117
|
| Dependencies | **0 runtime.** Verify: `npm ls --production` |
|
|
118
118
|
| Provenance | Every release [SLSA-attested](https://www.npmjs.com/package/@askalf/dario) via GitHub Actions + Sigstore, published with OIDC trusted publishing: no long-lived npm token exists to leak |
|
|
119
119
|
| Scanning | [CodeQL](https://github.com/askalf/dario/actions/workflows/codeql.yml) on every push to master, every PR and weekly · [ClusterFuzzLite](./.github/workflows/cflite.yml) fuzzes the SSE translator, the rejection parsers and the cch stamper weekly · the [OpenSSF Scorecard](https://scorecard.dev/viewer/?uri=github.com/askalf/dario) badge above and the [Best Practices](https://www.bestpractices.dev/projects/13638) entry are live |
|
|
120
|
-
| Tests | **
|
|
120
|
+
| Tests | **282 test files** run in parallel by `npm test` on Node 18, 20 and 22; the live e2e / compat / stealth suites have their own entry points. Green on every release |
|
|
121
121
|
| Credentials | Your own subscription tokens, never logged, redacted from errors, `0600` on disk in `0700` dirs |
|
|
122
|
-
| Network | Binds `127.0.0.1` by default; upstream only to configured backends over HTTPS; hardcoded SSRF allow-list; refuses a non-loopback bind without `DARIO_API_KEY
|
|
122
|
+
| Network | Binds `127.0.0.1` by default; upstream only to configured backends over HTTPS; hardcoded SSRF allow-list; refuses a non-loopback bind without `DARIO_API_KEY`; refuses cross-origin and DNS-rebound browser requests |
|
|
123
123
|
| Telemetry | **None.** No analytics, no tracking, nothing phones home |
|
|
124
124
|
| Overhead | Measured in the open on every PR: [`scripts/bench-overhead.mjs`](./scripts/bench-overhead.mjs) runs a real proxy against an instant upstream beside a bare http server serving the same bytes. On loopback dario adds no measurable p50 wall time over that floor; the CPU per request is the number to watch, and the per-request [timing split](./docs/analytics.md#the-timing-split) shows it live |
|
|
125
125
|
| This README | CI fails if the line count above drifts from `src/` or a link or anchor here stops resolving ([`check-readme-line-count.mjs`](./scripts/check-readme-line-count.mjs), [`check-readme-links.mjs`](./scripts/check-readme-links.mjs)); the TUI screenshots are rendered from the real TUI and the diagrams are briefed art, not screenshots ([how](./scripts/readme/README.md)) |
|
|
@@ -136,6 +136,7 @@ Security reports go to **security@askalf.org**, not a public issue: [SECURITY.md
|
|
|
136
136
|
|
|
137
137
|
- [Claude Code wire drift](https://askalf.github.io/dario/drift-feed/): every change to what Claude Code sends on the wire, as the template watcher observed it; [RSS](https://askalf.github.io/dario/drift-feed/feed.xml) · [JSON Feed](https://askalf.github.io/dario/drift-feed/feed.json)
|
|
138
138
|
|
|
139
|
+
- [#1017: Will my account get suspended? What is actually observable, and how to monitor it yourself](https://github.com/askalf/dario/discussions/1017)
|
|
139
140
|
- [#183: Modifying Claude Code's system prompt doesn't change billing; stripping its constraints recovers 1.2–2.8× output](https://github.com/askalf/dario/discussions/183)
|
|
140
141
|
- [#68: dario vs LiteLLM / OpenRouter / Kong AI Gateway (when each wins)](https://github.com/askalf/dario/discussions/68)
|
|
141
142
|
- [#14: Template replay: why we replay the shape instead of matching signals](https://github.com/askalf/dario/discussions/14)
|
|
@@ -151,7 +152,7 @@ PRs welcome. Small TypeScript codebase, zero runtime deps. Architecture, file-by
|
|
|
151
152
|
git clone https://github.com/askalf/dario && cd dario
|
|
152
153
|
npm install
|
|
153
154
|
npm run dev # tsx, no build step
|
|
154
|
-
npm test #
|
|
155
|
+
npm test # 282 files in parallel via test/all.test.mjs
|
|
155
156
|
npm run e2e # live proxy + OAuth (needs a working Claude backend)
|
|
156
157
|
```
|
|
157
158
|
|
|
@@ -206,6 +207,9 @@ Two easy ways to help beyond code: **star the repo**, the clearest signal this i
|
|
|
206
207
|
| [@robincle](https://github.com/robincle) | Utilisation freshness: `lastObservedAt` / `utilAgeMs` on `/accounts` ([#1032](https://github.com/askalf/dario/issues/1032)), the documented way out of a parked pool ([#1282](https://github.com/askalf/dario/issues/1282)) |
|
|
207
208
|
| [@anupamme](https://github.com/anupamme) | Refresh-lock ownership by server-issued lock id ([#1059](https://github.com/askalf/dario/pull/1059)) |
|
|
208
209
|
| [@LiveNathan](https://github.com/LiveNathan) | Never send or stamp empty text blocks ([#1067](https://github.com/askalf/dario/pull/1067)), empty final user turn from CC's stream-interruption retry ([#1092](https://github.com/askalf/dario/issues/1092), as [@NathanLively](https://github.com/NathanLively)) |
|
|
210
|
+
| [@dizzystuff](https://github.com/dizzystuff) | Fable's weekly allowance arrives as `7d_oi`, not `7d_fable`, so headroom now counts it ([#1262](https://github.com/askalf/dario/issues/1262)) |
|
|
211
|
+
| [@ZQiannnn](https://github.com/ZQiannnn) | Fable `input_schema.type` 400 on every request, with a full reproduction and the confirmed fix ([#1376](https://github.com/askalf/dario/issues/1376)) |
|
|
212
|
+
| [@andrewmalov](https://github.com/andrewmalov) | Hard-park seats at the headroom floor ([#1450](https://github.com/askalf/dario/pull/1450)) |
|
|
209
213
|
|
|
210
214
|
### Sponsors
|
|
211
215
|
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser request guard: keeps a web page from using a proxy it can reach.
|
|
3
|
+
* A tab on any site can reach 127.0.0.1, and CORS only stops a page from
|
|
4
|
+
* reading a response, not from sending a `no-cors` request in the first place.
|
|
5
|
+
*
|
|
6
|
+
* isCrossOriginAllowed refuses a state-changing request a page on another
|
|
7
|
+
* origin sent. Same algorithm as Go's net/http CrossOriginProtection: GET,
|
|
8
|
+
* HEAD and OPTIONS pass (a cross-origin page cannot read their responses),
|
|
9
|
+
* `Sec-Fetch-Site: same-origin | none` passes, an `Origin` on the trusted list
|
|
10
|
+
* passes, any other `Sec-Fetch-Site` is refused, and a browser that predates
|
|
11
|
+
* `Sec-Fetch-Site` falls back to comparing `Origin` with `Host`. It reads only
|
|
12
|
+
* headers a page cannot forge, and applies only to a request carrying one of
|
|
13
|
+
* them (isBrowserRequest): SDKs, curl and CLI clients send neither. Node's
|
|
14
|
+
* fetch sends `Sec-Fetch-Mode: cors`, so nothing here reads `Sec-Fetch-Mode`.
|
|
15
|
+
*
|
|
16
|
+
* isHostAllowed closes DNS rebinding. A page on attacker.example whose name is
|
|
17
|
+
* re-pointed at 127.0.0.1 is same-origin with the proxy as far as the browser
|
|
18
|
+
* knows, so the origin check passes it and the page can read every response.
|
|
19
|
+
* Its requests still carry `Host: attacker.example`, so a request must name the
|
|
20
|
+
* proxy by a host that cannot be rebound: localhost, a *.localhost name
|
|
21
|
+
* (browsers resolve those to loopback without DNS), an IP literal (no DNS to
|
|
22
|
+
* re-point), the bind host, or the host of a trusted origin. This check cannot
|
|
23
|
+
* wait for a browser header: browsers send `Sec-Fetch-Site` only to a
|
|
24
|
+
* trustworthy URL, which http://attacker.example is not, and a same-origin GET
|
|
25
|
+
* carries no `Origin`, so a rebound GET looks exactly like curl.
|
|
26
|
+
*
|
|
27
|
+
* The host check only matters where an absent credential is served, i.e. no
|
|
28
|
+
* DARIO_API_KEY. With the key set, a rebinding page never holds it and gets
|
|
29
|
+
* the same 401 as anyone else, so a keyed proxy behind a tunnel hostname keeps
|
|
30
|
+
* serving without listing that hostname anywhere.
|
|
31
|
+
*/
|
|
32
|
+
type Headers = Record<string, string | string[] | undefined>;
|
|
33
|
+
/**
|
|
34
|
+
* Lower-cased `scheme://host[:port]` with no trailing slash, the form a
|
|
35
|
+
* browser's `Origin` header takes. An http(s) origin goes through URL so a
|
|
36
|
+
* default port or trailing slash in DARIO_CORS_ORIGIN still matches. Other
|
|
37
|
+
* schemes (`chrome-extension://<id>`) have an opaque URL origin, so they are
|
|
38
|
+
* compared as written. `null` (sandboxed frames, file: pages) stays `null` so
|
|
39
|
+
* an operator can trust it explicitly. Anything else returns undefined and is
|
|
40
|
+
* never trusted.
|
|
41
|
+
*/
|
|
42
|
+
export declare function normalizeOrigin(origin: string): string | undefined;
|
|
43
|
+
/** The hostname of a `Host` header, port dropped and lower-cased; `[::1]` keeps its brackets. */
|
|
44
|
+
export declare function hostnameOf(host: string | undefined): string | undefined;
|
|
45
|
+
/** Whether the request carries a header only a browser sets. */
|
|
46
|
+
export declare function isBrowserRequest(headers: Headers): boolean;
|
|
47
|
+
/**
|
|
48
|
+
* The trusted origin list: the CORS origin dario already advertises.
|
|
49
|
+
* Unparseable entries drop out instead of matching anything.
|
|
50
|
+
*/
|
|
51
|
+
export declare function trustedOriginSet(origins: string[]): Set<string>;
|
|
52
|
+
export declare function isCrossOriginAllowed(method: string | undefined, headers: Headers, trusted: Set<string>): boolean;
|
|
53
|
+
/** Host names a request may use to reach an unkeyed proxy, besides *.localhost and IP literals. */
|
|
54
|
+
export declare function allowedHosts(trusted: Set<string>, bindHost: string | undefined): Set<string>;
|
|
55
|
+
export declare function isHostAllowed(headers: Headers, allowed: Set<string>): boolean;
|
|
56
|
+
export {};
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser request guard: keeps a web page from using a proxy it can reach.
|
|
3
|
+
* A tab on any site can reach 127.0.0.1, and CORS only stops a page from
|
|
4
|
+
* reading a response, not from sending a `no-cors` request in the first place.
|
|
5
|
+
*
|
|
6
|
+
* isCrossOriginAllowed refuses a state-changing request a page on another
|
|
7
|
+
* origin sent. Same algorithm as Go's net/http CrossOriginProtection: GET,
|
|
8
|
+
* HEAD and OPTIONS pass (a cross-origin page cannot read their responses),
|
|
9
|
+
* `Sec-Fetch-Site: same-origin | none` passes, an `Origin` on the trusted list
|
|
10
|
+
* passes, any other `Sec-Fetch-Site` is refused, and a browser that predates
|
|
11
|
+
* `Sec-Fetch-Site` falls back to comparing `Origin` with `Host`. It reads only
|
|
12
|
+
* headers a page cannot forge, and applies only to a request carrying one of
|
|
13
|
+
* them (isBrowserRequest): SDKs, curl and CLI clients send neither. Node's
|
|
14
|
+
* fetch sends `Sec-Fetch-Mode: cors`, so nothing here reads `Sec-Fetch-Mode`.
|
|
15
|
+
*
|
|
16
|
+
* isHostAllowed closes DNS rebinding. A page on attacker.example whose name is
|
|
17
|
+
* re-pointed at 127.0.0.1 is same-origin with the proxy as far as the browser
|
|
18
|
+
* knows, so the origin check passes it and the page can read every response.
|
|
19
|
+
* Its requests still carry `Host: attacker.example`, so a request must name the
|
|
20
|
+
* proxy by a host that cannot be rebound: localhost, a *.localhost name
|
|
21
|
+
* (browsers resolve those to loopback without DNS), an IP literal (no DNS to
|
|
22
|
+
* re-point), the bind host, or the host of a trusted origin. This check cannot
|
|
23
|
+
* wait for a browser header: browsers send `Sec-Fetch-Site` only to a
|
|
24
|
+
* trustworthy URL, which http://attacker.example is not, and a same-origin GET
|
|
25
|
+
* carries no `Origin`, so a rebound GET looks exactly like curl.
|
|
26
|
+
*
|
|
27
|
+
* The host check only matters where an absent credential is served, i.e. no
|
|
28
|
+
* DARIO_API_KEY. With the key set, a rebinding page never holds it and gets
|
|
29
|
+
* the same 401 as anyone else, so a keyed proxy behind a tunnel hostname keeps
|
|
30
|
+
* serving without listing that hostname anywhere.
|
|
31
|
+
*/
|
|
32
|
+
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
33
|
+
function headerOf(headers, name) {
|
|
34
|
+
const v = headers[name];
|
|
35
|
+
return Array.isArray(v) ? v[0] : v;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Lower-cased `scheme://host[:port]` with no trailing slash, the form a
|
|
39
|
+
* browser's `Origin` header takes. An http(s) origin goes through URL so a
|
|
40
|
+
* default port or trailing slash in DARIO_CORS_ORIGIN still matches. Other
|
|
41
|
+
* schemes (`chrome-extension://<id>`) have an opaque URL origin, so they are
|
|
42
|
+
* compared as written. `null` (sandboxed frames, file: pages) stays `null` so
|
|
43
|
+
* an operator can trust it explicitly. Anything else returns undefined and is
|
|
44
|
+
* never trusted.
|
|
45
|
+
*/
|
|
46
|
+
export function normalizeOrigin(origin) {
|
|
47
|
+
let o = origin.trim().toLowerCase();
|
|
48
|
+
// A loop, not /\/+$/: that regex backtracks quadratically on a long run of
|
|
49
|
+
// slashes, and the Origin header is caller-controlled.
|
|
50
|
+
while (o.endsWith('/'))
|
|
51
|
+
o = o.slice(0, -1);
|
|
52
|
+
if (o === 'null')
|
|
53
|
+
return o;
|
|
54
|
+
if (/^https?:\/\//.test(o)) {
|
|
55
|
+
try {
|
|
56
|
+
return new URL(o).origin;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return /^[a-z][a-z0-9+.-]*:\/\/[^/\s]+$/.test(o) ? o : undefined;
|
|
63
|
+
}
|
|
64
|
+
function httpHostOf(origin) {
|
|
65
|
+
return /^https?:\/\//.test(origin) ? new URL(origin) : undefined;
|
|
66
|
+
}
|
|
67
|
+
/** The hostname of a `Host` header, port dropped and lower-cased; `[::1]` keeps its brackets. */
|
|
68
|
+
export function hostnameOf(host) {
|
|
69
|
+
if (!host)
|
|
70
|
+
return undefined;
|
|
71
|
+
const h = host.trim().toLowerCase();
|
|
72
|
+
if (h.startsWith('[')) {
|
|
73
|
+
const end = h.indexOf(']');
|
|
74
|
+
return end === -1 ? undefined : h.slice(0, end + 1);
|
|
75
|
+
}
|
|
76
|
+
const colon = h.indexOf(':');
|
|
77
|
+
if (colon === -1)
|
|
78
|
+
return h;
|
|
79
|
+
// More than one colon unbracketed is not a valid Host.
|
|
80
|
+
return h.indexOf(':', colon + 1) === -1 ? h.slice(0, colon) : undefined;
|
|
81
|
+
}
|
|
82
|
+
/** Whether the request carries a header only a browser sets. */
|
|
83
|
+
export function isBrowserRequest(headers) {
|
|
84
|
+
return headerOf(headers, 'sec-fetch-site') !== undefined || headerOf(headers, 'origin') !== undefined;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The trusted origin list: the CORS origin dario already advertises.
|
|
88
|
+
* Unparseable entries drop out instead of matching anything.
|
|
89
|
+
*/
|
|
90
|
+
export function trustedOriginSet(origins) {
|
|
91
|
+
const out = new Set();
|
|
92
|
+
for (const o of origins) {
|
|
93
|
+
const n = normalizeOrigin(o);
|
|
94
|
+
if (n)
|
|
95
|
+
out.add(n);
|
|
96
|
+
}
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
export function isCrossOriginAllowed(method, headers, trusted) {
|
|
100
|
+
if (SAFE_METHODS.has((method ?? '').toUpperCase()))
|
|
101
|
+
return true;
|
|
102
|
+
const site = headerOf(headers, 'sec-fetch-site')?.toLowerCase();
|
|
103
|
+
if (site === 'same-origin' || site === 'none')
|
|
104
|
+
return true;
|
|
105
|
+
const origin = headerOf(headers, 'origin');
|
|
106
|
+
const normalized = origin === undefined ? undefined : normalizeOrigin(origin);
|
|
107
|
+
if (normalized !== undefined && trusted.has(normalized))
|
|
108
|
+
return true;
|
|
109
|
+
// A browser that sends Sec-Fetch-Site said cross-site or same-site here.
|
|
110
|
+
if (site !== undefined)
|
|
111
|
+
return false;
|
|
112
|
+
// Neither header: not a browser, or one too old to send either on a POST.
|
|
113
|
+
if (origin === undefined)
|
|
114
|
+
return true;
|
|
115
|
+
const url = normalized === undefined ? undefined : httpHostOf(normalized);
|
|
116
|
+
const host = headerOf(headers, 'host')?.trim().toLowerCase();
|
|
117
|
+
return url !== undefined && host !== undefined && url.host === host;
|
|
118
|
+
}
|
|
119
|
+
/** Host names a request may use to reach an unkeyed proxy, besides *.localhost and IP literals. */
|
|
120
|
+
export function allowedHosts(trusted, bindHost) {
|
|
121
|
+
const out = new Set(['localhost']);
|
|
122
|
+
for (const o of trusted) {
|
|
123
|
+
const url = httpHostOf(o);
|
|
124
|
+
if (url)
|
|
125
|
+
out.add(url.hostname);
|
|
126
|
+
}
|
|
127
|
+
if (bindHost) {
|
|
128
|
+
const h = bindHost.trim().toLowerCase();
|
|
129
|
+
out.add(h.includes(':') && !h.startsWith('[') ? `[${h}]` : h);
|
|
130
|
+
}
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
const IPV4_LITERAL = /^\d{1,3}(\.\d{1,3}){3}$/;
|
|
134
|
+
export function isHostAllowed(headers, allowed) {
|
|
135
|
+
const host = headerOf(headers, 'host');
|
|
136
|
+
// A browser always sends Host, so a request without one is not a rebound page.
|
|
137
|
+
if (host === undefined)
|
|
138
|
+
return true;
|
|
139
|
+
const name = hostnameOf(host);
|
|
140
|
+
if (name === undefined)
|
|
141
|
+
return false;
|
|
142
|
+
if (allowed.has(name))
|
|
143
|
+
return true;
|
|
144
|
+
if (name.endsWith('.localhost'))
|
|
145
|
+
return true;
|
|
146
|
+
return IPV4_LITERAL.test(name) || name.startsWith('[');
|
|
147
|
+
}
|
package/dist/proxy.js
CHANGED
|
@@ -9,6 +9,7 @@ import { arch, platform } from 'node:process';
|
|
|
9
9
|
import { FAMILY_BETA_DROPS } from './beta-family-drops.js';
|
|
10
10
|
import { getAccessToken, getStatus, ignoreCcCredentials } from './oauth.js';
|
|
11
11
|
import { buildHealthResponse, derivePoolStatus, probeRequested, shouldDiscloseHealthInternals, shouldRunServingProbe } from './health-response.js';
|
|
12
|
+
import { allowedHosts, isBrowserRequest, isCrossOriginAllowed, isHostAllowed, trustedOriginSet } from './browser-guard.js';
|
|
12
13
|
import { getServingProbe } from './serving-probe.js';
|
|
13
14
|
import { darioVersion } from './version.js';
|
|
14
15
|
import { CC_TOOL_DEFINITIONS_UNADVERTISABLE, CC_TEMPLATE_PROMPT_BYTES, resolveMaxTokens, buildCCRequest, applyCcPromptCaching, isGenuineCCClient, parseEffortSuffix, reverseMapResponse, createStreamingReverseMapper, orderHeadersForOutbound, overlayTemplateHeaderValues, forwardClientCCIdentityHeaders, isMcpToolName, UnsupportedClientToolError, CLIENT_TOOL_MCP_PREFIX, CC_TEMPLATE, effectiveCacheControl, withForced1hBeta } from './cc-template.js';
|
|
@@ -2329,6 +2330,10 @@ export async function startProxy(opts = {}) {
|
|
|
2329
2330
|
// override via DARIO_CORS_ORIGIN — otherwise browser-based clients hitting
|
|
2330
2331
|
// dario over the mesh will be blocked by their browser's CORS check.
|
|
2331
2332
|
const corsOrigin = process.env.DARIO_CORS_ORIGIN || `http://localhost:${port}`;
|
|
2333
|
+
// The browser guard trusts the same origin CORS advertises, and accepts its
|
|
2334
|
+
// host as a name an unkeyed proxy may be reached by (browser-guard.ts).
|
|
2335
|
+
const trustedOrigins = trustedOriginSet([corsOrigin]);
|
|
2336
|
+
const hostNames = allowedHosts(trustedOrigins, host);
|
|
2332
2337
|
// Security headers for all responses
|
|
2333
2338
|
const SECURITY_HEADERS = {
|
|
2334
2339
|
'X-Content-Type-Options': 'nosniff',
|
|
@@ -2397,6 +2402,8 @@ export async function startProxy(opts = {}) {
|
|
|
2397
2402
|
const ERR_UNAUTH = JSON.stringify({ error: 'Unauthorized', message: 'Invalid or missing API key' });
|
|
2398
2403
|
const ERR_FORBIDDEN = JSON.stringify({ error: 'Forbidden', message: 'Path not allowed. Supported paths: POST /v1/messages, POST /v1/messages/count_tokens, POST /v1/chat/completions, GET /v1/models' });
|
|
2399
2404
|
const ERR_METHOD = JSON.stringify({ error: 'Method not allowed' });
|
|
2405
|
+
const ERR_CROSS_ORIGIN = JSON.stringify({ error: 'Forbidden', message: 'Cross-origin browser request refused. A browser client on another origin needs DARIO_CORS_ORIGIN set to that origin.' });
|
|
2406
|
+
const ERR_HOST = JSON.stringify({ error: 'Forbidden', message: 'Request refused: the Host header is not localhost or an IP address, and DARIO_API_KEY is not set. Reach dario at localhost or 127.0.0.1, set DARIO_API_KEY, or set DARIO_CORS_ORIGIN to the origin you serve it under.' });
|
|
2400
2407
|
/** The named key each key-socket connection is (opts.keySockets); absent for TCP. */
|
|
2401
2408
|
const keySocketOf = new WeakMap();
|
|
2402
2409
|
/**
|
|
@@ -2750,6 +2757,32 @@ export async function startProxy(opts = {}) {
|
|
|
2750
2757
|
res.end();
|
|
2751
2758
|
return;
|
|
2752
2759
|
}
|
|
2760
|
+
// Browser request guard (browser-guard.ts), ahead of every route: a web
|
|
2761
|
+
// page must not spend the subscription, clear the overage halt or read
|
|
2762
|
+
// /accounts through a proxy that serves an absent credential. The
|
|
2763
|
+
// cross-origin check judges only requests carrying Origin or
|
|
2764
|
+
// Sec-Fetch-Site. The Host check covers every request to an unkeyed proxy,
|
|
2765
|
+
// because a rebound page's GET carries neither. A key socket is
|
|
2766
|
+
// unreachable from a browser.
|
|
2767
|
+
if (socketKey === undefined) {
|
|
2768
|
+
const refusal = isBrowserRequest(req.headers) && !isCrossOriginAllowed(req.method, req.headers, trustedOrigins)
|
|
2769
|
+
? 'cross-origin'
|
|
2770
|
+
: (!apiKeyBuf && !isHostAllowed(req.headers, hostNames)) ? 'host' : null;
|
|
2771
|
+
if (refusal) {
|
|
2772
|
+
if (verbose) {
|
|
2773
|
+
console.error(refusal === 'cross-origin'
|
|
2774
|
+
? `[dario] 403 refused (cross-origin browser request, Origin ${req.headers.origin ?? '-'}, Sec-Fetch-Site ${req.headers['sec-fetch-site'] ?? '-'}): ${req.method} ${urlPath}`
|
|
2775
|
+
: `[dario] 403 refused (Host ${req.headers.host ?? '-'} on a proxy without DARIO_API_KEY): ${req.method} ${urlPath}`);
|
|
2776
|
+
}
|
|
2777
|
+
writeLogLine(logFileStream, {
|
|
2778
|
+
ts: new Date().toISOString(), req: requestCount,
|
|
2779
|
+
method: req.method ?? '', path: urlPath, status: 403, reject: refusal,
|
|
2780
|
+
});
|
|
2781
|
+
res.writeHead(403, JSON_HEADERS);
|
|
2782
|
+
res.end(refusal === 'cross-origin' ? ERR_CROSS_ORIGIN : ERR_HOST);
|
|
2783
|
+
return;
|
|
2784
|
+
}
|
|
2785
|
+
}
|
|
2753
2786
|
// Liveness probe — always 200 while the HTTP server is accepting requests,
|
|
2754
2787
|
// deliberately decoupled from OAuth state. Docker's healthcheck (and the
|
|
2755
2788
|
// autoheal watchdog that keys on it) points HERE, not /health: a broken or
|
package/docs/commands.md
CHANGED
|
@@ -43,8 +43,6 @@ This page is the per-flag reference. For environment variables grouped by task
|
|
|
43
43
|
| `--key-socket=<path>=<key>` / `DARIO_KEY_SOCKETS` | Also listen on a unix socket bound to one named key: every request on it is that key's, with no secret sent or stored by the caller; the socket's directory and group decide who may connect. Repeatable. See [Key sockets](./keys.md#a-key-with-no-secret-key-sockets). | none |
|
|
44
44
|
| `--no-keys` / `DARIO_KEYS=0`; `--keys-path=<file>` / `DARIO_KEYS_PATH` | Ignore named keys (`~/.dario/keys.json`) so only `DARIO_API_KEY` authenticates; or move the file. See [Named keys](./keys.md). (v6.8) | on, `~/.dario/keys.json` |
|
|
45
45
|
| `--log-file=<path>` / `DARIO_LOG_FILE` | Append one JSON-ND record per completed request to PATH. Useful for backgrounded proxies where stdout is unobserved (where `--verbose` can't help). Field set: `ts`, `req`, `method`, `path`, `model`, `status`, `latency_ms`, `in_tokens`, `out_tokens`, `cache_read`, `cache_create`, `claim`, `bucket`, `account`, `client`, `preserve_tools`, `stream`, plus `reject` / `error` on failure paths, and on a ChatGPT (codex) request the cache trace `cache_key`, `cache_items`, `cache_since_ms`, `cache_prev_items`, `cache_extends`, `cache_diverged_at`, `cache_seat_changed`, `cache_prefix_changed`. Secrets scrubbed via the same redactor that `--verbose-bodies` uses; no request bodies. | off |
|
|
46
|
-
| `--pool-fallback=<models>` / `DARIO_POOL_FALLBACK` / config `poolFallback.model` | Strictly opt-in. When every pool seat is drained or in auth cool-down (at selection, or mid-flight on a 429 with no peer left), serve the request as `<model>` from whichever provider can, instead of surfacing the 429/503. Accepts a **chain** — `gpt-5.6-sol,claude-sonnet-5` — read left to right, each provider taking the first entry it can serve. A Codex/ChatGPT subscription that lists the model is preferred (no per-token cost) and works on **both** wire shapes; otherwise a configured openai-compat backend, which is still OpenAI-path only (no Messages translation on that route). A chain also makes failover **symmetric**: a rate-limited or failing subscription hands the request back to the Claude pool. Only a 429/5xx fails over — a 400 surfaces, since a bad request would just reproduce itself elsewhere. Every substituted response carries `x-dario-pool-fallback: <model>` — never silent. Needs a Codex account (`dario add altman`) or a backend (`dario backend add …`); `dario doctor` reports it as INERT with neither. Empty pool still 503s (setup error, not traffic to re-bill). Empty flag value disables, overriding env + config. See [Pool-exhausted fallback](./multi-account-pool.md#pool-exhausted-fallback). | off |
|
|
47
|
-
| `--family-fallback=<family=model,...>` / `DARIO_FAMILY_FALLBACK` / config `familyFallback` | Strictly opt-in. When a rate limit keeps every pool seat off a model family, serve that family's requests as `<model>` on the Claude pool, while some seat can serve the target's family. Written for Fable: its included credit runs out while the seat still has room for Opus, so `fable=claude-opus-5-5` keeps Fable traffic on the subscription instead of a local 429 until the credit resets. The target must be a `claude-*` model of another family; one step, never chained. Runs before `--pool-fallback`, so a pool with room for the target never leaves the Claude pool. Skipped in upstream API-key mode, under `--model`/`--fast-model` and for a seat-pinned request. A `[1m]` tag on the request carries over. Every switched response carries `x-dario-family-fallback: <requested model>`. Empty flag value disables, overriding env + config. See [Family fallback](./multi-account-pool.md#family-fallback). | off |
|
|
48
46
|
| `--passthrough-betas=<csv>` / `DARIO_PASSTHROUGH_BETAS` | Beta flags ALWAYS forwarded upstream regardless of CC's captured set or the client's `anthropic-beta` header. Bypasses the billable-beta filter (so `extended-cache-ttl-*` survives if you opt in). Per-account rejection cache still applies — a pinned flag the upstream 400's gets dropped on retry rather than re-sent forever. Use when you know a beta works on your account but isn't in the captured template, or when client traffic should be force-augmented. Empty flag value (`--passthrough-betas=`) clears the env-default. | off |
|
|
49
47
|
| `--strict-tls` / `DARIO_STRICT_TLS=1` | Refuse to start proxy mode unless runtime classifies as `bun-match` — i.e. the TLS ClientHello matches CC's. See [Wire-fidelity axes](./wire-fidelity.md). (v3.23) | off |
|
|
50
48
|
| `--pace-min=<ms>` / `DARIO_PACE_MIN_MS` | Minimum inter-request gap in ms. Replaces the legacy hardcoded 500 ms. (v3.24) | `500` |
|
|
@@ -59,8 +57,8 @@ This page is the per-flag reference. For environment variables grouped by task
|
|
|
59
57
|
| `--family-fallback=<family=model,...>` / `DARIO_FAMILY_FALLBACK` / config `familyFallback` | Strictly opt-in. When a rate limit keeps every pool seat off a model family, serve that family's requests as `<model>` on the Claude pool, while some seat can serve the target's family. Written for Fable: its included credit runs out while the seat still has room for Opus, so `fable=claude-opus-5-5` keeps Fable traffic on the subscription instead of a local 429 until the credit resets. The target must be a `claude-*` model of another family; one step, never chained. Runs before `--pool-fallback`, so a pool with room for the target never leaves the Claude pool. Skipped in upstream API-key mode, under `--model`/`--fast-model` and for a seat-pinned request. A `[1m]` tag on the request carries over. Every switched response carries `x-dario-family-fallback: <requested model>`. Empty flag value disables, overriding env + config. See [Family fallback](./multi-account-pool.md#family-fallback). | off |
|
|
60
58
|
| `--system-prompt=<verbatim\|partial\|aggressive\|filepath>` / `DARIO_SYSTEM_PROMPT` | System-prompt mode for outbound CC-shaped requests. `partial` strips behavioral constraints (Tone-and-style, Text-output, scope/verbosity/comment bullets) for ~1.2–2.8× output capability on open-ended work. `aggressive` adds prompt-level RLHF restatement removal (<3% over partial — alignment is RLHF-trained). `<filepath>` fully replaces the slot with file contents. Empirically validated as unfingerprinted by the billing classifier — see [`system-prompt.md`](./system-prompt.md) and [`research/system-prompt-classifier-study.md`](./research/system-prompt-classifier-study.md). (v3.34) | `verbatim` |
|
|
61
59
|
| `--upstream-proxy=<url>` / `--via=<url>` / `DARIO_UPSTREAM_PROXY` | Route dario's outbound fetches (api.anthropic.com, OpenAI-compat backends, OAuth) through an HTTP/HTTPS proxy. Pair with the HTTP proxy mode of a VPN provider (Mullvad, AirVPN), a corporate proxy, privoxy/Tor, etc. Localhost calls bypass. Requires Bun runtime; SOCKS5 not supported. Full provider matrix + setup in [`vpn-routing.md`](./vpn-routing.md). (v3.35) | unset |
|
|
62
|
-
| `DARIO_API_KEY` | If set, all endpoints (except `/health`) require a matching `x-api-key` or `Authorization: Bearer` header. Required when `--host` binds non-loopback. | unset (open) |
|
|
63
|
-
| `DARIO_CORS_ORIGIN` |
|
|
60
|
+
| `DARIO_API_KEY` | If set, all endpoints (except `/health`) require a matching `x-api-key` or `Authorization: Bearer` header. Required when `--host` binds non-loopback. Unset, every request must name dario by `localhost`, a `*.localhost` name, an IP address, the `--host` address or the `DARIO_CORS_ORIGIN` host (DNS rebinding). | unset (open) |
|
|
61
|
+
| `DARIO_CORS_ORIGIN` | The one browser origin besides dario's own that it serves: the CORS `Access-Control-Allow-Origin`, and the only other origin whose POSTs are not refused as cross-origin. Set it for a web UI or a browser extension that calls dario directly (`chrome-extension://<id>` works). Without `DARIO_API_KEY`, its host is also a name dario may be reached by. | `http://localhost:${port}` |
|
|
64
62
|
| `DARIO_QUIET_TLS` | Suppress the runtime/TLS mismatch startup banner | unset |
|
|
65
63
|
| `DARIO_NO_BUN` | Disable automatic Bun relaunch | unset |
|
|
66
64
|
| `DARIO_MIN_INTERVAL_MS` | Legacy name for `DARIO_PACE_MIN_MS`. Still honored; new name wins when both are set. | — |
|
package/docs/docker.md
CHANGED
|
@@ -106,7 +106,7 @@ All flags have env-var equivalents. The image sets sensible container defaults:
|
|
|
106
106
|
| `DARIO_HOST` | `0.0.0.0` | Bind address (image flips from `127.0.0.1`) |
|
|
107
107
|
| `DARIO_PORT` | `3456` | Listen port |
|
|
108
108
|
| `DARIO_API_KEY` | unset (**required**) | Required because of the `0.0.0.0` bind — see "Why an API key is mandatory" |
|
|
109
|
-
| `DARIO_CORS_ORIGIN` | unset |
|
|
109
|
+
| `DARIO_CORS_ORIGIN` | unset | The browser origin to serve besides dario's own (CORS and the cross-origin refusal); default `http://localhost:<port>` |
|
|
110
110
|
| `DARIO_LOG_FILE` | unset | Path inside the container (mount a volume) |
|
|
111
111
|
| `DARIO_LOG_BODIES` | unset | `1` to log request/response bodies |
|
|
112
112
|
| `DARIO_CACHE_TRACE` | unset | `1` to log one cache-trace line per ChatGPT (codex) request, see [`docs/analytics.md`](./analytics.md#the-cache-trace) |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@askalf/dario",
|
|
3
|
-
"version": "6.18.
|
|
3
|
+
"version": "6.18.3",
|
|
4
4
|
"description": "Use your Claude and ChatGPT subscriptions in Cursor, Cline, Aider, Claude Code and the Agent SDK at subscription pricing, not per-token API bills. One local Anthropic + OpenAI-compatible endpoint: either plan answers either wire shape, opt-in failover when one hits its limit, and a ledger of what each plan absorbed.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|