dsh-sub2api 0.0.0-stage → 0.1.5
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/CHANGELOG.md +54 -0
- package/LICENSE +674 -0
- package/README.md +171 -2
- package/cordis.patch.yml +16 -0
- package/lib/adapter.js +205 -0
- package/lib/client.js +754 -0
- package/lib/config.js +86 -0
- package/lib/constants.js +64 -0
- package/lib/index.js +197 -0
- package/lib/pay.js +243 -0
- package/lib/routes.js +378 -0
- package/lib/schema.js +37 -0
- package/lib/sub2api/api.js +247 -0
- package/lib/sub2api/auth.js +106 -0
- package/lib/sub2api/catalog.js +330 -0
- package/lib/sub2api/provision.js +244 -0
- package/lib/sub2api/session.js +187 -0
- package/lib/tools.js +171 -0
- package/lib/util.js +225 -0
- package/package.json +76 -4
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable login session, stored as a credential record.
|
|
3
|
+
*
|
|
4
|
+
* Why a record rather than a private JSON file: it rides the host's own
|
|
5
|
+
* credential store (`~/.dsh/.credentials.yaml`, mode 0600), disappears with the
|
|
6
|
+
* plugin, and is never enumerated into anything the browser can read. The
|
|
7
|
+
* record's payload is a `grant` blob — the seam treats it as opaque and only
|
|
8
|
+
* this plugin interprets it.
|
|
9
|
+
* @module dsh-sub2api/sub2api/session
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { SESSION_ID, SESSION_SCOPE, TOKEN_REFRESH_LEAD_MS } from "../constants.js";
|
|
13
|
+
import { Sub2ApiError } from "../util.js";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Build the record key. The host brand is a TypeScript-only marker, so a plain
|
|
17
|
+
* `<scope>/<id>` string is accepted at runtime and keeps this module importable
|
|
18
|
+
* outside a running host (tests, tooling).
|
|
19
|
+
*/
|
|
20
|
+
function sessionKey() {
|
|
21
|
+
return `${SESSION_SCOPE}/${SESSION_ID}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** @typedef {{accessToken: string, refreshToken?: string, expiresAt: number, user?: any, email?: string}} Session */
|
|
25
|
+
|
|
26
|
+
export class SessionStore {
|
|
27
|
+
/**
|
|
28
|
+
* @param {object} deps
|
|
29
|
+
* @param {() => any} deps.credentials resolves the host credential provider, may return undefined
|
|
30
|
+
* @param {import("./api.js").Sub2ApiApi} deps.api
|
|
31
|
+
* @param {() => string} deps.apiKeyEnv credential reference holding the API key
|
|
32
|
+
*/
|
|
33
|
+
constructor(deps) {
|
|
34
|
+
this.deps = deps;
|
|
35
|
+
/** In-flight refresh, so concurrent callers share one rotation. */
|
|
36
|
+
this.refreshing = undefined;
|
|
37
|
+
/** Last read, so a settings page render does not hit the store repeatedly. */
|
|
38
|
+
this.cached = undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** @returns {Promise<Session | undefined>} */
|
|
42
|
+
async read() {
|
|
43
|
+
if (this.cached !== undefined) return this.cached;
|
|
44
|
+
const credentials = this.deps.credentials();
|
|
45
|
+
if (credentials === undefined) return undefined;
|
|
46
|
+
const record = await credentials.readRecord(sessionKey());
|
|
47
|
+
const payload = record?.kind === "grant" ? record.payload : undefined;
|
|
48
|
+
if (!payload || typeof payload !== "object") return undefined;
|
|
49
|
+
this.cached = /** @type {Session} */ (payload);
|
|
50
|
+
return this.cached;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** @param {Session} session */
|
|
54
|
+
async write(session) {
|
|
55
|
+
const credentials = this.deps.credentials();
|
|
56
|
+
if (credentials === undefined) {
|
|
57
|
+
throw new Sub2ApiError("当前运行环境没有凭据服务,无法保存登录状态", {
|
|
58
|
+
code: "no_credentials_service",
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
const next = normalize(session);
|
|
62
|
+
await credentials.modifyRecord(sessionKey(), async () => ({ kind: "grant", payload: next }));
|
|
63
|
+
this.cached = next;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async clear() {
|
|
67
|
+
const credentials = this.deps.credentials();
|
|
68
|
+
this.cached = undefined;
|
|
69
|
+
if (credentials === undefined) return;
|
|
70
|
+
await credentials.deleteRecord(sessionKey());
|
|
71
|
+
try {
|
|
72
|
+
await credentials.unset(this.deps.apiKeyEnv());
|
|
73
|
+
} catch {
|
|
74
|
+
// A missing reference is not a failure worth surfacing on logout.
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* A usable access token, refreshing shortly before expiry.
|
|
80
|
+
* @param {AbortSignal} [signal]
|
|
81
|
+
* @returns {Promise<string>}
|
|
82
|
+
* @throws {Sub2ApiError} `not_logged_in` when there is no session at all
|
|
83
|
+
*/
|
|
84
|
+
async accessToken(signal) {
|
|
85
|
+
const session = await this.read();
|
|
86
|
+
if (session === undefined) {
|
|
87
|
+
throw new Sub2ApiError("尚未登录 Sub2API", { code: "not_logged_in" });
|
|
88
|
+
}
|
|
89
|
+
if (session.expiresAt > Date.now() + TOKEN_REFRESH_LEAD_MS || !session.refreshToken) {
|
|
90
|
+
return session.accessToken;
|
|
91
|
+
}
|
|
92
|
+
return this.refresh(session, signal);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Rotate the access token. Concurrent callers share one request: two
|
|
97
|
+
* rotations of the same refresh token would invalidate each other upstream.
|
|
98
|
+
* @param {Session} [session]
|
|
99
|
+
* @param {AbortSignal} [signal]
|
|
100
|
+
* @returns {Promise<string>}
|
|
101
|
+
*/
|
|
102
|
+
async refresh(session, signal) {
|
|
103
|
+
if (this.refreshing !== undefined) return this.refreshing;
|
|
104
|
+
const current = session ?? (await this.read());
|
|
105
|
+
if (current === undefined || !current.refreshToken) {
|
|
106
|
+
throw new Sub2ApiError("登录状态已失效,请重新登录", { code: "not_logged_in" });
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
this.refreshing = (async () => {
|
|
110
|
+
try {
|
|
111
|
+
const fresh = await this.deps.api.refresh(current.refreshToken);
|
|
112
|
+
const next = normalize({
|
|
113
|
+
accessToken: fresh.access_token,
|
|
114
|
+
refreshToken: fresh.refresh_token ?? current.refreshToken,
|
|
115
|
+
expiresAt: expiresAtOf(fresh),
|
|
116
|
+
user: fresh.user ?? current.user,
|
|
117
|
+
email: current.email,
|
|
118
|
+
});
|
|
119
|
+
await this.write(next);
|
|
120
|
+
return next.accessToken;
|
|
121
|
+
} catch (error) {
|
|
122
|
+
// A rejected refresh token means the session is unrecoverable; drop it
|
|
123
|
+
// rather than leaving the panel looping on a dead token.
|
|
124
|
+
if (error instanceof Sub2ApiError && error.status === 401) await this.clear();
|
|
125
|
+
throw error;
|
|
126
|
+
} finally {
|
|
127
|
+
this.refreshing = undefined;
|
|
128
|
+
}
|
|
129
|
+
})();
|
|
130
|
+
|
|
131
|
+
return this.refreshing;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** @returns {Promise<string | undefined>} the stored API key, if any */
|
|
135
|
+
async apiKey() {
|
|
136
|
+
const credentials = this.deps.credentials();
|
|
137
|
+
if (credentials === undefined) return undefined;
|
|
138
|
+
const resolved = await credentials.resolve(this.deps.apiKeyEnv());
|
|
139
|
+
const value = typeof resolved?.value === "string" ? resolved.value : undefined;
|
|
140
|
+
return value === undefined || value === "" ? undefined : value;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** @param {string} value */
|
|
144
|
+
async setApiKey(value) {
|
|
145
|
+
const credentials = this.deps.credentials();
|
|
146
|
+
if (credentials === undefined) {
|
|
147
|
+
throw new Sub2ApiError("当前运行环境没有凭据服务,无法保存 API Key", {
|
|
148
|
+
code: "no_credentials_service",
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
await credentials.set(this.deps.apiKeyEnv(), value);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Normalize whatever the site returned into the stored shape. */
|
|
156
|
+
export function normalize(input) {
|
|
157
|
+
const expiresIn = typeof input.expiresIn === "number" ? input.expiresIn : undefined;
|
|
158
|
+
return {
|
|
159
|
+
accessToken: String(input.accessToken ?? ""),
|
|
160
|
+
refreshToken: input.refreshToken ? String(input.refreshToken) : undefined,
|
|
161
|
+
expiresAt: Number.isFinite(input.expiresAt) ? Number(input.expiresAt) : Date.now() + 3600_000,
|
|
162
|
+
user: input.user,
|
|
163
|
+
email: input.email ?? input.user?.email,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Convert an auth response's relative `expires_in` into an absolute deadline.
|
|
169
|
+
* @param {{expires_in?: number}} response
|
|
170
|
+
* @returns {number}
|
|
171
|
+
*/
|
|
172
|
+
function expiresAtOf(response) {
|
|
173
|
+
const seconds =
|
|
174
|
+
typeof response.expires_in === "number" && response.expires_in > 0 ? response.expires_in : 3600;
|
|
175
|
+
return Date.now() + seconds * 1000;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Build a session from a login/register payload. */
|
|
179
|
+
export function sessionFromAuth(auth, email) {
|
|
180
|
+
return normalize({
|
|
181
|
+
accessToken: auth.access_token,
|
|
182
|
+
refreshToken: auth.refresh_token,
|
|
183
|
+
expiresAt: expiresAtOf(auth),
|
|
184
|
+
user: auth.user,
|
|
185
|
+
email,
|
|
186
|
+
});
|
|
187
|
+
}
|
package/lib/tools.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent-facing tools.
|
|
3
|
+
*
|
|
4
|
+
* These are deliberately read-only: the model may report the account's state,
|
|
5
|
+
* but it must never spend the user's balance or rotate a key on its own. A user
|
|
6
|
+
* who asks "我还有多少额度" gets an answer without opening the panel.
|
|
7
|
+
* @module dsh-sub2api/tools
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
11
|
+
import { maskSecret } from "./util.js";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @param {object} deps
|
|
15
|
+
* @param {import("./sub2api/api.js").Sub2ApiApi} deps.api
|
|
16
|
+
* @param {import("./sub2api/session.js").SessionStore} deps.session
|
|
17
|
+
* @param {import("./sub2api/catalog.js").ModelCatalog} deps.catalog
|
|
18
|
+
* @param {() => any} deps.cfg
|
|
19
|
+
* @returns {any[]}
|
|
20
|
+
*/
|
|
21
|
+
export function buildTools(deps) {
|
|
22
|
+
return [statusTool(deps), modelsTool(deps)];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Whether the account is wired up, and what it currently holds. */
|
|
26
|
+
function statusTool(deps) {
|
|
27
|
+
return defineTool({
|
|
28
|
+
name: "sub2api_status",
|
|
29
|
+
description:
|
|
30
|
+
"查看 Sub2API(sub.pscly.cc 中转站)在本机的接入状态:是否已登录、账号邮箱、余额、API 密钥是否已保存(只返回掩码)、订阅进度、已同步的模型数量。不会返回任何明文密钥。",
|
|
31
|
+
parameters: {},
|
|
32
|
+
output: {
|
|
33
|
+
schema: {
|
|
34
|
+
type: "object",
|
|
35
|
+
additionalProperties: false,
|
|
36
|
+
properties: {
|
|
37
|
+
ok: { type: "boolean", required: true },
|
|
38
|
+
message: { type: "string", required: true },
|
|
39
|
+
loggedIn: { type: "boolean" },
|
|
40
|
+
email: { type: "string" },
|
|
41
|
+
balance: { type: "number" },
|
|
42
|
+
hasKey: { type: "boolean" },
|
|
43
|
+
keyMasked: { type: "string" },
|
|
44
|
+
modelCount: { type: "number" },
|
|
45
|
+
apiBase: { type: "string" },
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
render: (_args, value) => [{ type: "text", text: String(value.message ?? "") }],
|
|
49
|
+
},
|
|
50
|
+
async execute() {
|
|
51
|
+
const stored = await deps.session.read();
|
|
52
|
+
const apiKey = await deps.session.apiKey();
|
|
53
|
+
await deps.catalog.load();
|
|
54
|
+
|
|
55
|
+
if (stored === undefined) {
|
|
56
|
+
return {
|
|
57
|
+
ok: false,
|
|
58
|
+
message: `尚未登录 Sub2API。请让用户在 DSH 的 设置 → Sub2API 面板用一个邮箱和密码完成登录或注册(插件会自动创建名为 dsh 的密钥)。站点:${deps.cfg().apiBase}`,
|
|
59
|
+
loggedIn: false,
|
|
60
|
+
hasKey: false,
|
|
61
|
+
modelCount: deps.catalog.visible().length,
|
|
62
|
+
apiBase: deps.cfg().apiBase,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const token = await deps.session.accessToken().catch(() => undefined);
|
|
67
|
+
const profile = token === undefined ? undefined : await safe(() => deps.api.profile(token));
|
|
68
|
+
const balance = typeof profile?.balance === "number" ? profile.balance : undefined;
|
|
69
|
+
const email = String(profile?.email ?? stored.email ?? "");
|
|
70
|
+
|
|
71
|
+
const parts = [`已登录 ${email || "(未知邮箱)"}`];
|
|
72
|
+
parts.push(balance === undefined ? "余额未知" : `余额 $${balance.toFixed(2)}`);
|
|
73
|
+
parts.push(typeof apiKey === "string" && apiKey !== "" ? `密钥 ${maskSecret(apiKey)}` : "尚未创建密钥");
|
|
74
|
+
parts.push(`已同步 ${deps.catalog.visible().length} 个模型`);
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
ok: true,
|
|
78
|
+
message: parts.join(","),
|
|
79
|
+
loggedIn: true,
|
|
80
|
+
email,
|
|
81
|
+
...(balance === undefined ? {} : { balance }),
|
|
82
|
+
hasKey: typeof apiKey === "string" && apiKey !== "",
|
|
83
|
+
keyMasked: maskSecret(apiKey),
|
|
84
|
+
modelCount: deps.catalog.visible().length,
|
|
85
|
+
apiBase: deps.cfg().apiBase,
|
|
86
|
+
};
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The upstream catalog, so the model can recommend an id instead of guessing. */
|
|
92
|
+
function modelsTool(deps) {
|
|
93
|
+
return defineTool({
|
|
94
|
+
name: "sub2api_models",
|
|
95
|
+
description:
|
|
96
|
+
"列出 Sub2API 中转站当前可用的模型 id(来自上游 /v1/models,与模型选择器一致)。需要先登录。返回 id、显示名、上下文窗口与是否支持图片。",
|
|
97
|
+
parameters: {
|
|
98
|
+
limit: {
|
|
99
|
+
type: "number",
|
|
100
|
+
description: "最多返回多少个模型,默认 50",
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
output: {
|
|
104
|
+
schema: {
|
|
105
|
+
type: "object",
|
|
106
|
+
additionalProperties: false,
|
|
107
|
+
properties: {
|
|
108
|
+
ok: { type: "boolean", required: true },
|
|
109
|
+
message: { type: "string", required: true },
|
|
110
|
+
count: { type: "number" },
|
|
111
|
+
models: {
|
|
112
|
+
type: "array",
|
|
113
|
+
items: {
|
|
114
|
+
type: "object",
|
|
115
|
+
additionalProperties: false,
|
|
116
|
+
properties: {
|
|
117
|
+
id: { type: "string" },
|
|
118
|
+
name: { type: "string" },
|
|
119
|
+
contextWindow: { type: "number" },
|
|
120
|
+
vision: { type: "boolean" },
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
},
|
|
126
|
+
render: (_args, value) => [{ type: "text", text: String(value.message ?? "") }],
|
|
127
|
+
},
|
|
128
|
+
async execute(args) {
|
|
129
|
+
const limit = Math.max(1, Math.min(200, Number(args?.limit) || 50));
|
|
130
|
+
await deps.catalog.load();
|
|
131
|
+
const models = deps.catalog.visible().slice(0, limit);
|
|
132
|
+
|
|
133
|
+
if (models.length === 0) {
|
|
134
|
+
return {
|
|
135
|
+
ok: false,
|
|
136
|
+
message: "还没有同步到任何模型。请在 设置 → Sub2API 面板登录后点「刷新模型」。",
|
|
137
|
+
count: 0,
|
|
138
|
+
models: [],
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return {
|
|
143
|
+
ok: true,
|
|
144
|
+
message: `共 ${deps.catalog.visible().length} 个模型,前 ${models.length} 个:\n${models
|
|
145
|
+
.map((model) => {
|
|
146
|
+
const extras = [];
|
|
147
|
+
if (model.contextWindow !== undefined) extras.push(`${model.contextWindow} tokens`);
|
|
148
|
+
if (model.vision === true) extras.push("图片");
|
|
149
|
+
return `- ${model.id}${extras.length > 0 ? `(${extras.join(",")})` : ""}`;
|
|
150
|
+
})
|
|
151
|
+
.join("\n")}`,
|
|
152
|
+
count: models.length,
|
|
153
|
+
models: models.map((model) => ({
|
|
154
|
+
id: model.id,
|
|
155
|
+
name: model.name,
|
|
156
|
+
...(model.contextWindow === undefined ? {} : { contextWindow: model.contextWindow }),
|
|
157
|
+
...(model.vision === true ? { vision: true } : {}),
|
|
158
|
+
})),
|
|
159
|
+
};
|
|
160
|
+
},
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Run one optional read, mapping a failure to `undefined`. */
|
|
165
|
+
async function safe(run) {
|
|
166
|
+
try {
|
|
167
|
+
return await run();
|
|
168
|
+
} catch {
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
}
|
package/lib/util.js
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small shared helpers: an HTTP JSON client with timeout/cancellation, error types,
|
|
3
|
+
* secret masking and loopback detection. No DSH imports here, so the module is testable
|
|
4
|
+
* on its own.
|
|
5
|
+
* @module dsh-sub2api/util
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** One failed remote or local operation, carrying enough context for a UI message. */
|
|
9
|
+
export class Sub2ApiError extends Error {
|
|
10
|
+
/**
|
|
11
|
+
* @param {string} message human-readable, already redacted
|
|
12
|
+
* @param {object} [options]
|
|
13
|
+
* @param {number} [options.status] HTTP status when the failure came from a response
|
|
14
|
+
* @param {string} [options.code] provider error code or a local discriminant
|
|
15
|
+
* @param {unknown} [options.cause] original error
|
|
16
|
+
*/
|
|
17
|
+
constructor(message, options = {}) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.name = "Sub2ApiError";
|
|
20
|
+
this.status = options.status;
|
|
21
|
+
this.code = options.code;
|
|
22
|
+
if (options.cause !== undefined) this.cause = options.cause;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Whether an unknown value is a Sub2ApiError carrying one of the given codes. */
|
|
27
|
+
export function hasCode(error, ...codes) {
|
|
28
|
+
return error instanceof Sub2ApiError && typeof error.code === "string" && codes.includes(error.code);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Read a Response body as JSON, translating the two sub2api envelopes
|
|
33
|
+
* (`{code, message, data}` for the control plane, plain objects for the gateway).
|
|
34
|
+
* @param {Response} response
|
|
35
|
+
* @returns {Promise<any>} the unwrapped payload
|
|
36
|
+
* @throws {Sub2ApiError} for a non-2xx status or an unusable body
|
|
37
|
+
*/
|
|
38
|
+
export async function readEnvelope(response) {
|
|
39
|
+
const text = await response.text().catch(() => "");
|
|
40
|
+
let body;
|
|
41
|
+
try {
|
|
42
|
+
body = text === "" ? undefined : JSON.parse(text);
|
|
43
|
+
} catch {
|
|
44
|
+
body = undefined;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (!response.ok) {
|
|
48
|
+
throw new Sub2ApiError(readableMessage(body, response.status), {
|
|
49
|
+
status: response.status,
|
|
50
|
+
code: typeof body?.code === "string" ? body.code : `http_${response.status}`,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (body !== undefined && typeof body === "object" && "code" in body) {
|
|
55
|
+
if (body.code !== 0 && body.code !== "0") {
|
|
56
|
+
throw new Sub2ApiError(String(body.message || `provider error ${body.code}`), {
|
|
57
|
+
status: response.status,
|
|
58
|
+
code: typeof body.code === "string" ? body.code : `code_${body.code}`,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
return body.data;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return body;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Perform one JSON request with a timeout and an optional caller signal.
|
|
69
|
+
* @param {string} url absolute URL
|
|
70
|
+
* @param {object} [options]
|
|
71
|
+
* @param {string} [options.method] HTTP method, GET when omitted
|
|
72
|
+
* @param {Record<string,string>} [options.headers] extra headers
|
|
73
|
+
* @param {unknown} [options.body] JSON-serializable request body
|
|
74
|
+
* @param {number} [options.timeoutMs] overall deadline
|
|
75
|
+
* @param {AbortSignal} [options.signal] caller cancellation
|
|
76
|
+
* @param {typeof fetch} [options.fetchImpl] replacement transport for tests
|
|
77
|
+
* @returns {Promise<{status:number, headers:Headers, payload:any}>}
|
|
78
|
+
*/
|
|
79
|
+
export async function requestJson(url, options = {}) {
|
|
80
|
+
const {
|
|
81
|
+
method = "GET",
|
|
82
|
+
headers = {},
|
|
83
|
+
body,
|
|
84
|
+
timeoutMs = 30000,
|
|
85
|
+
signal,
|
|
86
|
+
fetchImpl = fetch,
|
|
87
|
+
} = options;
|
|
88
|
+
|
|
89
|
+
const timeoutSignal = AbortSignal.timeout(Math.max(1, timeoutMs));
|
|
90
|
+
const merged = signal === undefined ? timeoutSignal : AbortSignal.any([signal, timeoutSignal]);
|
|
91
|
+
|
|
92
|
+
const init = {
|
|
93
|
+
method,
|
|
94
|
+
headers: { Accept: "application/json", ...headers },
|
|
95
|
+
signal: merged,
|
|
96
|
+
};
|
|
97
|
+
if (body !== undefined) {
|
|
98
|
+
init.headers = { "Content-Type": "application/json", ...init.headers };
|
|
99
|
+
init.body = JSON.stringify(body);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
let response;
|
|
103
|
+
try {
|
|
104
|
+
response = await fetchImpl(url, init);
|
|
105
|
+
} catch (cause) {
|
|
106
|
+
const aborted = merged.aborted;
|
|
107
|
+
throw new Sub2ApiError(
|
|
108
|
+
aborted ? "请求超时或已取消" : `网络请求失败:${String(cause?.message ?? cause)}`,
|
|
109
|
+
{ code: aborted ? "timeout" : "network", cause },
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const payload = await readEnvelope(response);
|
|
114
|
+
return { status: response.status, headers: response.headers, payload };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Pull a human-readable sentence out of whatever error body came back.
|
|
119
|
+
*
|
|
120
|
+
* Three shapes reach this: sub2api's `{code, message}`, OpenAI's
|
|
121
|
+
* `{error:{message, type}}` (which the gateway uses for key and permission
|
|
122
|
+
* faults), and a bare string. Taking `body.error` verbatim and casting it to a
|
|
123
|
+
* string is how an error surfaces as "[object Object]" in the panel.
|
|
124
|
+
* @param {any} body parsed response body
|
|
125
|
+
* @param {number} status HTTP status, used as the last resort
|
|
126
|
+
* @returns {string}
|
|
127
|
+
*/
|
|
128
|
+
export function readableMessage(body, status) {
|
|
129
|
+
if (typeof body === "string" && body.trim() !== "") return body.trim().slice(0, 500);
|
|
130
|
+
|
|
131
|
+
if (body !== null && typeof body === "object") {
|
|
132
|
+
for (const candidate of [body.message, body.error, body.detail, body.code]) {
|
|
133
|
+
if (typeof candidate === "string" && candidate.trim() !== "" && candidate !== "0") {
|
|
134
|
+
return candidate;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (body.error !== null && typeof body.error === "object") {
|
|
138
|
+
for (const inner of [body.error.message, body.error.type, body.error.code]) {
|
|
139
|
+
if (typeof inner === "string" && inner.trim() !== "") return inner;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return `HTTP ${status}`;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Mask a secret for display: keep a short head and tail so users can tell keys apart.
|
|
149
|
+
* @param {string | undefined} value
|
|
150
|
+
* @returns {string}
|
|
151
|
+
*/
|
|
152
|
+
export function maskSecret(value) {
|
|
153
|
+
if (typeof value !== "string" || value === "") return "";
|
|
154
|
+
if (value.length <= 12) return "…";
|
|
155
|
+
return `${value.slice(0, 6)}…${value.slice(-4)}`;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Reduce a URL to origin + path for logs and error text: query strings may carry tokens.
|
|
160
|
+
* @param {string} url
|
|
161
|
+
* @returns {string}
|
|
162
|
+
*/
|
|
163
|
+
export function safeUrl(url) {
|
|
164
|
+
try {
|
|
165
|
+
const parsed = new URL(url);
|
|
166
|
+
return `${parsed.origin}${parsed.pathname}`;
|
|
167
|
+
} catch {
|
|
168
|
+
return "<invalid url>";
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Whether a request originates from the loopback interface. */
|
|
173
|
+
export function isLoopbackRequest(req) {
|
|
174
|
+
const address = req?.socket?.remoteAddress ?? req?.connection?.remoteAddress ?? "";
|
|
175
|
+
return (
|
|
176
|
+
address === "127.0.0.1" ||
|
|
177
|
+
address === "::1" ||
|
|
178
|
+
address === "::ffff:127.0.0.1" ||
|
|
179
|
+
address.startsWith("127.")
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Serialize a JSON response with no cache. */
|
|
184
|
+
export function writeJson(res, status, body) {
|
|
185
|
+
const text = JSON.stringify(body);
|
|
186
|
+
res.statusCode = status;
|
|
187
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
188
|
+
res.setHeader("Cache-Control", "no-store");
|
|
189
|
+
res.end(text);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Read a bounded JSON request body.
|
|
194
|
+
* @returns {Promise<any | undefined>} parsed body, or undefined for an unusable one
|
|
195
|
+
*/
|
|
196
|
+
export async function readJsonBody(req, limit = 64 * 1024) {
|
|
197
|
+
const chunks = [];
|
|
198
|
+
let size = 0;
|
|
199
|
+
for await (const chunk of req) {
|
|
200
|
+
size += chunk.length;
|
|
201
|
+
if (size > limit) return undefined;
|
|
202
|
+
chunks.push(chunk);
|
|
203
|
+
}
|
|
204
|
+
if (size === 0) return {};
|
|
205
|
+
try {
|
|
206
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
207
|
+
} catch {
|
|
208
|
+
return undefined;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Hostname of this machine, used in the default API key name. */
|
|
213
|
+
export function localHostname() {
|
|
214
|
+
try {
|
|
215
|
+
return String(process.env.HOSTNAME ?? "").trim() || "localhost";
|
|
216
|
+
} catch {
|
|
217
|
+
return "localhost";
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Normalize a base URL: strip trailing slashes and an accidental /v1 suffix. */
|
|
222
|
+
export function normalizeBaseUrl(value) {
|
|
223
|
+
const trimmed = String(value ?? "").trim().replace(/\/+$/, "");
|
|
224
|
+
return trimmed.replace(/\/v1$/, "");
|
|
225
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,78 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-sub2api",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.5",
|
|
4
|
+
"description": "Sub2API provider for DeepSeek Harness: zero-friction signup, auto-provisioned API key, upstream model sync, balance and recharge",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "GPL-3.0-only",
|
|
7
|
+
"main": "./lib/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./lib/index.js",
|
|
10
|
+
"./client": "./lib/client.js",
|
|
11
|
+
"./package.json": "./package.json"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"CHANGELOG.md",
|
|
15
|
+
"README.md",
|
|
16
|
+
"cordis.patch.yml",
|
|
17
|
+
"lib"
|
|
18
|
+
],
|
|
19
|
+
"dsh": {
|
|
20
|
+
"bundle": {
|
|
21
|
+
"patch": "./cordis.patch.yml"
|
|
22
|
+
},
|
|
23
|
+
"client": {
|
|
24
|
+
"inject": [
|
|
25
|
+
"@deepseek-ai/dsh-client-runtime",
|
|
26
|
+
"@deepseek-ai/dsh-client-connection",
|
|
27
|
+
"@deepseek-ai/dsh-client-ui-settings"
|
|
28
|
+
],
|
|
29
|
+
"platform": "web"
|
|
30
|
+
},
|
|
31
|
+
"compatibility": {
|
|
32
|
+
"dsh": ">=0.2.1-rc.2 <0.2.3"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@dsh-ai-providers/core": "0.7.0",
|
|
37
|
+
"@dsh-ai-providers/openai-compatible": "0.7.0"
|
|
38
|
+
},
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"@deepseek-ai/cordis": "~4.1.0",
|
|
41
|
+
"@deepseek-ai/dsh-credentials": ">=0.2.2-rc.1 <0.2.3",
|
|
42
|
+
"@deepseek-ai/dsh-llm": ">=0.2.2-rc.1 <0.2.3",
|
|
43
|
+
"@deepseek-ai/dsh-tools": ">=0.2.2-rc.1 <0.2.3",
|
|
44
|
+
"@deepseek-ai/dsh-web": ">=0.2.2-rc.1 <0.2.3"
|
|
45
|
+
},
|
|
46
|
+
"peerDependenciesMeta": {
|
|
47
|
+
"@deepseek-ai/dsh-tools": {
|
|
48
|
+
"optional": true
|
|
49
|
+
},
|
|
50
|
+
"@deepseek-ai/dsh-web": {
|
|
51
|
+
"optional": true
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
"engines": {
|
|
55
|
+
"node": ">=24.9",
|
|
56
|
+
"dsh": ">=0.2.1-rc.2 <0.2.3"
|
|
57
|
+
},
|
|
58
|
+
"keywords": [
|
|
59
|
+
"dsh",
|
|
60
|
+
"dsh-plugin",
|
|
61
|
+
"deepseek-harness",
|
|
62
|
+
"sub2api",
|
|
63
|
+
"provider",
|
|
64
|
+
"llm",
|
|
65
|
+
"relay",
|
|
66
|
+
"gateway"
|
|
67
|
+
],
|
|
68
|
+
"scripts": {
|
|
69
|
+
"test": "node test/smoke.mjs && node test/edges.mjs && node test/client-load.mjs",
|
|
70
|
+
"test:smoke": "node test/smoke.mjs",
|
|
71
|
+
"test:edges": "node test/edges.mjs",
|
|
72
|
+
"test:client": "node test/client-load.mjs"
|
|
73
|
+
},
|
|
74
|
+
"publishConfig": {
|
|
75
|
+
"access": "public",
|
|
76
|
+
"provenance": false
|
|
77
|
+
}
|
|
78
|
+
}
|