ai-fly 0.1.1 → 0.3.0-alpha.2
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/dist/ai-fly.js +48 -22
- package/dist/args-CSxXW9eD.mjs +69 -0
- package/dist/common-CgxCXeTt.mjs +83 -0
- package/dist/common-CqxqIg6D.mjs +86 -0
- package/dist/config-BlZnFqx7.mjs +59 -0
- package/dist/daemon-DklsEniO.mjs +291 -0
- package/dist/{forget-BEbNwPip.mjs → forget-B17zGwj4.mjs} +3 -2
- package/dist/{sdk-C6xDRbzg.mjs → frames-BDqvhB2Y.mjs} +1 -10
- package/dist/{group-Csy9VmFb.mjs → group-B96IKEDF.mjs} +24 -4
- package/dist/{import-BVAFw5Tx.mjs → import-tilxdbTH.mjs} +8 -6
- package/dist/{join-E1_-Rt-7.mjs → join-DsKUAibH.mjs} +7 -5
- package/dist/{join-B9op0juF.mjs → join-hyqiwEek.mjs} +3 -3
- package/dist/{key-CK77IYXp.mjs → key-BiEp995L.mjs} +2 -2
- package/dist/{key-Bt4EWiuO.mjs → key-CNufbB__.mjs} +4 -3
- package/dist/local-test-C3HGjGY3.mjs +101 -0
- package/dist/models-dev-2UfQoIpQ.mjs +244 -0
- package/dist/{mux-xHl9Jrbi.mjs → mux-CS1zhF4W.mjs} +2 -2
- package/dist/{ports-BQukx7wS.mjs → ports-rRppuBgo.mjs} +3 -2
- package/dist/presets-C73CAMZ6.mjs +55 -0
- package/dist/proxy-D7VMUVEg.mjs +21 -0
- package/dist/{revoke-CyrOzc8t.mjs → revoke-CkpvK33Q.mjs} +5 -4
- package/dist/rewrite-xZHWnyJk.mjs +313 -0
- package/dist/route-test-Oew0CO1U.mjs +60 -0
- package/dist/rpc-contract-5qyWzT5t.mjs +638 -0
- package/dist/{run-Be8H-IRf.mjs → run-DbPXAm6h.mjs} +8 -5
- package/dist/{runtime-Dg4en1D8.mjs → runtime-D_nxUEjd.mjs} +3 -3
- package/dist/secret-SA37VND5.mjs +95 -0
- package/dist/secrets-BYI6ooTJ.mjs +113 -0
- package/dist/secrets-u19-8EyW.mjs +2 -0
- package/dist/{serve-DuyQMeJh.mjs → serve-Be4zdKVj.mjs} +14 -425
- package/dist/{serve-R03mDBwd.mjs → serve-DSBlodTF.mjs} +18 -6
- package/dist/service-B5uORhl3.mjs +232 -0
- package/dist/settings-C1Hb4zwd.mjs +34 -0
- package/dist/settings-DU0YqNDt.mjs +95 -0
- package/dist/{share-DGM2TOft.mjs → share-Cug0944N.mjs} +8 -5
- package/dist/{status-DRaKNvqz.mjs → status-B-j454u2.mjs} +7 -5
- package/dist/{status-W2OS7WB6.mjs → status-SkNsxGnk.mjs} +6 -4
- package/dist/{common-4VeA_3wo.mjs → store-BiTS2FTl.mjs} +3 -73
- package/dist/store-CrTUwskE.mjs +629 -0
- package/dist/test-Bc0OKBAi.mjs +64 -0
- package/package.json +1 -1
- package/dist/common-BULbPtYn.mjs +0 -1295
- package/dist/config-CO3WyW2H.mjs +0 -173
- package/dist/service-Cd4R47n4.mjs +0 -94
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
import { n as ROUTE_LOCAL_PREFIX, s as randomZ32 } from "./rpc-contract-5qyWzT5t.mjs";
|
|
2
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
6
|
+
//#region src/provider/match-pattern.ts
|
|
7
|
+
var MatchPatternError = class extends Error {
|
|
8
|
+
constructor(message) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = "MatchPatternError";
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
/** 花括号组 → 冒号组(兼容两种 URLPattern 文档写法)。 */
|
|
14
|
+
function normalizeMatchPatternSyntax(raw) {
|
|
15
|
+
return raw.replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g, ":$1");
|
|
16
|
+
}
|
|
17
|
+
const compiled = /* @__PURE__ */ new Map();
|
|
18
|
+
function compileMatchPattern(raw) {
|
|
19
|
+
const cached = compiled.get(raw);
|
|
20
|
+
if (cached !== void 0) return cached;
|
|
21
|
+
if (typeof URLPattern !== "function") throw new MatchPatternError("URLPattern is unavailable in this runtime");
|
|
22
|
+
const translated = normalizeMatchPatternSyntax(raw);
|
|
23
|
+
let pattern;
|
|
24
|
+
try {
|
|
25
|
+
pattern = new URLPattern({ pathname: translated });
|
|
26
|
+
} catch (err) {
|
|
27
|
+
throw new MatchPatternError(err.message || "invalid urlpattern");
|
|
28
|
+
}
|
|
29
|
+
compiled.set(raw, pattern);
|
|
30
|
+
return pattern;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* 匹配请求路径(含可选查询串)。返回捕获组(pathname groups);未命中返回
|
|
34
|
+
* null。exec 需要完整 URL——以 http://localhost 为基座构造。
|
|
35
|
+
*/
|
|
36
|
+
function matchRequestPath(pattern, pathname, search) {
|
|
37
|
+
const url = `http://localhost${pathname.startsWith("/") ? pathname : `/${pathname}`}${search === "" ? "" : `?${search}`}`;
|
|
38
|
+
const result = pattern.exec(url);
|
|
39
|
+
if (result === null) return null;
|
|
40
|
+
return { ...result.pathname.groups };
|
|
41
|
+
}
|
|
42
|
+
//#endregion
|
|
43
|
+
//#region src/provider/uri-template.ts
|
|
44
|
+
var UriTemplateError = class extends Error {
|
|
45
|
+
constructor(message) {
|
|
46
|
+
super(message);
|
|
47
|
+
this.name = "UriTemplateError";
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
const OPERATORS = {
|
|
51
|
+
"": {
|
|
52
|
+
first: "",
|
|
53
|
+
sep: ",",
|
|
54
|
+
named: false,
|
|
55
|
+
ifemp: "",
|
|
56
|
+
allowReserved: false
|
|
57
|
+
},
|
|
58
|
+
"+": {
|
|
59
|
+
first: "",
|
|
60
|
+
sep: ",",
|
|
61
|
+
named: false,
|
|
62
|
+
ifemp: "",
|
|
63
|
+
allowReserved: true
|
|
64
|
+
},
|
|
65
|
+
".": {
|
|
66
|
+
first: ".",
|
|
67
|
+
sep: ".",
|
|
68
|
+
named: false,
|
|
69
|
+
ifemp: "",
|
|
70
|
+
allowReserved: false
|
|
71
|
+
},
|
|
72
|
+
"/": {
|
|
73
|
+
first: "/",
|
|
74
|
+
sep: "/",
|
|
75
|
+
named: false,
|
|
76
|
+
ifemp: "",
|
|
77
|
+
allowReserved: false
|
|
78
|
+
},
|
|
79
|
+
";": {
|
|
80
|
+
first: ";",
|
|
81
|
+
sep: ";",
|
|
82
|
+
named: true,
|
|
83
|
+
ifemp: "",
|
|
84
|
+
allowReserved: false
|
|
85
|
+
},
|
|
86
|
+
"?": {
|
|
87
|
+
first: "?",
|
|
88
|
+
sep: "&",
|
|
89
|
+
named: true,
|
|
90
|
+
ifemp: "=",
|
|
91
|
+
allowReserved: false
|
|
92
|
+
},
|
|
93
|
+
"&": {
|
|
94
|
+
first: "&",
|
|
95
|
+
sep: "&",
|
|
96
|
+
named: true,
|
|
97
|
+
ifemp: "=",
|
|
98
|
+
allowReserved: false
|
|
99
|
+
},
|
|
100
|
+
"#": {
|
|
101
|
+
first: "#",
|
|
102
|
+
sep: ",",
|
|
103
|
+
named: false,
|
|
104
|
+
ifemp: "",
|
|
105
|
+
allowReserved: true
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
const UNRESERVED = /[A-Za-z0-9\-._~]/;
|
|
109
|
+
const RESERVED = /[A-Za-z0-9\-._~:\/\?#\[\]@!\$&'()*+,;=]/;
|
|
110
|
+
function encodeValue(value, allowReserved) {
|
|
111
|
+
let out = "";
|
|
112
|
+
for (const ch of value) if (UNRESERVED.test(ch) || allowReserved && RESERVED.test(ch)) out += ch;
|
|
113
|
+
else for (const byte of new TextEncoder().encode(ch)) out += `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
function parseExpression(expr) {
|
|
117
|
+
const opKey = /^[.+\/;?&#]/.test(expr) ? expr[0] : "";
|
|
118
|
+
const body = expr.slice(opKey.length);
|
|
119
|
+
const spec = OPERATORS[opKey];
|
|
120
|
+
const vars = [];
|
|
121
|
+
for (const raw of body.split(",")) {
|
|
122
|
+
const name = raw.replace(/:\d+$/, "").replace(/\*$/, "").trim();
|
|
123
|
+
if (name === "" || !/^[A-Za-z0-9_.%]+$/.test(name)) throw new UriTemplateError(`invalid variable name '${raw}' in expression '{${expr}}'`);
|
|
124
|
+
vars.push({ name });
|
|
125
|
+
}
|
|
126
|
+
if (vars.length === 0) throw new UriTemplateError(`empty expression '{${expr}}'`);
|
|
127
|
+
return {
|
|
128
|
+
op: spec,
|
|
129
|
+
vars
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/** 校验模板(写入期 fail-fast 用):花括号配对 + 全部表达式可解析。 */
|
|
133
|
+
function validateUriTemplate(template) {
|
|
134
|
+
expandUriTemplate(template, {});
|
|
135
|
+
}
|
|
136
|
+
/** RFC 6570 子集扩展。 */
|
|
137
|
+
function expandUriTemplate(template, vars) {
|
|
138
|
+
let out = "";
|
|
139
|
+
let i = 0;
|
|
140
|
+
while (i < template.length) {
|
|
141
|
+
const open = template.indexOf("{", i);
|
|
142
|
+
if (open < 0) {
|
|
143
|
+
out += template.slice(i);
|
|
144
|
+
break;
|
|
145
|
+
}
|
|
146
|
+
out += template.slice(i, open);
|
|
147
|
+
const close = template.indexOf("}", open);
|
|
148
|
+
if (close < 0) throw new UriTemplateError(`unbalanced '{' in template '${template}'`);
|
|
149
|
+
const { op, vars: specs } = parseExpression(template.slice(open + 1, close));
|
|
150
|
+
const parts = [];
|
|
151
|
+
let used = false;
|
|
152
|
+
for (const { name } of specs) {
|
|
153
|
+
const raw = vars[name];
|
|
154
|
+
if (raw === void 0 || raw === "") continue;
|
|
155
|
+
used = true;
|
|
156
|
+
const value = encodeValue(raw, op.allowReserved);
|
|
157
|
+
parts.push(op.named ? `${name}=${value}` : value);
|
|
158
|
+
}
|
|
159
|
+
if (used) out += op.first + parts.join(op.sep);
|
|
160
|
+
i = close + 1;
|
|
161
|
+
}
|
|
162
|
+
return out;
|
|
163
|
+
}
|
|
164
|
+
//#endregion
|
|
165
|
+
//#region src/provider/store.ts
|
|
166
|
+
const DIR_MODE = 448;
|
|
167
|
+
const FILE_MODE = 384;
|
|
168
|
+
/** 密钥哈希固定 salt(所有提供方实例一致;防直接彩虹表对照 sk-aifly- 空间)。 */
|
|
169
|
+
const KEY_HASH_SALT = "aifly-provider-key-v1:";
|
|
170
|
+
const KEY_MATERIAL_PREFIX = "sk-aifly-";
|
|
171
|
+
/** 存储层错误(用户面 message 为英文 ASCII,直接透出 CLI)。 */
|
|
172
|
+
var StoreError = class extends Error {
|
|
173
|
+
code;
|
|
174
|
+
constructor(code, message) {
|
|
175
|
+
super(message);
|
|
176
|
+
this.name = "StoreError";
|
|
177
|
+
this.code = code;
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
const SERVICE_MATCH_STORE_SCHEMA = z.strictObject({
|
|
181
|
+
type: z.enum([
|
|
182
|
+
"exact",
|
|
183
|
+
"suffix",
|
|
184
|
+
"regex"
|
|
185
|
+
]),
|
|
186
|
+
value: z.string().min(1).max(2048)
|
|
187
|
+
});
|
|
188
|
+
const SERVICE_REWRITE_STORE_SCHEMA = z.strictObject({
|
|
189
|
+
hostHeader: z.string().min(1).max(2048).optional(),
|
|
190
|
+
pathPrefixStrip: z.string().min(1).max(2048).optional(),
|
|
191
|
+
pathPrefixAppend: z.string().min(1).max(2048).optional(),
|
|
192
|
+
headerSet: z.record(z.string().min(1).max(1024), z.string().max(8192)).optional(),
|
|
193
|
+
headerRemove: z.array(z.string().min(1).max(1024)).max(32).optional()
|
|
194
|
+
});
|
|
195
|
+
/** 路径路由(M3-r7):按声明顺序命中的转发规则——prefix 模式(默认,
|
|
196
|
+
* localPrefix → upstreamPrefix)或 pattern 模式(matchPattern URLPattern
|
|
197
|
+
* + template RFC 6570)。forms 为 AI 层标注(可为空)。 */
|
|
198
|
+
const SERVICE_ROUTE_STORE_SCHEMA = z.strictObject({
|
|
199
|
+
forms: z.array(z.enum([
|
|
200
|
+
"openai-chat",
|
|
201
|
+
"openai-responses",
|
|
202
|
+
"anthropic"
|
|
203
|
+
])).max(3),
|
|
204
|
+
mode: z.enum(["prefix", "pattern"]).optional(),
|
|
205
|
+
localPrefix: z.string().min(1).max(2048).optional(),
|
|
206
|
+
upstreamPrefix: z.string().max(2048).optional(),
|
|
207
|
+
matchPattern: z.string().min(1).max(2048).optional(),
|
|
208
|
+
template: z.string().min(1).max(2048).optional()
|
|
209
|
+
});
|
|
210
|
+
const SERVICE_STORE_SCHEMA = z.strictObject({
|
|
211
|
+
serviceId: z.string().min(1).max(128),
|
|
212
|
+
name: z.string().min(1).max(256),
|
|
213
|
+
match: z.array(SERVICE_MATCH_STORE_SCHEMA).max(64),
|
|
214
|
+
upstream: z.string().min(1).max(2048),
|
|
215
|
+
rewrite: SERVICE_REWRITE_STORE_SCHEMA.optional(),
|
|
216
|
+
routes: z.array(SERVICE_ROUTE_STORE_SCHEMA).max(3).optional(),
|
|
217
|
+
defaultPort: z.number().int().min(1).max(65535)
|
|
218
|
+
});
|
|
219
|
+
const GROUP_LIMITS_STORE_SCHEMA = z.strictObject({
|
|
220
|
+
maxConcurrency: z.number().int().min(1).optional(),
|
|
221
|
+
dailyRequests: z.number().int().min(1).optional()
|
|
222
|
+
});
|
|
223
|
+
const GROUP_STORE_SCHEMA = z.strictObject({
|
|
224
|
+
name: z.string().min(1).max(256),
|
|
225
|
+
serviceIds: z.array(z.string().min(1).max(128)).max(256),
|
|
226
|
+
limits: GROUP_LIMITS_STORE_SCHEMA.optional()
|
|
227
|
+
});
|
|
228
|
+
const KEY_STORE_SCHEMA = z.strictObject({
|
|
229
|
+
keyId: z.string().min(1).max(128),
|
|
230
|
+
group: z.string().min(1).max(256),
|
|
231
|
+
hash: z.string().regex(/^[0-9a-f]{64}$/, "key hash must be 64 hex chars"),
|
|
232
|
+
createdAt: z.number().int().min(0),
|
|
233
|
+
revokedAt: z.number().int().min(0).optional()
|
|
234
|
+
});
|
|
235
|
+
const STORE_FILE_SCHEMA = z.strictObject({
|
|
236
|
+
revision: z.number().int().min(0),
|
|
237
|
+
meta: z.strictObject({ alias: z.string().min(1).max(256).optional() }).optional(),
|
|
238
|
+
services: z.array(SERVICE_STORE_SCHEMA).max(1024),
|
|
239
|
+
groups: z.array(GROUP_STORE_SCHEMA).max(256),
|
|
240
|
+
keys: z.array(KEY_STORE_SCHEMA).max(1024)
|
|
241
|
+
});
|
|
242
|
+
function ensurePrivateDir(dir) {
|
|
243
|
+
mkdirSync(dir, {
|
|
244
|
+
recursive: true,
|
|
245
|
+
mode: DIR_MODE
|
|
246
|
+
});
|
|
247
|
+
try {
|
|
248
|
+
chmodSync(dir, DIR_MODE);
|
|
249
|
+
} catch {}
|
|
250
|
+
}
|
|
251
|
+
/** 原子写:同目录 tmp + rename(失败残留 tmp 不影响旧文件)。 */
|
|
252
|
+
function atomicWriteFileSync(path, contents, mode = FILE_MODE) {
|
|
253
|
+
const tmp = `${path}.tmp-${randomBytes(4).toString("hex")}`;
|
|
254
|
+
writeFileSync(tmp, contents, { mode });
|
|
255
|
+
try {
|
|
256
|
+
chmodSync(tmp, mode);
|
|
257
|
+
} catch {}
|
|
258
|
+
renameSync(tmp, path);
|
|
259
|
+
}
|
|
260
|
+
function hashKeyMaterial(material) {
|
|
261
|
+
return createHash("sha256").update(KEY_HASH_SALT + material).digest("hex");
|
|
262
|
+
}
|
|
263
|
+
const PRIVILEGED_PORT_MAX = 1023;
|
|
264
|
+
/** 解析并校验上游 URL:http/https、必须有主机名、禁 userinfo/query/fragment。 */
|
|
265
|
+
function parseUpstreamUrl(upstream) {
|
|
266
|
+
let url;
|
|
267
|
+
try {
|
|
268
|
+
url = new URL(upstream);
|
|
269
|
+
} catch {
|
|
270
|
+
throw new StoreError("invalid", `error: invalid upstream URL: ${upstream}`);
|
|
271
|
+
}
|
|
272
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new StoreError("invalid", "error: upstream URL scheme must be http or https");
|
|
273
|
+
if (url.username !== "" || url.password !== "") throw new StoreError("invalid", "error: upstream URL must not embed credentials (user:pass@)");
|
|
274
|
+
if (url.hostname === "") throw new StoreError("invalid", "error: upstream URL must have a hostname");
|
|
275
|
+
if (url.search !== "" || url.hash !== "") throw new StoreError("invalid", "error: upstream URL must not contain query or fragment");
|
|
276
|
+
return url;
|
|
277
|
+
}
|
|
278
|
+
/** 上游生效端口(显式或缺省scheme端口)。 */
|
|
279
|
+
function upstreamEffectivePort(url) {
|
|
280
|
+
if (url.port !== "") return Number(url.port);
|
|
281
|
+
return url.protocol === "https:" ? 443 : 80;
|
|
282
|
+
}
|
|
283
|
+
var ProviderStore = class ProviderStore {
|
|
284
|
+
dataDir;
|
|
285
|
+
data;
|
|
286
|
+
constructor(dataDir, data) {
|
|
287
|
+
this.dataDir = dataDir;
|
|
288
|
+
this.data = data;
|
|
289
|
+
}
|
|
290
|
+
static filePath(dataDir) {
|
|
291
|
+
return join(dataDir, "services.json");
|
|
292
|
+
}
|
|
293
|
+
/** 打开(不存在则初始化空存储);损坏/非法文件抛 StoreError(corrupt)。 */
|
|
294
|
+
static open(dataDir) {
|
|
295
|
+
ensurePrivateDir(dataDir);
|
|
296
|
+
const path = ProviderStore.filePath(dataDir);
|
|
297
|
+
if (!existsSync(path)) return new ProviderStore(dataDir, {
|
|
298
|
+
revision: 0,
|
|
299
|
+
services: [],
|
|
300
|
+
groups: [],
|
|
301
|
+
keys: []
|
|
302
|
+
});
|
|
303
|
+
let raw;
|
|
304
|
+
try {
|
|
305
|
+
raw = readFileSync(path, "utf8");
|
|
306
|
+
} catch (err) {
|
|
307
|
+
throw new StoreError("corrupt", `error: cannot read ${path}: ${err.message}`);
|
|
308
|
+
}
|
|
309
|
+
let parsed;
|
|
310
|
+
try {
|
|
311
|
+
parsed = JSON.parse(raw);
|
|
312
|
+
} catch {
|
|
313
|
+
throw new StoreError("corrupt", `error: ${path} is not valid JSON (fix or remove it manually)`);
|
|
314
|
+
}
|
|
315
|
+
const result = STORE_FILE_SCHEMA.safeParse(parsed);
|
|
316
|
+
if (!result.success) throw new StoreError("corrupt", `error: ${path} failed validation: ${result.error.message}`);
|
|
317
|
+
return new ProviderStore(dataDir, result.data);
|
|
318
|
+
}
|
|
319
|
+
/** 当前文件 revision(watcher 判重入用)。 */
|
|
320
|
+
get revision() {
|
|
321
|
+
return this.data.revision;
|
|
322
|
+
}
|
|
323
|
+
listServices() {
|
|
324
|
+
return this.data.services.map((s) => ({ ...s }));
|
|
325
|
+
}
|
|
326
|
+
getService(serviceId) {
|
|
327
|
+
const found = this.data.services.find((s) => s.serviceId === serviceId);
|
|
328
|
+
return found === void 0 ? void 0 : { ...found };
|
|
329
|
+
}
|
|
330
|
+
getServiceByName(name) {
|
|
331
|
+
const found = this.data.services.find((s) => s.name === name);
|
|
332
|
+
return found === void 0 ? void 0 : { ...found };
|
|
333
|
+
}
|
|
334
|
+
addService(input) {
|
|
335
|
+
const name = input.name.trim();
|
|
336
|
+
if (name === "" || name.length > 256) throw new StoreError("invalid", "error: service name must be 1..256 chars");
|
|
337
|
+
if (this.data.services.some((s) => s.name === name)) throw new StoreError("duplicate", `error: service '${name}' already exists`);
|
|
338
|
+
if (input.match.length === 0) throw new StoreError("invalid", "error: service must declare at least one match rule");
|
|
339
|
+
if (input.match.length > 64) throw new StoreError("invalid", "error: service match rules exceed 64 entries");
|
|
340
|
+
for (const rule of input.match) if (rule.type === "regex") try {
|
|
341
|
+
new RegExp(rule.value);
|
|
342
|
+
} catch (err) {
|
|
343
|
+
throw new StoreError("invalid", `error: invalid regex '${rule.value}': ${err.message}`);
|
|
344
|
+
}
|
|
345
|
+
const upstreamUrl = parseUpstreamUrl(input.upstream);
|
|
346
|
+
let defaultPort;
|
|
347
|
+
if (input.defaultPort === void 0) {
|
|
348
|
+
const eff = upstreamEffectivePort(upstreamUrl);
|
|
349
|
+
if (eff <= PRIVILEGED_PORT_MAX) throw new StoreError("invalid", `error: upstream port ${eff} is privileged; declare an explicit consumer-side default port (--port <n>)`);
|
|
350
|
+
defaultPort = eff;
|
|
351
|
+
} else {
|
|
352
|
+
if (!Number.isInteger(input.defaultPort) || input.defaultPort < 1 || input.defaultPort > 65535) throw new StoreError("invalid", "error: default port must be an integer in 1..65535");
|
|
353
|
+
defaultPort = input.defaultPort;
|
|
354
|
+
}
|
|
355
|
+
const rewrite = input.rewrite === void 0 ? void 0 : normalizeRewrite(input.rewrite);
|
|
356
|
+
const routes = normalizeRoutes(input.routes);
|
|
357
|
+
let serviceId;
|
|
358
|
+
do
|
|
359
|
+
serviceId = randomZ32(8);
|
|
360
|
+
while (this.data.services.some((s) => s.serviceId === serviceId));
|
|
361
|
+
const service = {
|
|
362
|
+
serviceId,
|
|
363
|
+
name,
|
|
364
|
+
match: input.match.map((m) => ({ ...m })),
|
|
365
|
+
upstream: upstreamUrl.href,
|
|
366
|
+
rewrite,
|
|
367
|
+
...routes !== void 0 ? { routes } : {},
|
|
368
|
+
defaultPort
|
|
369
|
+
};
|
|
370
|
+
this.data.services.push(service);
|
|
371
|
+
this.save();
|
|
372
|
+
return { ...service };
|
|
373
|
+
}
|
|
374
|
+
removeService(name) {
|
|
375
|
+
const idx = this.data.services.findIndex((s) => s.name === name);
|
|
376
|
+
if (idx < 0) throw new StoreError("not-found", `error: service '${name}' not found`);
|
|
377
|
+
const [removed] = this.data.services.splice(idx, 1);
|
|
378
|
+
for (const group of this.data.groups) group.serviceIds = group.serviceIds.filter((id) => id !== removed.serviceId);
|
|
379
|
+
this.save();
|
|
380
|
+
}
|
|
381
|
+
listGroups() {
|
|
382
|
+
return this.data.groups.map((g) => ({
|
|
383
|
+
...g,
|
|
384
|
+
serviceIds: [...g.serviceIds]
|
|
385
|
+
}));
|
|
386
|
+
}
|
|
387
|
+
getGroup(name) {
|
|
388
|
+
const found = this.data.groups.find((g) => g.name === name);
|
|
389
|
+
return found === void 0 ? void 0 : {
|
|
390
|
+
...found,
|
|
391
|
+
serviceIds: [...found.serviceIds],
|
|
392
|
+
limits: found.limits ? { ...found.limits } : void 0
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
/** 组内服务视图(引用不存在的服务Id 自动跳过——防手工编辑残留)。 */
|
|
396
|
+
groupServices(groupName) {
|
|
397
|
+
const group = this.getGroup(groupName);
|
|
398
|
+
if (group === void 0) return [];
|
|
399
|
+
const out = [];
|
|
400
|
+
for (const id of group.serviceIds) {
|
|
401
|
+
const svc = this.getService(id);
|
|
402
|
+
if (svc !== void 0) out.push(svc);
|
|
403
|
+
}
|
|
404
|
+
return out;
|
|
405
|
+
}
|
|
406
|
+
addGroup(name, serviceNames, limits) {
|
|
407
|
+
const trimmed = name.trim();
|
|
408
|
+
if (trimmed === "" || trimmed.length > 256) throw new StoreError("invalid", "error: group name must be 1..256 chars");
|
|
409
|
+
if (this.data.groups.some((g) => g.name === trimmed)) throw new StoreError("duplicate", `error: group '${trimmed}' already exists`);
|
|
410
|
+
const serviceIds = this.resolveServiceIds(serviceNames);
|
|
411
|
+
if (limits !== void 0) validateLimits(limits);
|
|
412
|
+
const group = {
|
|
413
|
+
name: trimmed,
|
|
414
|
+
serviceIds,
|
|
415
|
+
limits: limits === void 0 ? void 0 : { ...limits }
|
|
416
|
+
};
|
|
417
|
+
this.data.groups.push(group);
|
|
418
|
+
this.save();
|
|
419
|
+
return {
|
|
420
|
+
...group,
|
|
421
|
+
serviceIds: [...serviceIds]
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
/** 更新既有分组的服务引用(整表替换;未知服务名报错)。 */
|
|
425
|
+
setGroupServices(name, serviceNames) {
|
|
426
|
+
const group = this.data.groups.find((g) => g.name === name);
|
|
427
|
+
if (group === void 0) throw new StoreError("not-found", `error: group '${name}' not found`);
|
|
428
|
+
group.serviceIds = this.resolveServiceIds(serviceNames);
|
|
429
|
+
this.save();
|
|
430
|
+
return {
|
|
431
|
+
...group,
|
|
432
|
+
serviceIds: [...group.serviceIds]
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
/** 更新分组限额(undefined = 清除限额变无限)。 */
|
|
436
|
+
setGroupLimits(name, limits) {
|
|
437
|
+
const group = this.data.groups.find((g) => g.name === name);
|
|
438
|
+
if (group === void 0) throw new StoreError("not-found", `error: group '${name}' not found`);
|
|
439
|
+
if (limits !== void 0) validateLimits(limits);
|
|
440
|
+
group.limits = limits === void 0 ? void 0 : { ...limits };
|
|
441
|
+
this.save();
|
|
442
|
+
return {
|
|
443
|
+
...group,
|
|
444
|
+
serviceIds: [...group.serviceIds]
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
/** 删除分组(仍有未撤销密钥时拒绝——孤儿密钥会以 key_all_invalid 形态困扰
|
|
448
|
+
* 持钥消费方;先 revoke 再删。Owner 验收 2026-09-10:group 管理对齐 keys)。 */
|
|
449
|
+
removeGroup(name) {
|
|
450
|
+
const index = this.data.groups.findIndex((g) => g.name === name);
|
|
451
|
+
if (index === -1) throw new StoreError("not-found", `error: group '${name}' not found`);
|
|
452
|
+
const activeKeys = this.data.keys.filter((k) => k.group === name && k.revokedAt === void 0);
|
|
453
|
+
if (activeKeys.length > 0) throw new StoreError("conflict", `error: group '${name}' still has ${activeKeys.length} active key(s) - revoke them first`);
|
|
454
|
+
this.data.groups.splice(index, 1);
|
|
455
|
+
this.save();
|
|
456
|
+
}
|
|
457
|
+
resolveServiceIds(serviceNames) {
|
|
458
|
+
const serviceIds = [];
|
|
459
|
+
for (const svcName of serviceNames) {
|
|
460
|
+
const svc = this.getServiceByName(svcName);
|
|
461
|
+
if (svc === void 0) throw new StoreError("not-found", `error: service '${svcName}' not found`);
|
|
462
|
+
if (!serviceIds.includes(svc.serviceId)) serviceIds.push(svc.serviceId);
|
|
463
|
+
}
|
|
464
|
+
return serviceIds;
|
|
465
|
+
}
|
|
466
|
+
listKeys() {
|
|
467
|
+
return this.data.keys.map((k) => ({ ...k }));
|
|
468
|
+
}
|
|
469
|
+
/** 签发:原文仅本次返回,存储只落哈希。 */
|
|
470
|
+
issueKey(groupName) {
|
|
471
|
+
if (this.getGroup(groupName) === void 0) throw new StoreError("not-found", `error: group '${groupName}' not found`);
|
|
472
|
+
let keyId;
|
|
473
|
+
do
|
|
474
|
+
keyId = randomZ32(8);
|
|
475
|
+
while (this.data.keys.some((k) => k.keyId === keyId));
|
|
476
|
+
const key = KEY_MATERIAL_PREFIX + randomZ32(32);
|
|
477
|
+
const createdAt = Date.now();
|
|
478
|
+
this.data.keys.push({
|
|
479
|
+
keyId,
|
|
480
|
+
group: groupName,
|
|
481
|
+
hash: hashKeyMaterial(key),
|
|
482
|
+
createdAt
|
|
483
|
+
});
|
|
484
|
+
this.save();
|
|
485
|
+
return {
|
|
486
|
+
keyId,
|
|
487
|
+
key,
|
|
488
|
+
createdAt
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
/** 撤销(幂等:已撤销为 no-op)。 */
|
|
492
|
+
revokeKey(keyId) {
|
|
493
|
+
const found = this.data.keys.find((k) => k.keyId === keyId);
|
|
494
|
+
if (found === void 0) throw new StoreError("not-found", `error: key '${keyId}' not found`);
|
|
495
|
+
if (found.revokedAt === void 0) {
|
|
496
|
+
found.revokedAt = Date.now();
|
|
497
|
+
this.save();
|
|
498
|
+
}
|
|
499
|
+
return { ...found };
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* 校验密钥原文:SHA-256(salt+原文) 后对全表 timingSafeEqual 扫描(不因命中
|
|
503
|
+
* 提前退出,时序与表内容无关节)。命中后按 revokedAt 区分 valid/revoked。
|
|
504
|
+
*/
|
|
505
|
+
verifyKey(material) {
|
|
506
|
+
const digest = Buffer.from(hashKeyMaterial(material), "hex");
|
|
507
|
+
let match;
|
|
508
|
+
for (const record of this.data.keys) {
|
|
509
|
+
const stored = Buffer.from(record.hash, "hex");
|
|
510
|
+
if (digest.length === stored.length && timingSafeEqual(digest, stored)) match = record;
|
|
511
|
+
}
|
|
512
|
+
if (match === void 0) return { status: "invalid" };
|
|
513
|
+
const located = {
|
|
514
|
+
keyId: match.keyId,
|
|
515
|
+
group: match.group
|
|
516
|
+
};
|
|
517
|
+
return match.revokedAt === void 0 ? {
|
|
518
|
+
status: "valid",
|
|
519
|
+
...located
|
|
520
|
+
} : {
|
|
521
|
+
status: "revoked",
|
|
522
|
+
...located
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
get alias() {
|
|
526
|
+
return this.data.meta?.alias;
|
|
527
|
+
}
|
|
528
|
+
setAlias(alias) {
|
|
529
|
+
const trimmed = alias.trim();
|
|
530
|
+
if (trimmed === "" || trimmed.length > 256) throw new StoreError("invalid", "error: alias must be 1..256 chars");
|
|
531
|
+
this.data.meta = {
|
|
532
|
+
...this.data.meta ?? {},
|
|
533
|
+
alias: trimmed
|
|
534
|
+
};
|
|
535
|
+
this.save();
|
|
536
|
+
}
|
|
537
|
+
/** 只读快照(引擎/测试)。 */
|
|
538
|
+
snapshot() {
|
|
539
|
+
return JSON.parse(JSON.stringify(this.data));
|
|
540
|
+
}
|
|
541
|
+
save() {
|
|
542
|
+
this.data.revision += 1;
|
|
543
|
+
atomicWriteFileSync(ProviderStore.filePath(this.dataDir), `${JSON.stringify(this.data, null, 2)}\n`);
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
function validateLimits(limits) {
|
|
547
|
+
for (const [key, value] of Object.entries(limits)) if (value !== void 0 && (!Number.isInteger(value) || value < 1)) throw new StoreError("invalid", `error: limit '${key}' must be a positive integer`);
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* 路由表规范化(M3-r7):空表→undefined;模式字段按 mode 归一——
|
|
551
|
+
* prefix:localPrefix 补 / 去尾斜杠(缺省按首个 form 规范前缀)+ upstreamPrefix;
|
|
552
|
+
* pattern:matchPattern 编译校验({name}→:name 兼容翻译)+ template RFC 6570
|
|
553
|
+
* 解析校验(写入期 fail-fast,运行期零重复解析)。不做语义限制。
|
|
554
|
+
*/
|
|
555
|
+
function normalizeRoutes(routes) {
|
|
556
|
+
if (routes === void 0) return void 0;
|
|
557
|
+
const cleaned = routes.filter((r) => r !== null && r !== void 0);
|
|
558
|
+
if (cleaned.length === 0) return void 0;
|
|
559
|
+
const out = [];
|
|
560
|
+
for (const route of cleaned) {
|
|
561
|
+
const forms = [...new Set(route.forms ?? [])];
|
|
562
|
+
if (route.mode === "pattern") {
|
|
563
|
+
const matchPattern = route.matchPattern?.trim() ?? "";
|
|
564
|
+
const template = route.template?.trim() ?? "";
|
|
565
|
+
if (matchPattern === "" || template === "") throw new StoreError("invalid", "error: pattern route requires matchPattern and template");
|
|
566
|
+
try {
|
|
567
|
+
compileMatchPattern(matchPattern);
|
|
568
|
+
} catch (err) {
|
|
569
|
+
throw new StoreError("invalid", `error: invalid matchPattern '${matchPattern}': ${err.message}`);
|
|
570
|
+
}
|
|
571
|
+
try {
|
|
572
|
+
validateUriTemplate(template);
|
|
573
|
+
} catch (err) {
|
|
574
|
+
throw new StoreError("invalid", `error: invalid template '${template}': ${err.message}`);
|
|
575
|
+
}
|
|
576
|
+
out.push({
|
|
577
|
+
forms,
|
|
578
|
+
mode: "pattern",
|
|
579
|
+
matchPattern,
|
|
580
|
+
template
|
|
581
|
+
});
|
|
582
|
+
continue;
|
|
583
|
+
}
|
|
584
|
+
let local = route.localPrefix?.trim() ?? "";
|
|
585
|
+
if (local !== "") {
|
|
586
|
+
if (!local.startsWith("/")) local = `/${local}`;
|
|
587
|
+
local = local.replace(/\/+$/, "");
|
|
588
|
+
}
|
|
589
|
+
if (local === "") local = ROUTE_LOCAL_PREFIX[forms[0] ?? "openai-chat"];
|
|
590
|
+
let up = route.upstreamPrefix?.trim() ?? "";
|
|
591
|
+
if (up !== "") {
|
|
592
|
+
if (!up.startsWith("/")) up = `/${up}`;
|
|
593
|
+
up = up.replace(/\/+$/, "");
|
|
594
|
+
}
|
|
595
|
+
out.push({
|
|
596
|
+
forms,
|
|
597
|
+
localPrefix: local,
|
|
598
|
+
upstreamPrefix: up
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
return out;
|
|
602
|
+
}
|
|
603
|
+
function normalizeRewrite(rewrite) {
|
|
604
|
+
const out = {};
|
|
605
|
+
if (rewrite.hostHeader !== void 0) {
|
|
606
|
+
if (rewrite.hostHeader.trim() === "") throw new StoreError("invalid", "error: rewrite hostHeader must not be empty");
|
|
607
|
+
out.hostHeader = rewrite.hostHeader.trim();
|
|
608
|
+
}
|
|
609
|
+
for (const field of ["pathPrefixStrip", "pathPrefixAppend"]) {
|
|
610
|
+
const value = rewrite[field];
|
|
611
|
+
if (value === void 0) continue;
|
|
612
|
+
const norm = value.startsWith("/") ? value : `/${value}`;
|
|
613
|
+
if (norm === "/") throw new StoreError("invalid", `error: rewrite ${field} must not be '/'`);
|
|
614
|
+
out[field] = norm;
|
|
615
|
+
}
|
|
616
|
+
if (rewrite.headerSet !== void 0) {
|
|
617
|
+
const headerSet = {};
|
|
618
|
+
for (const [name, value] of Object.entries(rewrite.headerSet)) {
|
|
619
|
+
const lower = name.toLowerCase();
|
|
620
|
+
if (lower === "") throw new StoreError("invalid", "error: rewrite headerSet name must not be empty");
|
|
621
|
+
headerSet[lower] = value;
|
|
622
|
+
}
|
|
623
|
+
out.headerSet = headerSet;
|
|
624
|
+
}
|
|
625
|
+
if (rewrite.headerRemove !== void 0) out.headerRemove = [...new Set(rewrite.headerRemove.map((n) => n.toLowerCase()))];
|
|
626
|
+
return out;
|
|
627
|
+
}
|
|
628
|
+
//#endregion
|
|
629
|
+
export { parseUpstreamUrl as a, matchRequestPath as c, ensurePrivateDir as i, StoreError as n, expandUriTemplate as o, atomicWriteFileSync as r, compileMatchPattern as s, ProviderStore as t };
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { n as UsageError, r as reportCliError } from "./errors-BGtxPkM7.mjs";
|
|
2
|
+
import { n as parseArgv } from "./args-CSxXW9eD.mjs";
|
|
3
|
+
import { n as consumersRoot, s as listKeyrings } from "./store-BiTS2FTl.mjs";
|
|
4
|
+
import { n as desiredPortFor } from "./ports-pI59MtmI.mjs";
|
|
5
|
+
import { n as testLocalService } from "./local-test-C3HGjGY3.mjs";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
//#region src/cli/commands/consumer/test.ts
|
|
8
|
+
const SPEC = {
|
|
9
|
+
data: {
|
|
10
|
+
type: "string",
|
|
11
|
+
tilde: true
|
|
12
|
+
},
|
|
13
|
+
service: { type: "string" },
|
|
14
|
+
form: { type: "string" },
|
|
15
|
+
content: { type: "string" },
|
|
16
|
+
model: { type: "string" },
|
|
17
|
+
"local-prefix": { type: "string" }
|
|
18
|
+
};
|
|
19
|
+
const FORMS = [
|
|
20
|
+
"openai-chat",
|
|
21
|
+
"openai-responses",
|
|
22
|
+
"anthropic"
|
|
23
|
+
];
|
|
24
|
+
async function run(argv, ctx = {}) {
|
|
25
|
+
try {
|
|
26
|
+
const home = ctx.homedir ?? homedir();
|
|
27
|
+
const { options, positionals } = parseArgv(argv, SPEC, { homedir: home });
|
|
28
|
+
if (positionals.length > 0) throw new UsageError(`error: unexpected argument '${positionals[0]}'`);
|
|
29
|
+
const formRaw = options.form === void 0 ? "openai-chat" : String(options.form);
|
|
30
|
+
if (!FORMS.includes(formRaw)) throw new UsageError(`error: --form must be one of ${FORMS.join(", ")}`);
|
|
31
|
+
const form = formRaw;
|
|
32
|
+
const root = consumersRoot(options.data === void 0 ? void 0 : String(options.data), home);
|
|
33
|
+
const { rings } = listKeyrings(root);
|
|
34
|
+
const flat = rings.flatMap((ring) => ring.services.map((svc) => ({
|
|
35
|
+
ring,
|
|
36
|
+
svc
|
|
37
|
+
})));
|
|
38
|
+
if (flat.length === 0) throw new UsageError("error: no imported services - 'ai-fly import <link>' first");
|
|
39
|
+
const serviceName = options.service === void 0 ? void 0 : String(options.service);
|
|
40
|
+
const target = serviceName === void 0 ? flat[0] : flat.find(({ svc }) => svc.name === serviceName || svc.serviceId === serviceName);
|
|
41
|
+
if (target === void 0) throw new UsageError(`error: service '${serviceName}' not found (imported: ${flat.map((f) => f.svc.name).join(", ")})`);
|
|
42
|
+
const port = desiredPortFor(target.svc, target.ring.ports);
|
|
43
|
+
const result = await testLocalService({
|
|
44
|
+
port,
|
|
45
|
+
form,
|
|
46
|
+
...options["local-prefix"] !== void 0 ? { localPrefix: String(options["local-prefix"]) } : {},
|
|
47
|
+
...options.model !== void 0 ? { model: String(options.model) } : {},
|
|
48
|
+
...options.content !== void 0 ? { content: String(options.content) } : {}
|
|
49
|
+
});
|
|
50
|
+
const out = (line) => {
|
|
51
|
+
process.stdout.write(`${line}\n`);
|
|
52
|
+
};
|
|
53
|
+
out(`${result.ok ? "ok" : "failed"}${result.httpStatus !== void 0 ? ` (HTTP ${result.httpStatus})` : ""} - ${result.latencyMs}ms`);
|
|
54
|
+
out(`POST ${result.request.url}`);
|
|
55
|
+
if (result.error !== void 0) out(`error: ${result.error}`);
|
|
56
|
+
if (result.bodyExcerpt !== void 0) out(result.bodyExcerpt.slice(0, 1200));
|
|
57
|
+
if (!result.ok && result.error !== void 0 && result.error.includes("ECONNREFUSED")) out(`(is the consumer gateway running? start it with 'ai-fly run')`);
|
|
58
|
+
return result.ok ? 0 : 1;
|
|
59
|
+
} catch (err) {
|
|
60
|
+
return reportCliError(err);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
export { run };
|