dsh-free-model 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +227 -2
- package/README_EN.md +241 -0
- package/SECURITY-AUDIT.md +119 -0
- package/client.js +2531 -0
- package/cordis.patch.yml +8 -0
- package/icon.svg +1 -0
- package/index.js +684 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +67 -4
- package/src/chan-relay.js +193 -0
- package/src/egress.js +793 -0
- package/src/key.js +24 -0
- package/src/store.js +166 -0
- package/src/trust.js +179 -0
- package/vendor/channel-pack/LICENSE +21 -0
- package/vendor/channel-pack/NOTICE.md +94 -0
- package/vendor/channel-pack/pack.js +73153 -0
- package/vendor/channel-pack/qoder-auth-wasm.wasm +0 -0
package/index.js
ADDED
|
@@ -0,0 +1,684 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Our Free Model — plugin entry (Host half), channels-only fork.
|
|
3
|
+
*
|
|
4
|
+
* Upstream 2.1.0 shipped nine settings pages behind one host: an anonymous free
|
|
5
|
+
* lane (opencode.ai), a Kilo free pool, the GitHub-gated EAC co-paid lane, a
|
|
6
|
+
* 76-provider aggregate lane with bring-your-own keys, named fallback chains
|
|
7
|
+
* (combos), a token-saving pipeline that runs inside that one adapter, a
|
|
8
|
+
* first-run announcement feed, a remote-published self-updater and a hot reload.
|
|
9
|
+
*
|
|
10
|
+
* This fork keeps exactly one of them: the absorbed channel pack
|
|
11
|
+
* (`vendor/channel-pack`), which carries the fourteen 白嫖 account providers
|
|
12
|
+
* (CodeArts, CodeBuddy / WorkBuddy, LobsterAI, Qoder / Qoder CN, TRAE, Cline,
|
|
13
|
+
* Loomy, Raccoon, MiniMax Code, ZCode, Gemini) and their OpenAI-compatible
|
|
14
|
+
* loopback gateway. Everything that hung off the plugin's own model adapter is
|
|
15
|
+
* gone, together with its routes, stores, timers and files.
|
|
16
|
+
*
|
|
17
|
+
* What this half still owns:
|
|
18
|
+
* - the settings file (`egress`, `chanGateway.relay`);
|
|
19
|
+
* - the egress outlet the pack sends its traffic through;
|
|
20
|
+
* - the pack's gateway relay — this plugin's own key, LAN-optional;
|
|
21
|
+
* - the JSON API the four remaining settings pages read
|
|
22
|
+
* (白嫖模型接入 / 数据看板 / 运行日志 / 网关设置).
|
|
23
|
+
*
|
|
24
|
+
* The dashboard and the request log do not come from here: the pack keeps its
|
|
25
|
+
* own per-request token ledger and serves it over the shell's `connection` RPC,
|
|
26
|
+
* so nothing in this half has to measure a turn.
|
|
27
|
+
*
|
|
28
|
+
* `llm` stays the only declared dependency. The pack mounts onto
|
|
29
|
+
* `credentials`/`commands`/`llm` in a nested fiber of its own, so a composition
|
|
30
|
+
* without a web server still serves models, and a composition that omits the
|
|
31
|
+
* pack's services degrades to "no channels" instead of failing the plugin.
|
|
32
|
+
*
|
|
33
|
+
* @module index.js
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import fs from 'node:fs'
|
|
37
|
+
import path from 'node:path'
|
|
38
|
+
import { fileURLToPath } from 'node:url'
|
|
39
|
+
import { DATA_DIR_NAME, JsonStore, SETTINGS_INITIAL, resolveDshHome } from './src/store.js'
|
|
40
|
+
import { generateKey } from './src/key.js'
|
|
41
|
+
import { chanGatewayCredential, chanGatewayEnabled, chanGatewayPort, startChanRelay } from './src/chan-relay.js'
|
|
42
|
+
import { egressActive, egressFetch, outletLabel, readOutletSelection, startEgressRelay } from './src/egress.js'
|
|
43
|
+
import { connectionAdmissionView, rejectionFor } from './src/trust.js'
|
|
44
|
+
|
|
45
|
+
export const name = 'our-free-model'
|
|
46
|
+
|
|
47
|
+
/** The installed package directory, read once so `/summary` can name it. */
|
|
48
|
+
const PKG_DIR = fileURLToPath(new URL('./', import.meta.url))
|
|
49
|
+
|
|
50
|
+
/** Published version of the installed package, read once at load. */
|
|
51
|
+
function readPackageVersion() {
|
|
52
|
+
try {
|
|
53
|
+
return String(JSON.parse(fs.readFileSync(path.join(PKG_DIR, 'package.json'), 'utf8')).version ?? '')
|
|
54
|
+
} catch {
|
|
55
|
+
return ''
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export const version = readPackageVersion()
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* `llm` is what the plugin exists for, so it is the only hard requirement of the
|
|
63
|
+
* plugin itself.
|
|
64
|
+
*
|
|
65
|
+
* Cordis withholds from a context any service its fiber does not name in
|
|
66
|
+
* `inject`, and keeps that fiber PENDING while a named one is absent — which is
|
|
67
|
+
* how v1.2.1 stayed permanently inactive on a composition with no HTTP server
|
|
68
|
+
* (upstream issue #4). So nothing else may be named here: a headless
|
|
69
|
+
* composition would rather serve channels without a settings page than serve
|
|
70
|
+
* nothing.
|
|
71
|
+
*
|
|
72
|
+
* What that costs and what still works:
|
|
73
|
+
* - `webServer` — the four in-app pages. Reached through a nested `ctx.inject`
|
|
74
|
+
* fiber (see the browser-facing API section), which pends on its own and
|
|
75
|
+
* never blocks the pack above.
|
|
76
|
+
* - `timer` (`ctx.interval`) — nothing. The one background loop below is a
|
|
77
|
+
* plain unref'd timer, because reading a mixin off an undeclared service
|
|
78
|
+
* throws rather than answering `undefined`.
|
|
79
|
+
* - `connection` — the fence falls back to its structural replica.
|
|
80
|
+
*/
|
|
81
|
+
export const inject = ['llm']
|
|
82
|
+
|
|
83
|
+
export function apply(ctx) {
|
|
84
|
+
const logger = ctx.logger ?? console
|
|
85
|
+
const dataDir = path.resolve(resolveDshHome(), DATA_DIR_NAME)
|
|
86
|
+
fs.mkdirSync(dataDir, { recursive: true })
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The only durable state this fork keeps.
|
|
90
|
+
*
|
|
91
|
+
* Upstream's `stats.json`, `availability.json` and `catalog.json` are gone
|
|
92
|
+
* with the lane that filled them; a `settings.json` written by 2.1.0 still
|
|
93
|
+
* carries those keys, and `JsonStore.load` merges the file over the defaults,
|
|
94
|
+
* so they survive as inert extras rather than being rewritten under the user.
|
|
95
|
+
*/
|
|
96
|
+
const settings = new JsonStore(path.join(dataDir, 'settings.json'), structuredClone(SETTINGS_INITIAL), {
|
|
97
|
+
log: message => logger.warn?.(message),
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Read a service the composition may or may not mount.
|
|
102
|
+
*
|
|
103
|
+
* `ctx.get` is cordis' opportunistic lookup: it answers `undefined` instead of
|
|
104
|
+
* throwing when the service is absent — and also while it is merely not
|
|
105
|
+
* provided yet, which matters because plugins load before the browser half has
|
|
106
|
+
* published anything. So a service read this way is a snapshot: `connection`
|
|
107
|
+
* is therefore resolved per request (see `fenceConnection` below).
|
|
108
|
+
*/
|
|
109
|
+
const optional = service => (typeof ctx.get === 'function' ? ctx.get(service) : undefined)
|
|
110
|
+
/**
|
|
111
|
+
* The trust fence's view of the connection service, looked up per request.
|
|
112
|
+
*
|
|
113
|
+
* The browser half publishes `connection` after plugins have loaded, so reading
|
|
114
|
+
* it once here would freeze in "absent" and leave every request on the replica
|
|
115
|
+
* fence for the life of the process. The view takes the service *thunk* rather
|
|
116
|
+
* than the service, and its `admit` answers `undefined` — not a no-op function
|
|
117
|
+
* — while the service is missing, which is what makes the fence fall through to
|
|
118
|
+
* its own structural check instead of reading as "admitted".
|
|
119
|
+
*/
|
|
120
|
+
const fenceConnection = connectionAdmissionView(() => optional('connection'))
|
|
121
|
+
|
|
122
|
+
/** Set when this generation is disposed; late async callbacks must stand down. */
|
|
123
|
+
let disposed = false
|
|
124
|
+
/** The optional egress outlet (subscription or single client), off by default. */
|
|
125
|
+
let outletRelay = null
|
|
126
|
+
let outletError = ''
|
|
127
|
+
/** Last reading of the outlet's own view of itself, cached for `/summary`. */
|
|
128
|
+
let outletNode = { node: '', delayMs: 0, at: 0 }
|
|
129
|
+
|
|
130
|
+
// ── the absorbed channel pack ───────────────────────────────────────────────
|
|
131
|
+
/**
|
|
132
|
+
* The 白嫖 channels — CodeArts (华为云), CodeBuddy / WorkBuddy (腾讯), LobsterAI
|
|
133
|
+
* (有道), Qoder / Qoder CN (阿里系), TRAE (字节), Cline, Loomy (讯飞), Raccoon
|
|
134
|
+
* (商汤), MiniMax Code, ZCode (智谱) and Gemini (Google) — are carried with
|
|
135
|
+
* local integration adaptations from the plugin that shipped them, vendored
|
|
136
|
+
* under `vendor/channel-pack` (provenance in `vendor/channel-pack/NOTICE.md`).
|
|
137
|
+
* Mounting the pack keeps every login flow, account pool, credit claim, model
|
|
138
|
+
* blacklist and its local OpenAI gateway working as validated upstream,
|
|
139
|
+
* instead of being re-implemented here and drifting.
|
|
140
|
+
*
|
|
141
|
+
* The pack runs on a fiber of its own, after `credentials`, `commands` and
|
|
142
|
+
* `llm` exist. `channelPack` is the state bit `/summary` reports so the page
|
|
143
|
+
* can say *why* the channel list is empty instead of showing nothing.
|
|
144
|
+
*/
|
|
145
|
+
let channelPack = { state: 'pending', error: '' }
|
|
146
|
+
ctx.inject(['credentials', 'commands', 'llm'], scoped => {
|
|
147
|
+
let stopped = false
|
|
148
|
+
scoped.effect(() => () => { stopped = true }, 'our-free-model: channel pack')
|
|
149
|
+
// Dynamic import: the pack's own imports (the kernel's llm and credential
|
|
150
|
+
// modules) are host-provided, and a composition that lacks them must still
|
|
151
|
+
// load this plugin. `pack.js` is the bundled form of the vendored tree (see
|
|
152
|
+
// scripts/build-channel-pack.mjs) — one file, so the release artifact stays
|
|
153
|
+
// inside its file cap.
|
|
154
|
+
void import('./vendor/channel-pack/pack.js').then(pack => {
|
|
155
|
+
if (stopped) return
|
|
156
|
+
pack.apply(scoped, {
|
|
157
|
+
// The anonymous OpenCode lane belonged to upstream's free lane, which
|
|
158
|
+
// this fork removed: the pack must not quietly re-introduce it.
|
|
159
|
+
disableOpencode: true,
|
|
160
|
+
outlet: { active: egressActive, fetch: egressFetch },
|
|
161
|
+
})
|
|
162
|
+
channelPack = { state: 'ready', error: '' }
|
|
163
|
+
logger.info?.('our-free-model: channel pack mounted (CodeArts, CodeBuddy, and 11 more)')
|
|
164
|
+
}).catch(error => {
|
|
165
|
+
if (stopped) return
|
|
166
|
+
channelPack = { state: 'failed', error: String(error?.message ?? error).slice(0, 300) }
|
|
167
|
+
logger.warn?.(`our-free-model: channel pack unavailable (${channelPack.error})`)
|
|
168
|
+
})
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
// ── the channels' gateway relay ─────────────────────────────────────────────
|
|
172
|
+
/**
|
|
173
|
+
* The absorbed pack serves every 白嫖 provider through one OpenAI-compatible
|
|
174
|
+
* gateway on the loopback. The relay is this plugin's own door in front of
|
|
175
|
+
* it: callers authenticate with `chanGateway.relay.key` and the forwarded
|
|
176
|
+
* hop is re-stamped with the gateway's own credential, which never leaves
|
|
177
|
+
* the host. Off until asked for; the settings page owns the switch.
|
|
178
|
+
*/
|
|
179
|
+
let chanRelay = null
|
|
180
|
+
let chanRelayError = ''
|
|
181
|
+
let chanRelaySyncInFlight = null
|
|
182
|
+
|
|
183
|
+
function chanRelayKey() {
|
|
184
|
+
const relay = settings.get().chanGateway?.relay ?? {}
|
|
185
|
+
if (typeof relay.key === 'string' && relay.key !== '') return relay.key
|
|
186
|
+
const minted = generateKey()
|
|
187
|
+
settings.update({ chanGateway: { ...(settings.get().chanGateway ?? {}), relay: { ...(settings.get().chanGateway?.relay ?? {}), key: minted } } })
|
|
188
|
+
settings.flush()
|
|
189
|
+
return minted
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function rotateChanRelayKey() {
|
|
193
|
+
const minted = generateKey()
|
|
194
|
+
settings.update({ chanGateway: { ...(settings.get().chanGateway ?? {}), relay: { ...(settings.get().chanGateway?.relay ?? {}), key: minted } } })
|
|
195
|
+
settings.flush()
|
|
196
|
+
return minted
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** The gateway's address and credential, read fresh: both can move (env). */
|
|
200
|
+
function chanGatewayTarget() {
|
|
201
|
+
return {
|
|
202
|
+
port: chanGatewayPort(process.env),
|
|
203
|
+
enabledByEnv: chanGatewayEnabled(process.env),
|
|
204
|
+
credential: chanGatewayCredential({ profileContext: optional('profileContext'), env: process.env }),
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function syncChanRelay() {
|
|
209
|
+
while (chanRelaySyncInFlight !== null) await chanRelaySyncInFlight.catch(() => {})
|
|
210
|
+
const run = syncChanRelayOnce()
|
|
211
|
+
chanRelaySyncInFlight = run
|
|
212
|
+
try { await run } finally { if (chanRelaySyncInFlight === run) chanRelaySyncInFlight = null }
|
|
213
|
+
}
|
|
214
|
+
async function syncChanRelayOnce() {
|
|
215
|
+
const relay = settings.get().chanGateway?.relay ?? {}
|
|
216
|
+
const wanted = relay.enabled === true
|
|
217
|
+
const host = String(relay.host ?? '').trim() || '127.0.0.1'
|
|
218
|
+
const port = Number.isFinite(Number(relay.port)) && Number(relay.port) > 0 ? Math.trunc(Number(relay.port)) : 0
|
|
219
|
+
const target = chanGatewayTarget()
|
|
220
|
+
if (chanRelay !== null && wanted && chanRelay.host === host && chanRelay.port === port) return
|
|
221
|
+
if (chanRelay === null && !wanted) return
|
|
222
|
+
if (chanRelay !== null) {
|
|
223
|
+
const closing = chanRelay
|
|
224
|
+
chanRelay = null
|
|
225
|
+
await closing.close().catch(() => {})
|
|
226
|
+
}
|
|
227
|
+
if (!wanted) { chanRelayError = ''; return }
|
|
228
|
+
if (port !== 0 && target.port === port) {
|
|
229
|
+
chanRelayError = 'the relay needs a port of its own (the gateway listens on ' + target.port + ')'
|
|
230
|
+
logger.warn?.(`our-free-model: channel gateway relay not started (${chanRelayError})`)
|
|
231
|
+
return
|
|
232
|
+
}
|
|
233
|
+
try {
|
|
234
|
+
chanRelay = await startChanRelay({
|
|
235
|
+
config: () => {
|
|
236
|
+
const current = settings.get().chanGateway?.relay ?? {}
|
|
237
|
+
const targetNow = chanGatewayTarget()
|
|
238
|
+
return {
|
|
239
|
+
enabled: current.enabled === true,
|
|
240
|
+
host: String(current.host ?? '').trim() || '127.0.0.1',
|
|
241
|
+
port: current.port ?? 0,
|
|
242
|
+
lanKey: chanRelayKey(),
|
|
243
|
+
gatewayHost: '127.0.0.1',
|
|
244
|
+
gatewayPort: targetNow.port,
|
|
245
|
+
gatewayKey: targetNow.credential?.key ?? '',
|
|
246
|
+
}
|
|
247
|
+
},
|
|
248
|
+
log: message => logger.warn?.(`our-free-model channel relay: ${message}`),
|
|
249
|
+
})
|
|
250
|
+
chanRelayError = ''
|
|
251
|
+
// The bound port goes back into the settings, so the page shows the
|
|
252
|
+
// address that actually answers (the OS picks when 0 was asked for).
|
|
253
|
+
const settled = settings.get().chanGateway ?? {}
|
|
254
|
+
settings.update({ chanGateway: { ...settled, relay: { ...(settled.relay ?? {}), port: chanRelay.port } } })
|
|
255
|
+
settings.flush()
|
|
256
|
+
} catch (error) {
|
|
257
|
+
chanRelayError = String(error?.message ?? error)
|
|
258
|
+
logger.warn?.(`our-free-model: channel gateway relay could not start (${chanRelayError})`)
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function chanRelayStatus() {
|
|
263
|
+
const relay = settings.get().chanGateway?.relay ?? {}
|
|
264
|
+
const target = chanGatewayTarget()
|
|
265
|
+
return {
|
|
266
|
+
relay: {
|
|
267
|
+
enabled: relay.enabled === true,
|
|
268
|
+
running: chanRelay !== null,
|
|
269
|
+
host: chanRelay?.host ?? (String(relay.host ?? '').trim() || '127.0.0.1'),
|
|
270
|
+
port: chanRelay?.port ?? relay.port ?? 0,
|
|
271
|
+
hasKey: typeof relay.key === 'string' && relay.key !== '',
|
|
272
|
+
error: chanRelayError,
|
|
273
|
+
},
|
|
274
|
+
gateway: {
|
|
275
|
+
port: target.port,
|
|
276
|
+
enabledByEnv: target.enabledByEnv,
|
|
277
|
+
keyFound: target.credential !== null,
|
|
278
|
+
keyFromEnv: target.credential?.fromEnv === true,
|
|
279
|
+
keyPath: target.credential?.path ?? '',
|
|
280
|
+
},
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
// ── egress outlet ───────────────────────────────────────────────────────────
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Which node the outlet is carrying traffic on. Purely informational: every
|
|
289
|
+
* failure is a missing reading, never an error, because the outlet itself may
|
|
290
|
+
* be perfectly healthy while the controller call that describes it is not.
|
|
291
|
+
*/
|
|
292
|
+
async function readOutletStatus() {
|
|
293
|
+
const relay = outletRelay
|
|
294
|
+
if (relay === null) {
|
|
295
|
+
outletNode = { node: '', delayMs: 0, at: 0 }
|
|
296
|
+
return { node: '', nodeDelayMs: 0, nodeAt: 0 }
|
|
297
|
+
}
|
|
298
|
+
const selection = await readOutletSelection(relay).catch(() => null)
|
|
299
|
+
// A settled read is cached for `/summary`, which cannot await a round trip.
|
|
300
|
+
if (outletRelay === relay) {
|
|
301
|
+
outletNode = { node: selection?.node ?? '', delayMs: selection?.delayMs ?? 0, at: Date.now() }
|
|
302
|
+
}
|
|
303
|
+
return {
|
|
304
|
+
node: selection?.node ?? '',
|
|
305
|
+
nodeDelayMs: selection?.delayMs ?? 0,
|
|
306
|
+
nodeAt: Date.now(),
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
// Same serialisation gate as the two listeners above: the boot chain and every
|
|
310
|
+
// settings POST call this, and overlapping runs would leak a spawned mihomo
|
|
311
|
+
// (the loser overwrites `outletRelay` while the winner's child still runs).
|
|
312
|
+
let outletSyncInFlight = null
|
|
313
|
+
/** What the currently running outlet was started with — restart on change. */
|
|
314
|
+
let outletFingerprint = ''
|
|
315
|
+
async function syncEgress() {
|
|
316
|
+
while (outletSyncInFlight !== null) await outletSyncInFlight.catch(() => {})
|
|
317
|
+
const run = syncEgressOnce()
|
|
318
|
+
outletSyncInFlight = run
|
|
319
|
+
try { await run } finally { if (outletSyncInFlight === run) outletSyncInFlight = null }
|
|
320
|
+
}
|
|
321
|
+
async function syncEgressOnce() {
|
|
322
|
+
const desired = settings.get().egress ?? {}
|
|
323
|
+
const wanted = desired.enabled === true
|
|
324
|
+
const mode = desired.mode === 'client' ? 'client' : 'subscription'
|
|
325
|
+
const url = String(desired.url ?? '').trim()
|
|
326
|
+
const mihomoPath = String(desired.mihomoPath ?? '').trim()
|
|
327
|
+
const fingerprint = `${mode}\n${url}\n${mihomoPath}`
|
|
328
|
+
if (outletRelay !== null && wanted && outletFingerprint === fingerprint && !outletRelay.dead) return
|
|
329
|
+
if (outletRelay === null && !wanted) return
|
|
330
|
+
if (outletRelay !== null) {
|
|
331
|
+
const closing = outletRelay
|
|
332
|
+
outletRelay = null
|
|
333
|
+
outletFingerprint = ''
|
|
334
|
+
await closing.close().catch(() => {})
|
|
335
|
+
}
|
|
336
|
+
if (!wanted) {
|
|
337
|
+
outletError = ''
|
|
338
|
+
return
|
|
339
|
+
}
|
|
340
|
+
if (url === '') {
|
|
341
|
+
outletError = 'the outlet needs a subscription or proxy URL'
|
|
342
|
+
logger.warn?.(`our-free-model: egress outlet not started (${outletError})`)
|
|
343
|
+
return
|
|
344
|
+
}
|
|
345
|
+
try {
|
|
346
|
+
outletRelay = await startEgressRelay({
|
|
347
|
+
config: () => {
|
|
348
|
+
const current = settings.get().egress ?? {}
|
|
349
|
+
return {
|
|
350
|
+
mode: current.mode === 'client' ? 'client' : 'subscription',
|
|
351
|
+
url: String(current.url ?? '').trim(),
|
|
352
|
+
mihomoPath: String(current.mihomoPath ?? '').trim(),
|
|
353
|
+
}
|
|
354
|
+
},
|
|
355
|
+
dataDir,
|
|
356
|
+
log: message => logger.info?.(`our-free-model egress: ${message}`),
|
|
357
|
+
onDead: scheduleOutletRestart,
|
|
358
|
+
})
|
|
359
|
+
outletFingerprint = fingerprint
|
|
360
|
+
outletError = ''
|
|
361
|
+
outletUpSince = Date.now()
|
|
362
|
+
logger.info?.(`our-free-model: egress outlet up (${outletLabel(url)} via ${mode})`)
|
|
363
|
+
} catch (error) {
|
|
364
|
+
outletError = String(error?.message ?? error)
|
|
365
|
+
logger.warn?.(`our-free-model: egress outlet could not start (${outletError})`)
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// A managed mihomo that dies mid-run used to leave the outlet bricked until
|
|
370
|
+
// the user touched the settings page: the relay stays up but its dial port is
|
|
371
|
+
// gone, so every upstream turn fails. syncEgressOnce already restarts a dead
|
|
372
|
+
// relay with an unchanged fingerprint — this only calls it, with a backoff so
|
|
373
|
+
// a mihomo that dies at boot cannot spin into a start/exit loop. A run that
|
|
374
|
+
// lasted two minutes counts as healthy and resets the ladder.
|
|
375
|
+
const OUTLET_STABLE_MS = 120_000
|
|
376
|
+
let outletUpSince = 0
|
|
377
|
+
let outletRestartAttempts = 0
|
|
378
|
+
let outletRestartTimer = null
|
|
379
|
+
function scheduleOutletRestart() {
|
|
380
|
+
if (outletRestartTimer !== null) return
|
|
381
|
+
if (Date.now() - outletUpSince >= OUTLET_STABLE_MS) outletRestartAttempts = 0
|
|
382
|
+
const delay = Math.min(15_000 * 2 ** outletRestartAttempts, 600_000)
|
|
383
|
+
outletRestartAttempts += 1
|
|
384
|
+
logger.warn?.(`our-free-model: egress outlet went down; restarting in ${Math.round(delay / 1000)}s (attempt ${outletRestartAttempts})`)
|
|
385
|
+
outletRestartTimer = setTimeout(() => {
|
|
386
|
+
outletRestartTimer = null
|
|
387
|
+
void syncEgress().catch(() => {})
|
|
388
|
+
}, delay)
|
|
389
|
+
outletRestartTimer.unref?.()
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// ── browser-facing API ──────────────────────────────────────────────────────
|
|
393
|
+
const logAdmissionRejection = surface => ({ status, source, reason }) => {
|
|
394
|
+
// Fixed fields only: headers, request URLs and admission errors may contain
|
|
395
|
+
// credentials. Every surface reports the same admission boundary.
|
|
396
|
+
logger.warn?.(`our-free-model: ${surface} admission rejected status=${status} source=${source} reason=${reason}`)
|
|
397
|
+
}
|
|
398
|
+
const api = createApiRoutes({
|
|
399
|
+
settings,
|
|
400
|
+
version,
|
|
401
|
+
// The absorbed channel pack's liveness, for the 白嫖接入 page: the page
|
|
402
|
+
// renders its channel grid from this bit plus the pack's own RPC.
|
|
403
|
+
channels: () => channelPack,
|
|
404
|
+
chanRelay: {
|
|
405
|
+
status: chanRelayStatus,
|
|
406
|
+
apply: async patch => {
|
|
407
|
+
const current = settings.get().chanGateway ?? {}
|
|
408
|
+
const relay = { ...(current.relay ?? {}) }
|
|
409
|
+
if (patch === null || typeof patch !== 'object') throw httpError(400, 'the request body must be a JSON object')
|
|
410
|
+
if (patch.enabled !== undefined) relay.enabled = patch.enabled === true
|
|
411
|
+
if (patch.host !== undefined) {
|
|
412
|
+
const host = String(patch.host ?? '').trim()
|
|
413
|
+
if (host !== '' && host !== '127.0.0.1' && host !== 'localhost' && host !== '0.0.0.0' && host !== '::') {
|
|
414
|
+
throw httpError(400, 'host must be one of 127.0.0.1, localhost, 0.0.0.0, ::')
|
|
415
|
+
}
|
|
416
|
+
relay.host = host === 'localhost' ? '127.0.0.1' : host
|
|
417
|
+
}
|
|
418
|
+
if (patch.port !== undefined) {
|
|
419
|
+
const port = Number(patch.port)
|
|
420
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) throw httpError(400, 'port must be an integer between 0 and 65535')
|
|
421
|
+
relay.port = port
|
|
422
|
+
}
|
|
423
|
+
settings.update({ chanGateway: { ...current, relay } })
|
|
424
|
+
settings.flush()
|
|
425
|
+
await syncChanRelay()
|
|
426
|
+
return chanRelayStatus()
|
|
427
|
+
},
|
|
428
|
+
key: () => chanRelayKey(),
|
|
429
|
+
rotate: rotateChanRelayKey,
|
|
430
|
+
},
|
|
431
|
+
// The subscription URL is a credential: only its masked label ever leaves
|
|
432
|
+
// this process. `active` mirrors what egressFetch is actually doing right
|
|
433
|
+
// now (direct until the relay finishes starting, direct again once closed).
|
|
434
|
+
egressInfo: () => ({
|
|
435
|
+
running: outletRelay !== null,
|
|
436
|
+
active: outletRelay !== null,
|
|
437
|
+
mode: outletRelay?.mode ?? '',
|
|
438
|
+
outlet: outletRelay === null ? '' : outletLabel(outletRelay.url ?? ''),
|
|
439
|
+
// Cached readings: `/summary` is synchronous, so the live controller call
|
|
440
|
+
// lives in `outletStatus` and only the last answer is echoed here.
|
|
441
|
+
node: outletNode.node,
|
|
442
|
+
nodeDelayMs: outletNode.delayMs,
|
|
443
|
+
nodeAt: outletNode.at,
|
|
444
|
+
// `dead` is the managed mihomo dying after startup — surfaced through the
|
|
445
|
+
// same field so the settings page shows why traffic fell back to direct.
|
|
446
|
+
error: outletError !== '' ? outletError : (outletRelay?.dead ?? ''),
|
|
447
|
+
}),
|
|
448
|
+
// The settings page polls this while the outlet is on: which node url-test is
|
|
449
|
+
// carrying traffic on is mihomo's own state, and it changes without anything
|
|
450
|
+
// else in this process moving.
|
|
451
|
+
outletStatus: () => readOutletStatus(),
|
|
452
|
+
syncEgress,
|
|
453
|
+
dataDir,
|
|
454
|
+
connection: fenceConnection,
|
|
455
|
+
onAdmissionRejection: logAdmissionRejection('settings API'),
|
|
456
|
+
logger,
|
|
457
|
+
})
|
|
458
|
+
|
|
459
|
+
// The dashboard half runs in its own fiber so that a composition without an
|
|
460
|
+
// HTTP server cannot take the channels down with it.
|
|
461
|
+
//
|
|
462
|
+
// `ctx.inject(deps, callback)` is cordis' "run this once these services exist":
|
|
463
|
+
// the callback pends while `webServer` is absent *or merely not provided yet*,
|
|
464
|
+
// and is re-run if the service is replaced. That pending is the whole point —
|
|
465
|
+
// reading `ctx.get('webServer')` once at apply time answered `undefined` in the
|
|
466
|
+
// real web composition (plugins load before the browser half publishes it), the
|
|
467
|
+
// routes never registered, and the settings page had no data source while a web
|
|
468
|
+
// server was busy serving it.
|
|
469
|
+
ctx.inject(['webServer'], scoped => {
|
|
470
|
+
const server = scoped.webServer
|
|
471
|
+
scoped.effect(() => server.register({ kind: 'prefix', path: '/api/our-free-model', handler: api }), 'our-free-model: api routes')
|
|
472
|
+
logger.info?.('our-free-model: settings API mounted at /api/our-free-model')
|
|
473
|
+
})
|
|
474
|
+
|
|
475
|
+
// ── boot + teardown ─────────────────────────────────────────────────────────
|
|
476
|
+
ctx.effect(() => () => {
|
|
477
|
+
void chanRelay?.close().catch(() => {})
|
|
478
|
+
void outletRelay?.close().catch(() => {})
|
|
479
|
+
}, 'our-free-model: local listeners')
|
|
480
|
+
|
|
481
|
+
ctx.effect(() => () => {
|
|
482
|
+
disposed = true
|
|
483
|
+
settings.dispose()
|
|
484
|
+
}, 'our-free-model: settings store')
|
|
485
|
+
|
|
486
|
+
ctx.effect(() => {
|
|
487
|
+
void (async () => {
|
|
488
|
+
// The outlet first: the pack's requests go through egressFetch, so the exit
|
|
489
|
+
// must be carrying traffic before anything else in this process goes out.
|
|
490
|
+
await syncEgress()
|
|
491
|
+
if (disposed) return
|
|
492
|
+
await syncChanRelay()
|
|
493
|
+
if (disposed) return
|
|
494
|
+
await readOutletStatus().catch(() => {})
|
|
495
|
+
})().catch(error => logger.warn?.(`our-free-model: startup failed (${error?.message ?? error})`))
|
|
496
|
+
}, 'our-free-model: boot')
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* Keep `/summary`'s cached outlet reading fresh.
|
|
500
|
+
*
|
|
501
|
+
* The panel polls `/outlet` itself while it is open; this loop exists for the
|
|
502
|
+
* case where nothing is open and the next mount must not render yesterday's
|
|
503
|
+
* node. One unref'd timer, re-armed after each read, on purpose: `ctx.interval`
|
|
504
|
+
* is a mixin over the undeclared `timer` service and reading it throws.
|
|
505
|
+
*/
|
|
506
|
+
let outletTimer = null
|
|
507
|
+
ctx.effect(() => {
|
|
508
|
+
const arm = () => {
|
|
509
|
+
outletTimer = setTimeout(() => {
|
|
510
|
+
if (disposed) return
|
|
511
|
+
if (outletRelay === null) { arm(); return }
|
|
512
|
+
void readOutletStatus().catch(() => {}).finally(arm)
|
|
513
|
+
}, 120_000)
|
|
514
|
+
outletTimer.unref?.()
|
|
515
|
+
}
|
|
516
|
+
arm()
|
|
517
|
+
return () => clearTimeout(outletTimer)
|
|
518
|
+
}, 'our-free-model: outlet reading')
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// ── helpers ─────────────────────────────────────────────────────────────────
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* An error the settings API presents with its own status line, not a bare 500.
|
|
525
|
+
* Used where a refusal is the *correct* answer, so the page can say why instead
|
|
526
|
+
* of blaming a fault.
|
|
527
|
+
*/
|
|
528
|
+
function httpError(statusCode, message) {
|
|
529
|
+
const error = new Error(message)
|
|
530
|
+
error.statusCode = statusCode
|
|
531
|
+
return error
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function pick(source, keys) {
|
|
535
|
+
const out = {}
|
|
536
|
+
for (const key of keys) if (source?.[key] !== undefined) out[key] = source[key]
|
|
537
|
+
return out
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/** The most a browser-API request body may weigh. The settings patch is the
|
|
541
|
+
* largest real payload here; without a cap, any caller past the fence could
|
|
542
|
+
* buffer unbounded bytes into the host process. */
|
|
543
|
+
const MAX_API_BODY_BYTES = 1024 * 1024
|
|
544
|
+
|
|
545
|
+
async function readJson(req) {
|
|
546
|
+
const chunks = []
|
|
547
|
+
let size = 0
|
|
548
|
+
for await (const chunk of req) {
|
|
549
|
+
size += chunk.length
|
|
550
|
+
if (size > MAX_API_BODY_BYTES) throw httpError(413, 'request body too large')
|
|
551
|
+
chunks.push(chunk)
|
|
552
|
+
}
|
|
553
|
+
if (chunks.length === 0) return {}
|
|
554
|
+
const text = Buffer.concat(chunks).toString('utf8')
|
|
555
|
+
try { return JSON.parse(text) } catch (error) {
|
|
556
|
+
// A body that was sent but is not JSON is a client bug, not "no body":
|
|
557
|
+
// answering {} made POST /settings a silent 200 no-op. Empty bodies stay
|
|
558
|
+
// legal ({} above) because no-body POSTs are real routes here.
|
|
559
|
+
throw httpError(400, `invalid JSON body (${error?.message ?? error})`)
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
function publicSettings(settings, egressInfo) {
|
|
564
|
+
return {
|
|
565
|
+
// A subscription link is not an endpoint, it is a bearer credential: the
|
|
566
|
+
// path of the URL *is* the token. Stored as given, but never echoed —
|
|
567
|
+
// `urlLabel` is the masked host for the panel, `hasUrl` says whether one is
|
|
568
|
+
// set at all, and the value itself is served only by `GET /egress/url`, on
|
|
569
|
+
// the settings page's own ask (see src/egress.js `outletLabel`).
|
|
570
|
+
egress: {
|
|
571
|
+
...pick(settings.egress ?? {}, ['enabled', 'mode', 'mihomoPath']),
|
|
572
|
+
hasUrl: String(settings.egress?.url ?? '') !== '',
|
|
573
|
+
urlLabel: outletLabel(settings.egress?.url ?? ''),
|
|
574
|
+
outlet: egressInfo?.outlet ?? '',
|
|
575
|
+
running: egressInfo?.running === true,
|
|
576
|
+
active: egressInfo?.active === true,
|
|
577
|
+
// The node url-test is carrying traffic on, and its last measured delay.
|
|
578
|
+
// Both are readings, not state.
|
|
579
|
+
node: egressInfo?.node ?? '',
|
|
580
|
+
nodeDelayMs: egressInfo?.nodeDelayMs ?? 0,
|
|
581
|
+
error: egressInfo?.error ?? '',
|
|
582
|
+
},
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
function buildSummary(deps) {
|
|
587
|
+
return {
|
|
588
|
+
settings: publicSettings(deps.settings.get(), deps.egressInfo()),
|
|
589
|
+
outlet: deps.egressInfo(),
|
|
590
|
+
version: deps.version,
|
|
591
|
+
// Whether the absorbed channel pack is live on this host, and its failure
|
|
592
|
+
// reason when it is not (see the mount in `apply`). The page that renders the
|
|
593
|
+
// channel grid reads this before the pack's own RPC answers.
|
|
594
|
+
channels: deps.channels?.() ?? { state: 'unknown', error: '' },
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* The settings pages' HTTP surface.
|
|
600
|
+
*
|
|
601
|
+
* Every route runs the trust fence first: the connection service's own
|
|
602
|
+
* admission when the composition mounts it (the same check the kernel applies
|
|
603
|
+
* to `/api`), otherwise the structural replica in src/trust.js. The plugin's
|
|
604
|
+
* prefix outranks `/api` in webServer's longest-prefix dispatch, so without
|
|
605
|
+
* this fence these routes would answer callers the app itself would refuse.
|
|
606
|
+
*
|
|
607
|
+
* Only the four surviving pages are served. The ledger and the request log come
|
|
608
|
+
* from the pack over the shell's `connection` RPC, so there is no `/stats` here,
|
|
609
|
+
* and nothing in this fork refreshes a catalog.
|
|
610
|
+
*/
|
|
611
|
+
function createApiRoutes(deps) {
|
|
612
|
+
return async function handler(req, res) {
|
|
613
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
614
|
+
const routePath = url.pathname.replace(/^\/api\/our-free-model/, '').replace(/\/+$/, '') || '/'
|
|
615
|
+
const method = String(req.method ?? 'GET').toUpperCase()
|
|
616
|
+
const rejection = rejectionFor(req, deps.connection, deps.onAdmissionRejection)
|
|
617
|
+
const send = (status, payload) => {
|
|
618
|
+
const body = JSON.stringify(payload)
|
|
619
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
620
|
+
res.end(body)
|
|
621
|
+
}
|
|
622
|
+
if (rejection !== undefined) return send(rejection, {
|
|
623
|
+
error: rejection === 401 ? 'unauthorized' : rejection === 503 ? 'admission unavailable' : 'forbidden',
|
|
624
|
+
})
|
|
625
|
+
try {
|
|
626
|
+
if (method === 'GET' && routePath === '/summary') {
|
|
627
|
+
return send(200, buildSummary(deps))
|
|
628
|
+
}
|
|
629
|
+
if (method === 'GET' && routePath === '/outlet') {
|
|
630
|
+
return send(200, await deps.outletStatus())
|
|
631
|
+
}
|
|
632
|
+
if (method === 'GET' && routePath === '/egress/url') {
|
|
633
|
+
return send(200, { url: deps.settings.get().egress?.url ?? '' })
|
|
634
|
+
}
|
|
635
|
+
if (method === 'POST' && routePath === '/settings') {
|
|
636
|
+
const patch = await readJson(req)
|
|
637
|
+
const current = deps.settings.get()
|
|
638
|
+
const next = {}
|
|
639
|
+
if (patch.egress !== undefined) {
|
|
640
|
+
const egressPatch = pick(patch.egress, ['enabled', 'mode', 'url', 'mihomoPath'])
|
|
641
|
+
if (egressPatch.mode !== undefined && egressPatch.mode !== 'subscription' && egressPatch.mode !== 'client') {
|
|
642
|
+
return send(400, { error: 'the egress mode is "subscription" or "client"' })
|
|
643
|
+
}
|
|
644
|
+
for (const key of ['url', 'mihomoPath']) {
|
|
645
|
+
if (egressPatch[key] !== undefined) {
|
|
646
|
+
const value = String(egressPatch[key]).trim()
|
|
647
|
+
if (value.length > 2048) return send(400, { error: `the egress ${key} is too long` })
|
|
648
|
+
egressPatch[key] = value
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
const egress = { ...(current.egress ?? {}), ...egressPatch }
|
|
652
|
+
if (egress.enabled === true && String(egress.url ?? '') === '') {
|
|
653
|
+
return send(400, { error: 'the outlet needs a subscription or proxy URL' })
|
|
654
|
+
}
|
|
655
|
+
next.egress = egress
|
|
656
|
+
}
|
|
657
|
+
deps.settings.update(next)
|
|
658
|
+
deps.settings.flush()
|
|
659
|
+
await deps.syncEgress()
|
|
660
|
+
return send(200, { ok: true, settings: publicSettings(deps.settings.get(), deps.egressInfo()) })
|
|
661
|
+
}
|
|
662
|
+
// The channels' gateway relay (the pack's loopback OpenAI endpoint,
|
|
663
|
+
// re-exposed under this plugin's own key). Status never carries a secret;
|
|
664
|
+
// the key routes are read by the same fence as every other route here.
|
|
665
|
+
if (method === 'GET' && routePath === '/chan-gateway') {
|
|
666
|
+
return send(200, deps.chanRelay.status())
|
|
667
|
+
}
|
|
668
|
+
if (method === 'POST' && routePath === '/chan-gateway/apply') {
|
|
669
|
+
const body = await readJson(req)
|
|
670
|
+
return send(200, await deps.chanRelay.apply(body))
|
|
671
|
+
}
|
|
672
|
+
if (method === 'GET' && routePath === '/chan-gateway/key') {
|
|
673
|
+
return send(200, { key: deps.chanRelay.key() })
|
|
674
|
+
}
|
|
675
|
+
if (method === 'POST' && routePath === '/chan-gateway/rotate') {
|
|
676
|
+
return send(200, { key: deps.chanRelay.rotate() })
|
|
677
|
+
}
|
|
678
|
+
return send(404, { error: 'not found' })
|
|
679
|
+
} catch (error) {
|
|
680
|
+
const status = Number(error?.statusCode)
|
|
681
|
+
return send(Number.isInteger(status) && status >= 400 && status <= 599 ? status : 500, { error: String(error?.message ?? error) })
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
}
|